回到頂部
應用程式把多家 AI 模型請求集中通過一個可觀測、限流與回滾的 Gateway

Cloudflare AI Gateway REST API:多模型路由實作

用 Cloudflare AI Gateway 的新 REST API 統一呼叫 OpenAI、Anthropic、Google 與 Workers AI。本文實測認證、Unified Billing、BYOK、OpenAI SDK、日誌與支出限制。

內容查核: 來源查核:

如果同一個產品同時呼叫 OpenAI、Anthropic 和 Workers AI,最先失控的往往是金鑰、帳單、日誌與 fallback,而非模型選擇。Cloudflare 2026 年 5 月推出的新 AI Gateway REST API,讓應用程式用同一組 Cloudflare 認證與 API 形狀呼叫多家模型;代價是多一個託管中介層,也要重新決定哪些 prompt、回應與使用者資訊能被記錄。

已經只有單一模型、單一後端且供應商觀測足夠時,直接呼叫原廠 API 較簡單。當你需要跨模型流量統計、每位使用者預算、集中限流或切換供應商,再把 Gateway 放進架構。AI Gateway 屬於託管路由與治理服務;模型參數量、量化或自行架設模型權重不在它的選型範圍。要管理自架模型,仍需另有推論服務與監控。

先分清 REST API、BYOK 與 Workers AI

新 REST API 位於 api.cloudflare.com/client/v4/accounts/{ACCOUNT_ID}/ai/...,以具有 AI Gateway 權限的 Cloudflare API token 放在標準 Authorization: Bearer ... header。第三方模型使用 author/model 名稱,例如 openai/...anthropic/...;Cloudflare 代管認證與 Unified Billing,所以 request 不需要再附 provider key。

Unified Billing 要先購買並載入 Cloudflare credits。Cloudflare 的計費文件目前說明,第三方推論單價依供應商原價轉付,購買 credits 另收 5% 費用。這條路徑適合想集中帳單、減少 provider key 的團隊,但要把 credits 餘額、自動加值與負餘額風險納入營運。

BYOK 則保留自己的 provider 合約與 key。Cloudflare 可把 key 存進 Secrets Store,支援同一 provider 多個 alias 與輪替;provider-native endpoint 位於 gateway.ai.cloudflare.com/v1/{account_id}/{gateway_id}/{provider}/...,Gateway 認證使用 cf-aig-authorization。這和新 REST API 的 URL、header 與計費路徑不同,遷移時不能混用。

Workers AI 模型使用 @cf/author/model 名稱。它不走 Unified Billing,仍依 Workers AI 定價;透過 REST API 路由到特定 Gateway 時,還要加 cf-aig-gateway-id。先決定每條流量屬於 Unified Billing、BYOK 或 Workers AI,再寫共用 client。

第一個 REST API 請求怎麼送?

先建立權限最小化的 Cloudflare API token,準備 account ID,並確認 Unified Billing 有 credits。以下使用 OpenAI-compatible Chat Completions endpoint;model ID 請從 Cloudflare 當下的 Model Catalog 選,不要假設範例型號永久存在。

curl -X POST \
  "https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions" \
  -H "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  -H "Content-Type: application/json" \
  -H "cf-aig-gateway-id: production" \
  -H "cf-aig-collect-log-payload: false" \
  --data '{
    "model": "openai/gpt-4.1-mini",
    "messages": [{"role": "user", "content": "Reply with exactly: gateway-ok"}],
    "max_tokens": 20
  }'

首次 request 若不指定 gateway ID,Cloudflare 會使用帳號的 default gateway;正式環境建議明確指定,避免測試和正式流量混在一起。先驗收 HTTP status、回應格式、model/provider、token、cost、duration 與 log,再加入串流、工具呼叫或 fallback。

OpenAI SDK 要改哪些地方?

對 Chat Completions 或 Responses 相容路徑,主要改 apiKeybaseURLmodel。Cloudflare 的 REST API 文件目前示範:

import OpenAI from "openai";

const client = new OpenAI({
  apiKey: process.env.CLOUDFLARE_API_TOKEN,
  baseURL: `https://api.cloudflare.com/client/v4/accounts/${process.env.CLOUDFLARE_ACCOUNT_ID}/ai/v1`,
  defaultHeaders: {
    "cf-aig-gateway-id": "production",
    "cf-aig-collect-log-payload": "false",
  },
});

const response = await client.chat.completions.create({
  model: "openai/gpt-4.1-mini",
  messages: [{ role: "user", content: "Reply with exactly: gateway-ok" }],
});

相容 API 不等於每家模型的全部參數完全相同。切到 Anthropic、Google 或不同模態時,要用 Cloudflare Model Catalog 與 endpoint 文件確認 schema、串流、工具與輸出欄位。SDK 編譯通過只能證明 request 送得出去,不能證明 provider 行為等價。

四個 endpoint 怎麼選?

POST /ai/run 是通用入口,request 以 model 和各模型的 input schema 組成,可處理文字、影像、TTS、ASR 等模態。想統一所有模態時從它開始,但程式仍要理解不同模型 input。

POST /ai/v1/chat/completions 使用 OpenAI Chat Completions 形狀,適合既有 SDK 與一般 LLM 對話。POST /ai/v1/responses 使用 OpenAI Responses API 形狀,適合以 Responses client 建立的工具或 agent 流程;Workers AI 只有支援該 schema 的模型可用。

