OpenCode 配置 XAI Router:在 opencode 中使用 Codex 模型

Posted January 10, 2026 by XAI 技术团队 ‐ 4 min read

OpenCode(opencode)是一款面向开发者的终端/全栈编程助手。本文将教你把 opencode 的模型请求统一打到 XAI Router(xairouter),并使用 Codex 模型(如 gpt-5.2-codex)稳定完成编码任务。

提示:如果你只想使用 OpenAI 兼容的 Chat/Completions 模型(如 gpt-4o / gpt-4.1),可直接参考文末「非 Codex 模型的简化配置」。

先决条件

  1. 一个 XAI Router 账户:访问 m.xairouter.com 注册并创建 API Key。
  2. 本地已安装 opencode
  3. 准备好要使用的模型 ID(如 gpt-5.2-codex)。

步骤一:在 XAI Router 创建 API Key

  1. 登录 m.xairouter.com
  2. 进入 API Keys 页面,创建一个新的 Key(建议备注用途,如 opencode)。
  3. 复制保存该 Key,后面会作为 OPENAI_API_KEY 使用。

步骤二:设置环境变量

推荐使用 OPENAI_API_KEY(与 opencode 的 OpenAI 兼容配置保持一致)。

macOS / Linux:

export OPENAI_API_KEY="sk-xxx"

Windows PowerShell:

$env:OPENAI_API_KEY="sk-xxx"

步骤三:配置 opencode(Codex 模型)

创建或覆盖 ~/.config/opencode/opencode.json

cat > ~/.config/opencode/opencode.json << 'EOF'
{
  "$schema": "https://opencode.ai/config.json",
  "model": "openai/gpt-5.2-codex",
  "small_model": "openai/gpt-5.2-codex",
  "provider": {
    "openai": {
      "name": "XAI Router",
      "env": ["OPENAI_API_KEY"],
      "whitelist": ["gpt-5.2", "gpt-5.2-codex"],
      "options": {
        "baseURL": "https://api.xairouter.com"
      },
      "models": {
        "gpt-5.2-codex": {
          "id": "gpt-5.2-codex",
          "name": "gpt-5.2-codex",
          "tool_call": true,
          "reasoning": true
        }
      }
    }
  },
  "share": "disabled"
}
EOF

说明:这里使用 openai Provider + baseURL 指向 https://api.xairouter.com,让 opencode 走 Responses API(Codex 模型需要)。 另外加了 small_modelwhitelist,避免自动回落到其它小模型(如 gpt-5-nano)。


步骤四:启用 Codex 兼容模式(必做)

Codex 的 Responses 接口 不允许 system 消息,并要求 instructionsstore=falseopencode 的 Codex 模式会自动处理这些细节。

你只需要两步:

  1. 写入一个 openai 的 OAuth 占位凭证(用于触发 Codex 模式):
cat > ~/.local/share/opencode/auth.json << 'EOF'
{
  "openai": {
    "type": "oauth",
    "refresh": "dummy",
    "access": "dummy",
    "expires": 0
  }
}
EOF
chmod 600 ~/.local/share/opencode/auth.json
  1. 启动 opencode 时禁用默认插件(避免请求被重写到官方 ChatGPT 端点):
OPENCODE_DISABLE_DEFAULT_PLUGINS=1

步骤五:验证是否生效

opencode debug config
opencode models openai

确认输出里包含:

  • model = openai/gpt-5.2-codex
  • baseURL = https://api.xairouter.com

常见报错与解决

  • Instructions are required
  • Store must be set to false
  • System messages are not allowed
  • Unsupported parameter: max_output_tokens

这些通常表示 未启用 Codex 兼容模式。请确保完成「步骤四」,并用 OPENCODE_DISABLE_DEFAULT_PLUGINS=1 启动。


非 Codex 模型的简化配置(可选)

如果你只使用 Chat/Completions 模型(如 gpt-4o / gpt-4.1),可以将 Provider 改为 OpenAI-compatible:

{
  "$schema": "https://opencode.ai/config.json",
  "model": "xai/gpt-4o-mini",
  "provider": {
    "xai": {
      "name": "XAI Router",
      "npm": "@ai-sdk/openai-compatible",
      "env": ["XAI_API_KEY"],
      "options": {
        "baseURL": "https://api.xairouter.com/v1"
      }
    }
  }
}

这条路径适合常规模型,配置更简单。


完成上述配置后,你的 opencode 即可通过 XAI Router 稳定调用 Codex 模型,密钥统一管理、可观测、可控成本。