Skip to content
TheChatArchiveThe Chat Archive
o1-mini-2024-09-12· OpenAIAi2 WildChat-4.8M (AI2)

我現在想將Workers AI的api在第三方web ui上使用,我想部屬可以將Workers AI的api接口轉化為Openai api格式的base…

  1. User

    我現在想將Workers AI的api在第三方web ui上使用,我想部屬可以將Workers AI的api接口轉化為Openai api格式的base url,之後我只要在類似lobehub這樣的web ui上,填入base url和api和模型名字就能使用,我應該怎麼寫這個網站代碼呢? 註解:網站我會部屬在Cloudflare Workers上。 註解:這是Workers AI相容於Openai的文件說明

    Use AI Gateway for analytics, caching, and security on requests to Workers AI. REST API

    To interact with a REST API, update the URL used for your request:

    Previous: https://api.cloudflare.com/client/v4/accounts/{account_id}/ai/run/{model_id}
    New: https://gateway.ai.cloudflare.com/v1/{account_id}/{gateway_id}/workers-ai/{model_id}
    

    For these parameters:

    {account_id} is your Cloudflare account ID.
    {gateway_id} refers to the name of your existing AI Gateway.
    {model_id} refers to the model ID of the Workers AI model.
    

    Examples

    First, generate an API token with Workers AI Read access and use it in your request. Request to Workers AI llama model

    curl https://gateway.ai.cloudflare.com/v1/{account_id}/{gateway_id}/workers-ai/@cf/meta/llama-3.1-8b-instruct
    --header 'Authorization: Bearer {cf_api_token}'
    --header 'Content-Type: application/json'
    --data '{"prompt": "What is Cloudflare?"}'

    Request to Workers AI text classification model

    curl https://gateway.ai.cloudflare.com/v1/{account_id}/{gateway_id}/workers-ai/@cf/huggingface/distilbert-sst-2-int8
    --header 'Authorization: Bearer {cf_api_token}'
    --header 'Content-Type: application/json'
    --data '{ "text": "Cloudflare docs are amazing!" }'

    OpenAI compatible endpoints

    Workers AI supports OpenAI compatible endpoints for text generation (/v1/chat/completions) and text embedding models (/v1/embeddings). This allows you to use the same code as you would for your OpenAI commands, but swap in Workers AI easily.

    Request to OpenAI compatible endpoint

    curl https://gateway.ai.cloudflare.com/v1/{account_id}/{gateway_id}/workers-ai/v1/chat/completions
    --header 'Authorization: Bearer {cf_api_token}'
    --header 'Content-Type: application/json'
    --data '{ "model": "@cf/meta/llama-3.1-8b-instruct", "messages": [ { "role": "user", "content": "What is Cloudflare?" } ] } '

    Worker

    To include an AI Gateway within your Worker, add the gateway as an object in your Workers AI request.

    export interface Env { AI: Ai; }

    export default { async fetch(request: Request, env: Env): Promise { const response = await env.AI.run( "@cf/meta/llama-3.1-8b-instruct", { prompt: "Why should you use Cloudflare for your AI inference?", }, { gateway: { id: "{gateway_id}", skipCache: false, cacheTtl: 3360, }, }, ); return new Response(JSON.stringify(response)); }, } satisfies ExportedHandler;

    Workers AI supports the following parameters for AI gateways:

    id string
        Name of your existing AI Gateway. Must be in the same account as your Worker.
    skipCache boolean(default: false)
        Controls whether the request should skip the cache.
    cacheTtl number
        Controls the Cache TTL.
    

    以下這是我部屬在cloudflare Workers的代碼,但是他顯示"error": "AI Gateway responded with 400: {"success":false,"result":[],"messages":[],"error":[{"code":2008,"message":"Invalid provider"}]}", 請問要怎麼修改,請將完整代碼一次列出,因為我是新手,我不會局部修改

    // 配置部分:請替換為您的實際值 const ACCOUNT_ID = 'your_account_id' // 請替換為您的實際賬戶 ID const API_TOKEN = 'your_api_token' // 請替換為您的實際 API 令牌 const AI_GATEWAY_ID = 'your_ai_gateway_id' // 請替換為您的 AI Gateway ID

    // 構建 AI Gateway URL const AI_GATEWAY_URL = https://gateway.ai.cloudflare.com/v1/${ACCOUNT_ID}/${AI_GATEWAY_ID}

    addEventListener('fetch', event => { event.respondWith(handleRequest(event.request)) })

    async function handleRequest(request) { console.log('Received request:', request.url)

    // 處理 CORS 預檢請求 if (request.method === "OPTIONS") { return handleCORS(request) }

    // 獲取請求的路徑和方法 const url = new URL(request.url) const path = url.pathname const method = request.method

    // 處理所有 POST 請求 if (method === 'POST') { try { const body = await request.json()

      // 確保模型名稱格式正確
      if (body.model && !body.model.startsWith('@cf/')) {
        body.model = '@cf/' + body.model
      }
    
      console.log('Sending request to AI Gateway:', JSON.stringify(body))
    
      // 發送請求到 AI Gateway,保持原始路徑
      const gatewayResponse = await fetch(`${AI_GATEWAY_URL}${path}`, {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${API_TOKEN}`,
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(body)
      })
    
      if (!gatewayResponse.ok) {
        const errorText = await gatewayResponse.text()
        console.error('AI Gateway Error:', errorText)
        throw new Error(`AI Gateway responded with ${gatewayResponse.status}: ${errorText}`)
      }
    
      // 獲取 AI Gateway 的響應
      const gatewayResult = await gatewayResponse.json()
    
      console.log('Received response from AI Gateway:', JSON.stringify(gatewayResult))
    
      // 直接返回 AI Gateway 的響應
      return new Response(JSON.stringify(gatewayResult), {
        headers: { 
          'Content-Type': 'application/json',
          'Access-Control-Allow-Origin': '*',
          'Access-Control-Allow-Methods': 'POST, OPTIONS',
          'Access-Control-Allow-Headers': 'Content-Type, Authorization',
        }
      })
    
    } catch (error) {
      console.error('Error:', error)
      return new Response(JSON.stringify({ error: error.message }), {
        status: 500,
        headers: { 
          'Content-Type': 'application/json',
          'Access-Control-Allow-Origin': '*',
        }
      })
    }
    

    }

    // 對於其他請求,返回 404 return new Response('Not Found', { status: 404 }) }

    // 處理 CORS 預檢請求的函數 function handleCORS(request) { return new Response(null, { headers: { 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Methods': 'POST, OPTIONS', 'Access-Control-Allow-Headers': 'Content-Type, Authorization', } }) }

  2. Assistant

    看起來您在設置 Cloudflare Workers 代理以將 Workers AI 的 API 轉換為 OpenAI 兼容的格式時遇到了“Invalid provider”的錯誤。這通常是由於請求的路徑或模型名稱不正確引起的。以下是完整的修正代碼,以及詳細的說明,幫助您正確配置和部署這個代理。

    完整的 Cloudflare Workers 代碼

    請確保替換代碼中的占位符 (your_account_id、your_api_token、your_ai_gateway_id) 為您的實際值。

    // 配置部分:請替換為您的實際值
    const ACCOUNT_ID = 'your_account_id' // 請替換為您的實際賬戶 ID
    const API_TOKEN = 'your_api_token' // 請替換為您的實際 API 令牌
    const AI_GATEWAY_ID = 'your_ai_gateway_id' // 請替換為您的 AI Gateway ID
    
    // 構建 AI Gateway 的基礎 URL
    const AI_GATEWAY_BASE_URL = `https://gateway.ai.cloudflare.com/v1/${ACCOUNT_ID}/${AI_GATEWAY_ID}/workers-ai`
    
    addEventListener('fetch', event => {
      event.respondWith(handleRequest(event.request))
    })
    
    /**
     * 處理傳入的請求
     * @param {Request} request
     * @returns {Promise<Response>}
     */
    async function handleRequest(request) {
      console.log('Received request:', request.url)
    
      // 處理 CORS 預檢請求
      if (request.method === "OPTIONS") {
        return handleCORS(request)
      }
    
      // 獲取請求的路徑和方法
      const url = new URL(request.url)
      let path = url.pathname
      const method = request.method
    
      // 將 /v1/... 的路徑轉換為 /workers-ai/v1/...
      if (path.startsWith('/v1/')) {
        path = `/v1${path}` // 根據需要調整路徑
      } else {
        // 當前僅支持 OpenAI 兼容的 /v1/... 路徑
        return new Response(JSON.stringify({ error: 'Unsupported endpoint' }), {
          status: 400,
          headers: { 
            'Content-Type': 'application/json',
            'Access-Control-Allow-Origin': '*',
          }
        })
      }
    
      // 處理所有 POST 請求
      if (method === 'POST') {
        try {
          const body = await request.json()
    
          // 檢查並修正模型名稱格式
          if (body.model && !body.model.startsWith('@cf/')) {
            // 這裡假設所有模型都在 @cf/meta/ 下,根據實際情況調整
            body.model = `@cf/meta/${body.model}`
          }
    
          console.log('Processed request body:', JSON.stringify(body))
    
          // 發送請求到 AI Gateway,包含 /v1/... 路徑
          const gatewayResponse = await fetch(`${AI_GATEWAY_BASE_URL}${path}`, {
            method: 'POST',
            headers: {
              'Authorization': `Bearer ${API_TOKEN}`,
              'Content-Type': 'application/json',
            },
            body: JSON.stringify(body)
          })
    
          if (!gatewayResponse.ok) {
            const errorText = await gatewayResponse.text()
            console.error('AI Gateway Error:', errorText)
            return new Response(JSON.stringify({ error: `AI Gateway responded with ${gatewayResponse.status}: ${errorText}` }), {
              status: gatewayResponse.status,
              headers: { 
                'Content-Type': 'application/json',
                'Access-Control-Allow-Origin': '*',
              }
            })
          }
    
          // 獲取 AI Gateway 的響應
          const gatewayResult = await gatewayResponse.json()
    
          console.log('Received response from AI Gateway:', JSON.stringify(gatewayResult))
    
          // 返回 AI Gateway 的響應
          return new Response(JSON.stringify(gatewayResult), {
            headers: { 
              'Content-Type': 'application/json',
              'Access-Control-Allow-Origin': '*',
              'Access-Control-Allow-Methods': 'POST, OPTIONS',
              'Access-Control-Allow-Headers': 'Content-Type, Authorization',
            }
          })
    
        } catch (error) {
          console.error('Error:', error)
          return new Response(JSON.stringify({ error: error.message }), {
            status: 500,
            headers: { 
              'Content-Type': 'application/json',
              'Access-Control-Allow-Origin': '*',
            }
          })
        }
      }
    
      // 對於其他請求,返回 404
      return new Response('Not Found', { status: 404 })
    }
    
    /**
     * 處理 CORS 預檢請求
     * @param {Request} request
     * @returns {Response}
     */
    function handleCORS(request) {
      return new Response(null, {
        headers: {
          'Access-Control-Allow-Origin': '*',
          'Access-Control-Allow-Methods': 'POST, OPTIONS',
          'Access-Control-Allow-Headers': 'Content-Type, Authorization',
        }
      })
    }
    

    詳細說明與步驟

    1. 配置部分:

      • ACCOUNT_ID:您的 Cloudflare 賬戶 ID。
      • API_TOKEN:具有 Workers AI Read 與 Write 權限的 API 令牌。請確保此令牌具有正確的權限。
      • AI_GATEWAY_ID:您在 Cloudflare 上配置的 AI Gateway 的 ID。請確保這個 Gateway 已正確設置並指向 Workers AI。
    2. 構建 AI Gateway 的基礎 URL:

      const AI_GATEWAY_BASE_URL = `https://gateway.ai.cloudflare.com/v1/${ACCOUNT_ID}/${AI_GATEWAY_ID}/workers-ai`
      

      這個基礎 URL 將用於轉發所有的 API 請求。

    3. 處理請求:

      • CORS 預檢請求:對於 OPTIONS 方法的請求,回應 CORS 預檢。
      • 路徑處理:
        • 將傳入的 /v1/... 路徑轉換為 /v1/...。根據 Workers AI 的要求,如果需要,可以在路徑前添加 /workers-ai,但根據文檔,已經在基礎 URL 中包含了 /workers-ai。
      • 模型名稱處理:
        • 檢查請求體中的 model 欄位,確保它以 @cf/meta/ 開頭。如果沒有,則自動加上前綴。請根據您實際使用的模型名稱調整這部分邏輯。
      • 轉發請求到 AI Gateway:
        • 使用 fetch 將請求轉發到 AI Gateway,並附上必要的標頭(Authorization 和 Content-Type)。
      • 處理 AI Gateway 的響應:
        • 如果 Gateway 回傳錯誤,將錯誤信息回傳給客戶端。
        • 如果成功,將 Gateway 的響應直接回傳給客戶端。
    4. 錯誤處理:

      • 在請求處理過程中,如果發生任何錯誤,都會回傳 500 狀態碼以及錯誤信息。
    5. CORS 處理:

      • 所有的回應都包括 Access-Control-Allow-Origin: *,允許來自任何來源的請求。如果需要更嚴格的 CORS 策略,請根據需要調整。

    解決 “Invalid provider” 錯誤的方法

    這個錯誤通常是由於 AI Gateway 未能正確識別請求的 provider。以下是幾個可能的原因及解決方法:

    1. 確認 AI_GATEWAY_ID 是否正確:

      • 確保您在代碼中設置的 AI_GATEWAY_ID 與您在 Cloudflare 上配置的 AI Gateway ID 完全一致。
    2. 確認 AI Gateway 是否指向 Workers AI 提供者:

      • 登錄到 Cloudflare 控制台,檢查您配置的 AI Gateway 是否正確選擇了 Workers AI 作為其提供者。
    3. 查看模型名稱是否正確:

      • 確保您在請求中使用的 model 名稱與 Workers AI 中配置的模型名稱完全匹配,並且以 @cf/meta/ 開頭(或根據您的配置進行調整)。
    4. 檢查 API Token 的權限:

      • 確保您的 API Token 具有 Workers AI 的讀寫權限。不正確的權限可能導致 AI Gateway 無法正確處理請求。
    5. 確保路徑正確:

      • 根據 Workers AI 的文檔,OpenAI 兼容的端點應該以 /v1/... 開始並附加到 /workers-ai 路徑下。由於我們在基礎 URL 中已經包含了 /workers-ai,因此傳入的請求路徑應該僅為 /v1/chat/completions 或其他 OpenAI 兼容的端點。
    6. 日誌檢查:

      • 使用 console.log 來檢查傳入的請求路徑和模型名稱,確保它們是正確的。例如:
        console.log('Processed request body:', JSON.stringify(body))
        console.log('Request path:', path)
        
      • 在 Cloudflare Workers 的日誌中檢查這些輸出,確認請求是否被正確處理和轉發。

    部署步驟

    1. 設置 Cloudflare Workers:

      • 登錄到您的 Cloudflare 帳戶,導航到 Workers,並創建一個新的 Worker。
      • 將上述完整代碼粘貼到 Workers 的編輯器中。
    2. 替換配置參數:

      • 將 ACCOUNT_ID、API_TOKEN 和 AI_GATEWAY_ID 替換為您的實際值。
    3. 保存並部署:

      • 保存您的 Worker,並將其部署到一個子域或自定義域。
    4. 測試代理:

      • 使用類似 curl 的工具或 Postman 發送 POST 請求到您的 Worker,模擬 OpenAI API 的請求。例如:
        curl -X POST https://your-worker-domain.com/v1/chat/completions \
          -H 'Authorization: Bearer YOUR_API_KEY' \
          -H 'Content-Type: application/json' \
          -d '{
                "model": "llama-3.1-8b-instruct",
                "messages": [
                  {
                    "role": "user",
                    "content": "What is Cloudflare?"
                  }
                ]
              }'
        
      • 確保回應中沒有錯誤並且返回了期望的結果。
    5. 在第三方 Web UI 上配置:

      • 在 LobeHub 或其他支持 OpenAI API 的 Web UI 中,設置 API 基礎 URL 為您的 Cloudflare Worker 的 URL。
      • 使用您設置的 API Token 進行身份驗證。
      • 指定您在 Workers AI 中配置的模型名稱。

    小結

    通過以上步驟,您應該能夠成功配置並部署一個 Cloudflare Worker,將 Workers AI 的 API 轉換為 OpenAI 兼容的格式。請特別注意配置參數的正確性,以及模型名稱的格式。如果仍然遇到問題,建議檢查 Cloudflare Workers 和 AI Gateway 的日誌,以獲取更多調試資訊。

    如果您有任何進一步的問題,請隨時告訴我!

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.