使用 AI 网关对 Workers AI 的请求进行分析、缓存和安全控制。Workers AI 与 AI 网关无缝集成,允许您通过 API 请求或通过 Workers 脚本的环境绑定执行 AI 推理。绑定通过以最少的设置将请求路由到您的 AI 网关来简化过程。
在向 Workers AI 发出请求时,确保您具有以下内容:
- 您的 AI 网关账户 ID。
- 您的 AI 网关网关名称。
- 一个有效的 Workers AI API 令牌。
- 您要使用的 Workers AI 模型的名称。
要与 REST API 交互,请更新用于请求的 URL:
- 之前:
https://api.cloudflare.com/client/v4/accounts/{account_id}/ai/run/{model_id}
- 现在:
https://gateway.ai.cloudflare.com/v1/{account_id}/{gateway_id}/workers-ai/{model_id}
对于这些参数:
{account_id}
是您的 Cloudflare 账户 ID。{gateway_id}
指您现有的 AI 网关的名称。{model_id}
指 Workers AI 模型的模型 ID。
首先,生成一个具有 Workers AI Read
访问权限的 API 令牌并在您的请求中使用它。
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?"}'
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!" }'
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.
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?" } ] }'
您可以使用环境绑定将 Workers AI 与 AI 网关集成。要在您的 Worker 中包含 AI 网关,请在您的 Workers AI 请求中将网关添加为对象。
export interface Env { AI: Ai;}
export default { async fetch(request: Request, env: Env): Promise<Response> { 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<Env>;
有关使用绑定将 Workers AI 与 AI 网关集成的详细分步指南,请参阅 AI 网关中的集成。
Workers AI 支持以下 AI 网关参数:
id
string- 您现有的 AI 网关的名称。必须与您的 Worker 在同一账户中。
skipCache
boolean(默认:false)- 控制请求是否应跳过缓存。
cacheTtl
number- 控制缓存 TTL。
You can also use the OpenAI-compatible endpoint (/ai-gateway/chat-completion/
) to access Workers AI models using the OpenAI API schema. To do so, send your requests to:
https://gateway.ai.cloudflare.com/v1/{account_id}/{gateway_id}/compat/chat/completions
Specify:
{"model": "workers-ai/{model}"}
- @2025 Cloudflare Ubitools
- Cf Repo