OpenCode · 手动配置
v1.18.5GitHub
适用场景
直接配置 OpenCode provider、model 与项目级覆盖
面向读者
需要自定义端点或多 provider 的开发者
TL;DR
配置文件使用 JSON/JSONC → Key 引用环境变量 → model 写 provider/model-id
配置文件
| 范围 | 常用位置 |
|---|---|
| 全局 | ~/.config/opencode/opencode.json |
| 项目级 | 仓库根目录 opencode.json |
| 自定义配置文件 | OPENCODE_CONFIG(指向单个配置文件路径) |
另有 OPENCODE_CONFIG_DIR 环境变量,用于指定额外搜索 agents、commands、modes、plugins 等扩展资源的目录;官方文档未说明它会加载 opencode.json,不要把它当作配置文件的自定义路径。
OpenCode 配置支持 JSON 和 JSONC。不同层会合并,项目级配置会覆盖冲突项。不要在项目文件中写真实 API Key,因为它很容易被提交到仓库。
OpenAI 兼容 custom provider
以下 schema 来自 OpenCode 官方 custom provider 文档;foropencode.com 是第三方网关:
{
"$schema": "https://opencode.ai/config.json",
"provider": {
"foropencode": {
"npm": "@ai-sdk/openai-compatible",
"name": "foropencode (third-party gateway)",
"options": {
"baseURL": "https://foropencode.com/v1",
"apiKey": "{env:FOROPENCODE_API_KEY}"
},
"models": {
"gateway-model-id": {
"name": "gateway-model-id"
}
}
}
},
"model": "foropencode/gateway-model-id"
}export FOROPENCODE_API_KEY="sk-xxx"
opencode{env:VAR} 让 OpenCode 在运行时读取环境变量,避免把 Key 写进配置。模型 ID 应从网关实际模型列表取得。
Anthropic 兼容 custom provider
只有第三方端点明确支持当前 Anthropic Messages 行为时,才使用 Anthropic adapter。以下 @ai-sdk/anthropic 写法是社区常见配置,未见于 OpenCode 官方 Providers 文档的第三方端点示例;字段是否生效以 OpenCode 当前版本与端点方文档为准:
{
"$schema": "https://opencode.ai/config.json",
"provider": {
"gateway-claude": {
"npm": "@ai-sdk/anthropic",
"name": "Third-party Anthropic-compatible gateway",
"options": {
"baseURL": "https://foropencode.com",
"apiKey": "{env:FOROPENCODE_ANTHROPIC_KEY}"
},
"models": {
"gateway-model-id": {
"name": "gateway-model-id"
}
}
}
},
"model": "gateway-claude/gateway-model-id"
}项目级覆盖
项目根目录可只写需要覆盖的非敏感项:
{
"$schema": "https://opencode.ai/config.json",
"model": "foropencode/gateway-model-id"
}不要把 apiKey 或包含 Key 的 OPENCODE_CONFIG_CONTENT 写入仓库、CI 日志或共享 shell 历史。
验证
- 运行
opencode --version - 启动 TUI,用模型选择器确认 provider/model
- 发送不含敏感数据的最小请求
- 401 时检查环境变量名;404/协议错误时向网关确认 Base URL 与 API 类型
- 配置解析失败时从最小 JSON 开始逐项恢复,不把含 Key 的文件粘贴到在线校验站
资料来源:OpenCode Config · OpenCode Providers · anomalyco/opencode(2026-07-26 核对)