POST /ai/v1/messages 使用 Anthropic Messages schema,可路由到 Anthropic 和部分第三方模型,但不支援 @cf/ Workers AI。不要為了「只有一個 endpoint」強迫所有 workload 用同一 schema;統一認證與觀測通常比抹平所有模型差異更實際。

哪些功能真的會自動生效?

Request 經過 Gateway 後會進入同一套 logging、analytics 與政策能力,但每項功能的預設與設定不同。最需要先處理的是 Logging:Cloudflare 的日誌文件說明,gateway 預設會保存 metrics、request 與 response data,其中可能包含 prompt 與模型回應。

不需要保存內容時,可在 Gateway 關閉 logs,單一 request 用 cf-aig-collect-log: false 完全不留 log,或用 cf-aig-collect-log-payload: false 只保留 token、cost、provider、status、duration 等 metadata。這是資料治理設定,不能只靠供應商的 Zero Data Retention。Cloudflare ZDR 目前只套用 Unified Billing 的特定 upstream,且不控制 AI Gateway 自己的 logging。

Caching 會對相同 request 重用 response,適合固定、非個人化且容許舊資料的內容;使用者上下文、即時價格、一次性工具結果與含敏感資料的 prompt 不應隨便 cache。Rate limiting 管請求數,Spend limits 管估算成本;後者達上限時會回 429,也可配 Dynamic Route 降到較便宜模型。Spend tracking 是 eventually consistent,並發 burst 仍可能短暫超過預算。

Guardrails 要在 Gateway 啟用並設定 prompt、response、hazard category 與 flag/block 動作。官方目前提醒它會增加延遲、不支援 streaming,支援語言也有限;繁中產品不能把它當成唯一安全層。內容政策、PII/DLP、工具權限與業務規則仍要在應用層分別測試。

Dynamic Route 與 fallback 怎麼設計?

Dynamic Routes 可把條件、model、rate limit、budget limit、fallback 與 metadata 組成可版本化流程,並支援部署和回滾。官方目前要求 authenticated gateway 與存入 BYOK 的 upstream provider keys;呼叫時可把 dynamic/{route-name} 當 model。

先定義能不能 fallback,再定義 fallback 到哪裡。客服摘要可以在主模型超時後改用次模型;法規判讀、結構化 JSON 或特定工具呼叫若模型行為不同,靜默 fallback 可能比直接失敗更危險。每個 route 都要測正常、429、timeout、provider 5xx、無 credits、Guardrail block 和 schema 不相容。

cf-aig-metadata 標記 app、team、environment 或匿名 user ID,可在 logs、analytics 與 spend limits 分組。不要放 Email、姓名或完整 prompt;Cloudflare 目前每個 request 最多保存五個 metadata 欄位,命名也應先固定。

上線前最小驗收

先把一個低風險 endpoint 的 1% 流量導入新 Gateway,比較直接呼叫與 Gateway 的成功率、首 token 延遲、總延遲、token、provider cost、Cloudflare credits、cache hit 與錯誤分類。接著演練停用 Gateway、切回原 provider endpoint 和撤銷 token。

把 Logging payload、retention、Logpush、cache key、rate limit、spend limit、Guardrails、ZDR、BYOK rotation 和 Dynamic Route version 當成設定檔審查。Cloudflare Dashboard 裡「有功能」不代表目前 policy 符合產品要求。Agent 會連續呼叫模型與工具時,也要把 MCP Gateway 的工具資料流和模型 Gateway 分開治理。

若主要需求是 Vercel AI SDK 與 provider allowlist,可比較 Vercel AI Gateway 治理;需要觀察 agent trace、evaluation 與 runtime policy,則接著看 LangSmith Gateway

FAQ

Cloudflare AI Gateway REST API 一定要有 OpenAI 或 Anthropic key 嗎?

走 Unified Billing 時不需要 provider key,要使用 Cloudflare API token並先載入 credits。走 BYOK provider-native endpoint 時仍需要自己的 provider key,只是可由 Cloudflare Secrets Store 管理。兩條路徑的 URL、header 與帳單不同。

Unified Billing 會比原廠模型價格貴嗎?

Cloudflare 目前表示 provider inference price 不加價轉付,但購買 Unified Billing credits 會收 5% 費用。另有 Workers AI、Guardrails 或其他功能用量時,也要分開查看對應定價。正式預算以當下官方文件和帳單為準。

把 OpenAI baseURL 換掉就完成遷移了嗎?

還沒有。你仍要驗證 model 命名、支援參數、streaming、tools、error schema、retry、timeout、usage、日誌 payload、帳單與 fallback。相容 endpoint 降低 client 改動,不保證所有供應商語意完全一致。

Cloudflare 會保存 prompt 和模型回應嗎?

AI Gateway logging 預設開啟,可能保存 request 與 response payload。可在 Gateway 關閉、以 cf-aig-collect-log: false 跳過整筆 log,或用 cf-aig-collect-log-payload: false 只留 metadata。敏感資料還要評估 provider 端保留與組織規範。

Cloudflare AI Gateway 可以取代自架模型服務嗎?

它處理 API routing、billing、observability 與政策,不負責替你部署任意模型權重。若已有自架推論,仍需自己的 GPU/CPU serving、autoscaling、模型版本、健康檢查與資料治理,再評估是否把 endpoint 接進可支援的 Gateway 路徑。

官方資料

№ · further reading

延伸閱讀