Asia/Shanghai
March 15, 2026

OpenCode + Google Vertex: Free Gemini Pro 3.1 Setup

OpenCode + Google Vertex:免费 Gemini Pro 3.1 配置指南

Mingjian Shao
OpenCode + Google Vertex: Free Gemini Pro 3.1 Setup
Get Gemini 3.1 Pro running in OpenCode for free via Google Vertex AI — $300 trial credit + $10/month developer benefit, with a proxy fix that actually works in mainland China.
OpenCode lets you configure any AI provider as a backend. Google Vertex AI gives you access to Gemini 3.1 Pro with $300 free trial credit (new GCP accounts) plus $10/month from the Google Developer Program.This post covers the complete setup: GCP project, auth, OpenCode config, and the proxy fix required if you're in mainland China.
If you use an AI coding assistant, paste this and let it do everything:
Markdown
I want to set up Google Vertex AI in OpenCode to use Gemini 3.1 Pro for free.
Reference: https://mjshao.fun/blog/opencode-vertex-gemini-pro

My setup:
- OS: [macOS / Linux]
- OpenCode config path: [~/.config/opencode/opencode.json]
- GCP project ID: [ask me]
- Service account JSON key path: [ask me]
- In mainland China (need proxy fix): [yes / no]
- Proxy address if yes: [http://127.0.0.1:7890]
- OpenCode launched as launchctl service: [yes / no]

Steps:
1. Install @ai-sdk/google-vertex in OpenCode's node_modules
2. Add "vertex" provider block to opencode.json with SA JSON key auth
3. If in China: add NODE_OPTIONS=--use-env-proxy to ~/.zshenv
4. If launchctl service: create ~/.bin/opencode-server wrapper script with proxy env vars, update plist ProgramArguments
5. Verify connectivity: node -e https.get test against oauth2.googleapis.com
6. Restart OpenCode server and confirm vertex provider appears
Google has two separate billing lanes for Gemini:
AI Studio APIVertex AI API
Endpointgenerativelanguage.googleapis.comaiplatform.googleapis.com
AuthAPI Key (AIzaSy...)GCP project + Service Account
BillingAI Studio billingGCP Billing Account
Free creditsFree tier only$300 trial + $10/month
QuotaShared, rate-limitedIndependent quota
Once you link a GCP Billing Account, Vertex AI models also appear in the AI Studio UI — with a different model ID format (versioned suffix). Both use the same Billing Account, so one Spend Cap covers both.
Every new GCP Billing Account gets $300 free credit, valid for 90 days.
  • Go to console.cloud.google.com
  • Create a Billing Account → select "Start free trial"
  • Credit applies automatically to Vertex AI API usage
Members of the Google Developer Program get $10 Vertex AI credit every month.
  • Not automatic — you must claim it manually each month
  • URL: developers.google.com/program/my-benefits
  • $10 credit is consumed first, before the $300 trial credit
Critical: create your GCP project with a personal Gmail account, not a Google Workspace / company account.Workspace accounts create projects bound to an Organization. Organization policies can block billing attachment and Vertex AI API enablement — a frustrating failure mode that's hard to diagnose.Personal Gmail → project is automatically no-org with no restrictions.Verify:
Bash
gcloud projects describe YOUR_PROJECT_ID --format='value(parent.type)'
# empty output = no-org ✅
# "organization" = might cause issues ⚠️
Bash
# Or do it in GCP Console
gcloud projects create YOUR_PROJECT_ID --name="my-vertex-project"
gcloud config set project YOUR_PROJECT_ID
Bash
gcloud services enable aiplatform.googleapis.com
Or: APIs & Services → Library → "Vertex AI API" → Enable
Bash
# Create service account
gcloud iam service-accounts create vertex-sa \
  --display-name="Vertex AI SA"

# Grant Vertex AI User role
gcloud projects add-iam-policy-binding YOUR_PROJECT_ID \
  --member="serviceAccount:vertex-sa@YOUR_PROJECT_ID.iam.gserviceaccount.com" \
  --role="roles/aiplatform.user"

# Create JSON key
gcloud iam service-accounts keys create ~/vertex-key.json \
  --iam-account="vertex-sa@YOUR_PROJECT_ID.iam.gserviceaccount.com"
Store the key somewhere stable (not a temp folder). Keep it out of git.Prevent accidental charges after the $300 credit runs out:GCP Console → Billing → Budgets & Alerts → Create Budget:
  • Amount: $0
  • Actions: ✅ "Disable billing on this project when budget is exceeded"
When credit is exhausted, API calls return an error instead of charging your card.
OpenCode uses its own Node.js environment:
Bash
cd ~/.local/share/opencode && bun add @ai-sdk/google-vertex
Verify:
Bash
ls ~/.local/share/opencode/node_modules/@ai-sdk/google-vertex/package.json && echo "OK"
Json
{
  "providers": {
    "vertex": {
      "name": "🪐 Vertex AI",
      "npm": "@ai-sdk/google-vertex",
      "options": {
        "project": "YOUR_PROJECT_ID",
        "location": "global",
        "googleAuthOptions": {
          "keyFile": "/absolute/path/to/vertex-key.json"
        }
      },
      "whitelist": [
        "gemini-3.1-pro-preview-customtools",
        "gemini-3.1-pro-preview",
        "gemini-3-flash-preview",
        "gemini-3.1-flash-lite-preview"
      ]
    }
  }
}
Why JSON Key, not ADC? In mainland China, ADC relies on periodic token refresh via oauth2.googleapis.com. If your proxy drops for a moment, token refresh fails and requests fail too. JSON Key signs tokens locally using the private key — no outbound network call required for auth. More resilient.OpenCode has a built-in vertex provider, but it ignores the whitelist field — it shows all available models (DeepSeek, GLM, old Gemini versions, dozens of others). The custom @ai-sdk/google-vertex npm provider respects whitelist exactly.Also: the built-in provider activates automatically if certain env vars are present (GOOGLE_APPLICATION_CREDENTIALS, GOOGLE_CLOUD_PROJECT). Keep those out of your plist/environment to avoid it appearing.
OpenCode's Vertex AI integration uses @ai-sdk/google-vertexgoogle-auth-library → Node.js native https to fetch OAuth tokens from oauth2.googleapis.com.Node.js native https does not read HTTP_PROXY / HTTPS_PROXY environment variables. Even if you have a working system proxy, Node.js bypasses it entirely. Result: SSL certificate error (connection blocked by GFW).Node.js v25+ supports --use-env-proxy, which makes native https respect proxy env vars.Add to ~/.zshenv:
Bash
export NODE_OPTIONS="--use-env-proxy"
And make sure your proxy is set:
Bash
export HTTP_PROXY="http://127.0.0.1:7890"
export HTTPS_PROXY="http://127.0.0.1:7890"
export NO_PROXY="localhost,127.0.0.1,10.0.0.0/8"
If you run OpenCode as a macOS launchd service (via a .plist), there's a second layer: launchctl does not inherit ~/.zshenv. Even setting EnvironmentVariables in the plist doesn't reliably propagate to child processes.The fix is a wrapper shell script:
Bash
# ~/.bin/opencode-server
#!/bin/bash
export NODE_OPTIONS="--use-env-proxy"
export HTTP_PROXY="http://127.0.0.1:7890"
export HTTPS_PROXY="http://127.0.0.1:7890"
export NO_PROXY="10.0.0.0/8,127.0.0.1,localhost"
exec /path/to/opencode serve --port 4096 --hostname 0.0.0.0 "$@"
Bash
chmod +x ~/.bin/opencode-server
Update your plist to use the wrapper:
Xml
<key>ProgramArguments</key>
<array>
    <string>/Users/YOUR_USERNAME/.bin/opencode-server</string>
</array>
Then reload:
Bash
launchctl unload ~/Library/LaunchAgents/ai.opencode.server.plist
launchctl load ~/Library/LaunchAgents/ai.opencode.server.plist
Bash
# Test Node.js can reach Google through proxy
NODE_OPTIONS="--use-env-proxy" HTTP_PROXY="http://127.0.0.1:7890" \
  node -e "const https=require('https'); https.get('https://oauth2.googleapis.com/', (res)=>{console.log('HTTP', res.statusCode); res.destroy()})"
# HTTP 404 = reachable ✅ (404 just means no handler for /, that's fine)

# Confirm running server has the env vars
ps eww $(pgrep -f "opencode serve") | tr ' ' '\n' | grep -E "NODE_OPTIONS|HTTP_PROXY"
With two Vertex projects and AI Studio as backup, you can stack them for near-zero downtime:
Text
vertex/gemini-3.1-pro-preview-customtools   ← primary (Vertex project 1)
  ↓ 429 / fail
vertex2/gemini-3.1-pro-preview-customtools  ← secondary (Vertex project 2)
  ↓ 429 / fail
google/gemini-3.1-pro-preview               ← AI Studio (API key)
  ↓ 429 / fail
qwen-coding-plan/qwen3-max                  ← final fallback
For lightweight agents (explorers, librarians):
Text
vertex/gemini-3.1-flash-lite-preview
  ↓ 429 / fail
vertex2/gemini-3.1-flash-lite-preview
  ↓ 429 / fail
google/gemini-3.1-flash-lite-preview
Model IDTypeNotes
gemini-3.1-pro-preview-customtoolsProRecommended — stronger tool use
gemini-3.1-pro-previewProStandard
gemini-3-flash-previewFlashFast
gemini-3.1-flash-lite-previewFlash LiteLightest
⚠️ gemini-3.1-flash-preview does not exist. The correct ID is gemini-3.1-flash-lite-preview.
Bash
# Confirm no ADC file (triggers built-in provider)
ls ~/.config/gcloud/application_default_credentials.json 2>/dev/null && echo "WARNING" || echo "OK"

# Confirm plist has no GCP env vars that trigger built-in provider
/usr/libexec/PlistBuddy -c "Print :EnvironmentVariables" \
  ~/Library/LaunchAgents/ai.opencode.server.plist | grep -i "GOOGLE_APPLICATION\|GOOGLE_CLOUD"

# Check SDK installed
ls ~/.local/share/opencode/node_modules/@ai-sdk/google-vertex/package.json && echo "OK"

# Restart server
launchctl stop ai.opencode.server && sleep 1 && launchctl start ai.opencode.server
If you use an AI coding assistant like OpenCode, paste this prompt and let it handle everything:
Bash
I want to set up Google Vertex AI in OpenCode to use free Gemini 3.1 Pro.
Reference: https://mjshao.fun/blog/opencode-vertex-gemini-pro

My setup:
- GCP project ID: [ask me]
- Service account JSON key path: [ask me]
- OpenCode config: ~/.config/opencode/opencode.json
- In mainland China (need proxy fix): [yes / no]
- Proxy address if yes: [http://127.0.0.1:7890]
- OpenCode runs as launchctl service: [yes / no]

Steps:
1. Install @ai-sdk/google-vertex in ~/.local/share/opencode via bun
2. Add vertex provider block to opencode.json with SA JSON key
3. If in China: add NODE_OPTIONS=--use-env-proxy to ~/.zshenv
4. If launchctl: create ~/.bin/opencode-server wrapper, update plist ProgramArguments
5. Verify: node https.get test to oauth2.googleapis.com expect HTTP 404
6. Reload launchctl service and confirm vertex provider appears in OpenCode
通过 Google Vertex AI 免费运行 Gemini 3.1 Pro — $300 试用额度 + 每月 $10 开发者福利,附中国大陆代理修复方案。
OpenCode 支持配置任意 AI provider。Google Vertex AI 可以通过 $300 新账号试用额度 + Google Developer Program 每月 $10 额度,免费使用 Gemini 3.1 Pro。本文覆盖完整配置:GCP 项目创建、认证、OpenCode 配置,以及中国大陆必需的代理修复。
如果你用 AI 编程助手,把这段 prompt 粘进去,让它帮你搞定:
Markdown
我想在 OpenCode 里配置 Google Vertex AI,免费使用 Gemini 3.1 Pro。
参考文章:https://mjshao.fun/blog/opencode-vertex-gemini-pro

我的环境:
- OS:[macOS / Linux]
- OpenCode 配置路径:[~/.config/opencode/opencode.json]
- GCP 项目 ID:[告诉我]
- 服务账号 JSON Key 路径:[告诉我]
- 在中国大陆(需要代理修复):[是 / 否]
- 代理地址(如果是):[http://127.0.0.1:7890]
- OpenCode 以 launchctl 服务方式运行:[是 / 否]

步骤:
1. 在 OpenCode 的 node_modules 里安装 @ai-sdk/google-vertex
2. 在 opencode.json 里添加 vertex provider,使用 SA JSON Key 认证
3. 如果在中国:在 ~/.zshenv 添加 NODE_OPTIONS=--use-env-proxy
4. 如果是 launchctl 服务:创建 ~/.bin/opencode-server wrapper 脚本,更新 plist ProgramArguments
5. 验证:node https.get 测试 oauth2.googleapis.com → 期望 HTTP 404
6. 重启 OpenCode server,确认 vertex provider 出现
Google 的 Gemini 有两条独立计费通道:
AI Studio APIVertex AI API
接入点generativelanguage.googleapis.comaiplatform.googleapis.com
认证API Key(AIzaSy...GCP 项目 + 服务账号
计费AI Studio 独立计费GCP Billing Account
免费额度仅 Free Tier 限速$300 试用 + 每月 $10
Quota共享,限速较严独立 quota
开启 GCP Billing 后,AI Studio 页面也会出现 Vertex AI 模型(模型 ID 格式不同,带版本号后缀)。两者共用同一个 Billing Account,设一个 Spend Cap 统一保护。
每个新 GCP Billing Account 赠送 $300 免费额度,90 天有效
  • 进入 console.cloud.google.com
  • 创建 Billing Account → 选择"Start free trial"
  • 自动计入 Vertex AI API 用量
加入 Google Developer Program 的成员每月可领 $10 Vertex AI 额度
  • 不自动发放 — 每月要去手动 claim
  • 地址:developers.google.com/program/my-benefits
  • $10 额度优先消耗,再消耗 $300 试用额度
关键:必须用个人 Gmail 账号创建 GCP 项目,不能用 Google Workspace / 企业账号。企业账号创建的项目会绑定组织(Organization),组织策略可能阻止 Billing Account 附加和 Vertex AI API 启用 — 这个坑很难诊断。个人 Gmail → 项目自动 no-org,没有任何限制。验证:
Bash
gcloud projects describe YOUR_PROJECT_ID --format='value(parent.type)'
# 空输出 = no-org ✅
# 输出 "organization" = 有 org,可能有问题 ⚠️
Bash
# 启用 Vertex AI API
gcloud services enable aiplatform.googleapis.com

# 创建服务账号
gcloud iam service-accounts create vertex-sa \
  --display-name="Vertex AI SA"

# 授予 Vertex AI User 角色
gcloud projects add-iam-policy-binding YOUR_PROJECT_ID \
  --member="serviceAccount:vertex-sa@YOUR_PROJECT_ID.iam.gserviceaccount.com" \
  --role="roles/aiplatform.user"

# 创建 JSON Key
gcloud iam service-accounts keys create ~/vertex-key.json \
  --iam-account="vertex-sa@YOUR_PROJECT_ID.iam.gserviceaccount.com"
$300 额度用完后防止意外扣费:GCP Console → Billing → Budgets & Alerts → Create Budget:
  • Amount:$0
  • Actions:✅ "Disable billing on this project when budget is exceeded"
额度耗尽后 API 调用返回错误,不会继续扣费。
Bash
cd ~/.local/share/opencode && bun add @ai-sdk/google-vertex
Json
{
  "providers": {
    "vertex": {
      "name": "🪐 Vertex AI",
      "npm": "@ai-sdk/google-vertex",
      "options": {
        "project": "YOUR_PROJECT_ID",
        "location": "global",
        "googleAuthOptions": {
          "keyFile": "/绝对路径/vertex-key.json"
        }
      },
      "whitelist": [
        "gemini-3.1-pro-preview-customtools",
        "gemini-3.1-pro-preview",
        "gemini-3-flash-preview",
        "gemini-3.1-flash-lite-preview"
      ]
    }
  }
}
为什么用 JSON Key 而不是 ADC?在中国大陆,ADC 依赖定期访问 oauth2.googleapis.com 刷新 token。代理偶尔断开时,刷新失败,请求全部报错。JSON Key 用私钥本地签名 JWT,不需要实时联网认证,更健壮。为什么不用内置 vertex provider?OpenCode 内置的 vertex provider 会忽略 whitelist 字段,把所有内置模型都显示出来(DeepSeek、GLM、各种老版 Gemini,几十个)。用自定义 @ai-sdk/google-vertex npm provider 才能让 whitelist 精确生效。
@ai-sdk/google-vertexgoogle-auth-library → Node.js 原生 https 访问 oauth2.googleapis.com 获取 OAuth token。Node.js 原生 https 不读取 HTTP_PROXY / HTTPS_PROXY 环境变量。即使系统代理正常工作,Node.js 也会绕过它直连 Google → GFW 阻断 → SSL 错误。Node.js v25+ 支持 --use-env-proxy,让原生 https 读取代理环境变量。~/.zshenv 添加:
Bash
export NODE_OPTIONS="--use-env-proxy"
export HTTP_PROXY="http://127.0.0.1:7890"
export HTTPS_PROXY="http://127.0.0.1:7890"
export NO_PROXY="localhost,127.0.0.1,10.0.0.0/8"
如果 OpenCode 以 macOS launchd 服务运行(plist),launchctl 不继承 ~/.zshenv,在 plist EnvironmentVariables 里设也不够可靠。解决方案:wrapper 脚本:
Bash
# ~/.bin/opencode-server
#!/bin/bash
export NODE_OPTIONS="--use-env-proxy"
export HTTP_PROXY="http://127.0.0.1:7890"
export HTTPS_PROXY="http://127.0.0.1:7890"
export NO_PROXY="10.0.0.0/8,127.0.0.1,localhost"
exec /path/to/opencode serve --port 4096 --hostname 0.0.0.0 "$@"
plist 改为使用 wrapper:
Xml
<key>ProgramArguments</key>
<array>
    <string>/Users/YOUR_USERNAME/.bin/opencode-server</string>
</array>
Bash
# 测试 Node.js 能通过代理访问 Google
NODE_OPTIONS="--use-env-proxy" HTTP_PROXY="http://127.0.0.1:7890" \
  node -e "const https=require('https'); https.get('https://oauth2.googleapis.com/', (res)=>{console.log('HTTP', res.statusCode); res.destroy()})"
# HTTP 404 = 可达 ✅

# 确认运行中的 server 有代理变量
ps eww $(pgrep -f "opencode serve") | tr ' ' '\n' | grep -E "NODE_OPTIONS|HTTP_PROXY"
两个 Vertex 项目 + AI Studio 备用,实现近零中断:
Text
vertex/gemini-3.1-pro-preview-customtools   ← 主力(Vertex 项目 1)
  ↓ 429 / 失败
vertex2/gemini-3.1-pro-preview-customtools  ← 备用(Vertex 项目 2)
  ↓ 429 / 失败
google/gemini-3.1-pro-preview               ← AI Studio(API Key)
  ↓ 429 / 失败
qwen-coding-plan/qwen3-max                  ← 最终兜底
轻量级 agent(探索、检索):
Text
vertex/gemini-3.1-flash-lite-preview
  ↓ 429 / 失败
vertex2/gemini-3.1-flash-lite-preview
  ↓ 429 / 失败
google/gemini-3.1-flash-lite-preview
Model ID类型说明
gemini-3.1-pro-preview-customtoolsPro推荐,工具调用更强
gemini-3.1-pro-previewPro标准版
gemini-3-flash-previewFlash快速
gemini-3.1-flash-lite-previewFlash Lite最轻量
⚠️ gemini-3.1-flash-preview 不存在,正确 ID 是 gemini-3.1-flash-lite-preview
Bash
# 确认无 ADC 文件(会触发内置 provider)
ls ~/.config/gcloud/application_default_credentials.json 2>/dev/null && echo "WARNING" || echo "OK"

# 确认 plist 无 GCP 环境变量
/usr/libexec/PlistBuddy -c "Print :EnvironmentVariables" \
  ~/Library/LaunchAgents/ai.opencode.server.plist | grep -i "GOOGLE_APPLICATION\|GOOGLE_CLOUD"

# 检查 SDK 已安装
ls ~/.local/share/opencode/node_modules/@ai-sdk/google-vertex/package.json && echo "OK"

# 重启 server
launchctl stop ai.opencode.server && sleep 1 && launchctl start ai.opencode.server
Share this post:
Enjoy this post? Subscribe via RSS: English | 中文