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

OpenAI Codex

最后更新 查看 MarkdownAgent 设置

OpenAI Codex ↗ 是你在终端中运行的编码智能体。它支持在 config.toml 中定义的自定义模型提供商 ↗。此配置添加一个指向 AI Gateway OpenAI 端点 的提供商,使 Codex 通过 AI Gateway 发送请求。AI Gateway 通过 Unified Billing 为你对模型提供商进行身份验证,因此你传递的是 Cloudflare API 令牌,而不是 OpenAI API 密钥。如果 gateway 受 Cloudflare Access 保护,请参阅与 Cloudflare Access 一起使用。

前提条件

开始之前,你需要:

  1. 在 ~/.codex/cloudflare-aig.config.toml 创建 Codex profile ↗ 文件。该 profile 定义一个指向 gateway 的 OpenAI 端点的自定义模型提供商,并从环境变量读取你的 Cloudflare API 令牌。

    将 <ACCOUNT_ID> 和 <GATEWAY_ID> 替换为你的值。可以将 gateway 设为 default,以通过账户的默认 gateway 路由;也可以改为其他 gateway slug。

    ~/.codex/cloudflare-aig.config.tomltoml
    model_provider = "cloudflare-ai-gateway"
    model = "gpt-5.5"
    model_reasoning_effort = "medium"
    
    [model_providers.cloudflare-ai-gateway]
    name = "Cloudflare AI Gateway"
    # Run `wrangler whoami` to get your account ID, then replace <ACCOUNT_ID>.
    # Use `default` for <GATEWAY_ID> to route through your account's default gateway.
    base_url = "https://gateway.ai.cloudflare.com/v1/<ACCOUNT_ID>/<GATEWAY_ID>/openai"
    env_key = "CLOUDFLARE_API_KEY"
    wire_api = "responses"
  2. 将 Cloudflare API 令牌设为 CLOUDFLARE_API_KEY 环境变量。以下命令为当前会话设置该变量。若要持久化,请将其添加到 shell 配置文件(例如 ~/.zshrc 或 ~/.bashrc)。

    将 <CLOUDFLARE_API_KEY> 替换为你的值。

    # Run `wrangler auth token` to get an auth token.
    export CLOUDFLARE_API_KEY="<CLOUDFLARE_API_KEY>"
    # Run `wrangler auth token` to get an auth token.
    $env:CLOUDFLARE_API_KEY = "<CLOUDFLARE_API_KEY>"
  3. 使用该 profile 启动 Codex 并发送提示。请求现在会通过 AI Gateway 路由。cloudflare-aig profile 名称与你创建的 cloudflare-aig.config.toml 文件对应。

    codex --profile cloudflare-aig

与 Cloudflare Access 一起使用

如果 gateway 受 Cloudflare Access 保护,Codex 可以使用短期 Access 令牌进行身份验证,而无需 Cloudflare API 令牌。将提供商指向你的自定义域,并配置提供商的 auth 命令,通过 cloudflared 获取令牌,而不是通过环境变量传递令牌。

更新 Unified Billing 设置中同一个 ~/.codex/cloudflare-aig.config.toml profile,使提供商指向你的自定义域,并使用 cloudflared 进行身份验证。codex --profile cloudflare-aig 中的 cloudflare-aig 指该文件的名称。将 ai-gateway.example.com 替换为你的自定义域。

~/.codex/cloudflare-aig.config.tomltoml
model_provider = "cloudflare-ai-gateway"
model = "gpt-5.5"
model_reasoning_effort = "medium"

[model_providers.cloudflare-ai-gateway]
name = "Cloudflare AI Gateway"
base_url = "https://ai-gateway.example.com/openai"
wire_api = "responses"

[model_providers.cloudflare-ai-gateway.auth]
command = "cloudflared"
args = ["access", "login", "--no-verbose", "https://ai-gateway.example.com"]
timeout_ms = 30000
refresh_interval_ms = 0

与上一节的 Unified Billing 设置相比,自定义域替换了 base_url 中的账户 ID 和 gateway ID,auth 块替换了 env_key。

使用该 profile 启动 Codex:

codex --profile cloudflare-aig

首次请求会打开身份提供商的登录流程。完成身份验证后,请求会通过 AI Gateway 路由,并将你的 Access 身份作为 cf.user_id 附加。

要确认流量已到达 AI Gateway,请参阅验证是否生效。

这篇文档对您有帮助吗?