OpenAI Codex ↗ 是你在终端中运行的编码智能体。它支持在 config.toml 中定义的自定义模型提供商 ↗。此配置添加一个指向 AI Gateway OpenAI 端点 的提供商,使 Codex 通过 AI Gateway 发送请求。AI Gateway 通过 Unified Billing 为你对模型提供商进行身份验证,因此你传递的是 Cloudflare API 令牌,而不是 OpenAI API 密钥。如果 gateway 受 Cloudflare Access 保护,请参阅与 Cloudflare Access 一起使用。
开始之前,你需要:
- 你的 Cloudflare 账户 ID。查找方法请参阅查找账户和 zone ID。
- 一个 AI Gateway。你可以使用账户的
defaultgateway,或创建 gateway 并使用其 slug。 - 具有
AI Gateway权限的 Cloudflare API 令牌。 - 账户上已为第三方模型加载积分。
- 已安装并更新到最新版本的 Codex ↗。
-
在
~/.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" -
将 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>" -
使用该 profile 启动 Codex 并发送提示。请求现在会通过 AI Gateway 路由。
cloudflare-aigprofile 名称与你创建的cloudflare-aig.config.toml文件对应。codex --profile cloudflare-aig
如果 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 替换为你的自定义域。
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,请参阅验证是否生效。