跳转到内容
搜索文档

Workers AI

最后更新 查看 MarkdownAgent 设置

在发往 Workers AI 的请求上使用 AI Gateway 进行分析、缓存和安全防护。

REST API

使用 REST API 调用 Workers AI 模型。Workers AI 模型在模型名称中使用 @cf/ 前缀,并需要 cf-aig-gateway-id 标头来指定路由通过的 gateway。

Request to Workers AI Kimi modelbash
# 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 "cf-aig-gateway-id: default" \
  --header "Content-Type: application/json" \
  --data '{
    "model": "@cf/moonshotai/kimi-k2.6",
    "messages": [
      {
        "role": "user",
        "content": "What is Cloudflare?"
      }
    ]
  }'

Workers 绑定

你可以使用环境绑定(binding)将 Workers AI 与 AI Gateway 集成。要在 Worker 中包含 AI Gateway,请在 Workers AI 请求中将 gateway 作为对象添加。

export default {
	async fetch(request, env) {
		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));
	},
};
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 Gateway 集成的分步指南,请参阅 AI Gateway 中的集成

Workers AI 支持以下 AI Gateway 参数:

  • id string
    • 现有 AI Gateway 的名称。必须与你的 Worker 位于同一账户。
  • skipCache boolean(default: false)
  • cacheTtl number

这篇文档对您有帮助吗?