跳转到内容
本站为社区维护的非官方中文翻译,与 Cloudflare, Inc. 无关联。本站不提供账户登录,请勿在任何非官方站点输入您的 Cloudflare 账户信息。官方文档:developers.cloudflare.com

自动路由器

最后更新 查看 MarkdownAgent 设置

AI Gateway Auto Router 会为每个请求自动选择 AI 模型。它通过将请求匹配到最适合该任务的模型,在保持响应质量的同时帮助降低成本。

工作原理

对于每个请求,AI Gateway 首先构建符合条件的模型池。它会排除不支持该请求格式或其输入的模型。例如,如果请求包含图像,则只有接受图像输入的模型才符合条件。它还会考虑为 gateway 配置的凭据、计费配置和支出限制。不健康的提供商会被排除,并在恢复后自动重新加入。

随后,分类步骤会分析对话,以估计任务的类型和难度。评分步骤会权衡每个剩余候选模型的预期质量与成本,并按适配度排序。AI Gateway 首先尝试排名最高的模型;如果提供商无法处理该请求,则回退到下一个模型。

快速入门

要使用 Auto Router,请向你的 AI Gateway 发送请求,并用 cloudflare/auto 代替特定提供商的模型。端点和身份验证说明请参阅 Unified API(OpenAI 兼容)。

curl -i -X POST "https://gateway.ai.cloudflare.com/v1/$CLOUDFLARE_ACCOUNT_ID/$CLOUDFLARE_GATEWAY_ID/compat/chat/completions" \
  --header "cf-aig-authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
    "model": "cloudflare/auto",
    "messages": [
      {
        "role": "user",
        "content": "hello"
      }
    ]
  }'

响应标头会显示 Auto Router 选择了哪个模型:

cf-aig-routed-model: openai/gpt-6-luna
cf-aig-routing-reason: cost_optimal_within_pool
cf-aig-routing-decision-id: 91e0b970-33f0-4921-b8dc-127412e7b103

要从 Worker 调用 Auto Router,请使用 AI 绑定 并指定 AI Gateway ID:

const response = await env.AI.run(
	"cloudflare/auto",
	{
		messages: [
			{
				role: "system",
				content:
					"You are a helpful oracle powered by lava lamps. Answer clearly, with a flicker of dry humor.",
			},
			{
				role: "user",
				content: "hello",
			},
		],
	},
	{
		gateway: {
			id: "my-gateway",
		},
	},
);
const response = await env.AI.run(
    "cloudflare/auto",
    {
        messages: [
            {
                role: "system",
                content:
                    "You are a helpful oracle powered by lava lamps. Answer clearly, with a flicker of dry humor.",
            },
            {
                role: "user",
                content: "hello",
            },
        ],
    },
    {
        gateway: {
            id: "my-gateway",
        },
    },
);

会话亲和性

对于多轮对话(例如聊天或编码智能体),请在每个请求中发送 cf-aig-session-id 标头。这样 Auto Router 会在整个 turn 中保持同一模型,从而让请求可以利用提示缓存。一个 turn 是一条用户消息加上后续请求(例如工具调用)。受支持的客户端(例如 OpenCode)会自动执行此操作。

没有 session ID 时,Auto Router 会为每个请求选择模型。同一对话中的请求可能被发往不同模型,因此无法复用提示缓存。

Auto Router 会根据消息历史检测 turn。若要自行标记 turn,请发送 cf-aig-turn-id 标头。若要关闭会话亲和性(包括对受支持客户端),请发送 cf-aig-no-session-affinity: true。

在每个 turn 开始时,仅当预期收益超过失去缓存的成本时,Auto Router 才会切换模型。例如,如果对话从简单问题变为多文件编码任务,Auto Router 可能会切换到能力更强的模型。

标头

Auto Router 支持以下请求标头:

