本指南将介绍如何设置并使用你的第一个 AI Gateway。
在发送请求之前,你需要准备以下两项:
- Account ID — 在 Cloudflare 仪表板中查找。
- Cloudflare API 令牌 — 创建 API 令牌,并授予
AI Gateway - Read、AI Gateway - Edit和Workers AI - Read权限。
运行以下命令,通过 AI Gateway 发送第一个请求。此示例调用 Workers AI 模型,需要使用 @cf/ 模型前缀和 cf-aig-gateway-id 标头。
# Run `wrangler auth token` to get an auth token to replace $CLOUDFLARE_API_TOKEN,
# and `wrangler whoami` to replace $CLOUDFLARE_ACCOUNT_ID.
curl -X POST "https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions" \
--header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
--header "cf-aig-gateway-id: default" \
--header "Content-Type: application/json" \
--data '{
"model": "@cf/moonshotai/kimi-k2.6",
"messages": [
{
"role": "user",
"content": "What is Cloudflare?"
}
]
}'手动创建 gateway
你也可以通过仪表板或 API 手动创建具有自定义名称和配置的 gateway。
Go to AI Gateway ↗
- 登录 Cloudflare 仪表板 ↗ 并选择你的账户。
- 前往 AI > AI Gateway。
- 选择 Create Gateway(创建网关)。
- 输入 Gateway name(网关名称)。注意:网关名称最多 64 个字符。
- 选择 Create(创建)。
要使用 API 设置 AI Gateway:
-
创建 API token,并授予以下权限:
AI Gateway - ReadAI Gateway - Edit
-
获取你的 Account ID。
-
使用该 API token 和 Account ID,向 Cloudflare API 发送
POST请求。
使用以下选项之一对上游 AI 提供商进行身份验证:
- Unified Billing(统一计费): 使用 AI Gateway 计费来支付和验证推理请求。请参阅统一计费。
- BYOK(存储密钥): 将你的提供商 API 密钥存储在 Cloudflare,AI Gateway 将在运行时包含这些密钥。请参阅 BYOK。
- 请求标头: 像往常一样在请求标头中包含你的提供商 API 密钥(例如
Authorization: Bearer <OPENAI_API_KEY>)。
通过同一个 Cloudflare API 调用任何模型——无论托管在 Cloudflare 上还是第三方提供商。无需提供商 SDK 或 API 密钥——身份验证和计费通过你的 Cloudflare 账户处理。提供三个端点:/ai/run 适用于所有模态,/ai/v1/chat/completions 兼容 OpenAI SDK,/ai/v1/responses 适用于智能体工作流。
# Run `wrangler whoami` to get your account ID to replace $CLOUDFLARE_ACCOUNT_ID,
# and `wrangler auth token` to get an auth token to replace $CLOUDFLARE_API_TOKEN.
curl -X POST "https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions" \
--header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
--header "Content-Type: application/json" \
--data '{
"model": "openai/gpt-4.1-mini",
"messages": [{"role": "user", "content": "What is Cloudflare?"}]
}'请参阅 REST API 了解详情和示例。
如需与特定 AI 提供商直接集成,请使用专用端点,这些端点保留原始提供商的 API 架构,同时添加 AI Gateway 功能。
https://gateway.ai.cloudflare.com/v1/{account_id}/{gateway_id}/{provider}可用提供商:
- OpenAI - GPT 模型和嵌入
- Anthropic - Claude 模型
- Google AI Studio - Gemini 模型
- Workers AI - Cloudflare 推理平台
- AWS Bedrock - Amazon 托管 AI 服务
- Azure OpenAI - Microsoft OpenAI 服务
- 以及更多...
- 了解缓存以加快请求速度并节省成本,以及速率限制以控制应用的扩展方式。
- 探索如何指定模型或提供商回退、速率限制、A/B 测试以提高弹性。
- 了解如何在 Workers AI(我们的 AI 推理服务)上使用低成本开源模型。