标头 说明
cf-aig-session-id 标识请求所属的会话。用于启用会话亲和性。
cf-aig-turn-id 标识请求所属的 turn。覆盖根据消息历史进行的 turn 检测。
cf-aig-no-session-affinity 设为 true 时,为每个请求选择模型,而不是在该 turn 内固定模型。
cf-aig-allowed-models Auto Router 可从中选择的模型的逗号分隔列表。支持 * 通配符,例如 anthropic/*。
cf-aig-allowed-providers Auto Router 可从中选择的提供商的逗号分隔列表,例如 openai,anthropic。

默认情况下,Auto Router 从一组默认模型中选择。cf-aig-allowed-models 会用你提供的模型替换默认模型。条目可以匹配 Models 中的任何模型,包括附加模型。* 通配符不匹配 /,因此请使用 anthropic/* 而不是 *。如果某个条目不匹配任何模型,AI Gateway 会返回 400 错误。如果同时发送这两个标头,模型必须同时匹配两者。

响应包含描述路由决策的标头。这些标头可帮助你识别所选模型、了解选择原因,并将请求与 AI Gateway 日志关联,以便支持和诊断:

标头 说明
cf-aig-routed-model 为请求提供服务的模型,例如 anthropic/claude-sonnet-5.5。
cf-aig-routing-reason 选择该模型的原因。请参阅路由原因。
cf-aig-routing-decision-id 路由决策标识符。
cf-aig-request-id 请求标识符。

路由原因

cf-aig-routing-reason 标头为以下值之一:

值 说明
cost_optimal_within_pool Auto Router 选择了预期质量与成本平衡最佳的模型。
forced_by_candidate_pool 仅有一个模型符合条件,因此无需选择。
pinned_by_turn Auto Router 复用了该 turn 中较早选择的模型。
fallback_candidate_unavailable 所选模型无法处理该请求,因此 AI Gateway 使用了另一个符合条件的模型。
fallback_key_not_in_candidates 路由决策无效,因此 AI Gateway 在没有该决策的情况下选择了模型。
fallback_router_error 路由器不可用,因此 AI Gateway 在没有它的情况下选择了模型。
fallback_router_timeout 路由器未及时响应,因此 AI Gateway 在没有它的情况下选择了模型。
fallback_unsupported_input 请求没有可分类的文本,因此 AI Gateway 在没有路由器的情况下选择了模型。

模型

Auto Router 从 Cloudflare 管理的模型池中选择。该模型池可能会随时间变化。

默认模型

默认情况下,Auto Router 从以下模型中选择。要提供你自己的模型集,请使用 cf-aig-allowed-models 或 cf-aig-allowed-providers 标头。

模型 提供商
@cf/deepseek-ai/deepseek-v4-flash-0731 workers-ai
anthropic/claude-haiku-5.5 anthropic
anthropic/claude-opus-5.5 anthropic
anthropic/claude-sonnet-5.5 anthropic
moonshotai/kimi-k3 workers-ai
openai/gpt-6-luna openai
openai/gpt-6.1-sol openai
xai/grok-4.7 xai

附加模型

仅当这些模型匹配 cf-aig-allowed-models 或 cf-aig-allowed-providers 时,Auto Router 才会选择它们。

附加模型

模型 提供商
@cf/deepseek-ai/deepseek-v4-pro-0813 workers-ai
@cf/google/gemma-4-26b-a4b-it workers-ai
@cf/moonshotai/kimi-k2.7-code workers-ai
@cf/openai/gpt-oss-20b workers-ai
@cf/qwen/qwen3.8-27b workers-ai
@cf/zai-org/glm-5.2 workers-ai
alibaba/qwen3.8-max alibaba
anthropic/claude-fable-5 anthropic
anthropic/claude-fable-5.1 anthropic
anthropic/claude-opus-4.8 anthropic
anthropic/claude-opus-5 anthropic
anthropic/claude-sonnet-4.6 anthropic
anthropic/claude-sonnet-5 anthropic
fireworks/glm-5.3 fireworks
fireworks/glm-5.3-flash fireworks
google/gemini-3.8-flash google-vertex-ai
minimax/m3 minimax
openai/gpt-5.5 openai
openai/gpt-5.6-luna openai
openai/gpt-5.6-sol openai
openai/gpt-5.6-terra openai
openai/gpt-6-astra openai
openai/gpt-6-sol openai
xai/grok-4.5 xai
xai/grok-4.6 xai

提供商列使用 cf-aig-allowed-providers 所接受的值。

与 OpenCode 一起使用

OpenCode ↗ 可以将 Auto Router 用作自定义模型。设置 CLOUDFLARE_ACCOUNT_ID、CLOUDFLARE_GATEWAY_ID 和 CLOUDFLARE_API_TOKEN 环境变量,然后将以下 opencode.json 文件添加到项目根目录:

opencode.jsonjson
{
    "$schema": "https://opencode.ai/config.json",
    "enabled_providers": ["cloudflare-auto-gateway"],
    "provider": {
        "cloudflare-auto-gateway": {
            "npm": "@ai-sdk/openai-compatible",
            "name": "Cloudflare AI Gateway",
            "options": {
                "baseURL": "https://gateway.ai.cloudflare.com/v1/{env:CLOUDFLARE_ACCOUNT_ID}/{env:CLOUDFLARE_GATEWAY_ID}/compat",
                "apiKey": "",
                "headers": {
                    "cf-aig-authorization": "Bearer {env:CLOUDFLARE_API_TOKEN}"
                }
            },
            "models": {
                "cloudflare/auto": {
                    "name": "Cloudflare Auto",
                    "modalities": {
                        "input": ["text", "image"],
                        "output": ["text"]
                    },
                    "limit": {
                        "context": 1000000,
                        "output": 128000
                    },
                    "options": {
                        "max_completion_tokens": 32000
                    }
                }
            }
        }
    }
}

使用 opencode 启动 OpenCode,然后选择 Cloudflare Auto。更多 OpenCode 配置选项请参阅 OpenCode。

安装 AI Gateway 插件

@cloudflare/aig-opencode-plugin ↗ 插件会显示 Auto Router 为每个请求选择的模型。它需要 OpenCode 1.18.29 或更高版本。要安装它,请运行对应 OpenCode 版本的命令,然后重启 OpenCode:

opencode plugin add @cloudflare/aig-opencode-plugin
opencode plugin @cloudflare/aig-opencode-plugin --global

该插件添加以下功能:

  • AI Gateway 侧边栏部分。 显示当前会话中最新请求的所选模型、session ID、request ID、routing decision ID 和 trace ID。选择该部分即可复制这些值。
  • /aig-show 命令。 打印最新请求的 AI Gateway 标头(包括 cf-aig-routing-reason),而不会向模型发送任何内容。运行 /aig-show --help 可查看选项,例如显示更早的请求或包含请求和响应正文。
  • /aig-capture 命令。 运行 /aig-capture off 或 /aig-capture on 可停止或恢复捕获请求。捕获默认开启。捕获的请求保存在内存中,并在 OpenCode 重启时清除。

这篇文档对您有帮助吗?