使用 Gemini 3.1 Pro 構建應用程式:API、Coding 與 Vibe Coding 開發者指南
2026 年 2 月 19 日 — Gemini 3.1 Pro 剛剛發布,它是目前最強大的程式碼編寫模型之一:SWE-Bench Verified 達到 80.6%、LiveCodeBench 達到 2887 Elo,且擁有 100 萬 Token 上下文窗口,價格僅為 每百萬輸入 Token 2 美元。這意味著您能以極低的成本獲得前沿等級的程式碼編寫能力。
本指南適合希望從今天開始使用它進行構建的開發者。我們將涵蓋 API 設置、Python 和 Node.js 的程式碼範例、思考層級、用於成本優化的上下文快取,以及 Gemini 3.1 Pro 如何融入 Vibe Coding 工作流程。
快速入門
選項 1:Google AI Studio(免費,無需設置)
嘗試 Gemini 3.1 Pro 最快的方法:
- 前往 aistudio.google.com
- 使用您的 Google 帳戶登入
- 從模型下拉選單中選擇 Gemini 3.1 Pro Preview
- 開始輸入提示詞
AI Studio 提供免費使用(有速率限制),非常適合原型設計和實驗。
選項 2:API 金鑰(用於構建應用程式)
- 在 AI Studio 中,前往 Get API Key → Create API Key
- 安全地儲存金鑰(切勿將其提交至版本控制系統)
- 安裝 SDK:
# Python
pip install google-genai
# Node.js
npm install @google/genai
您的第一個 API 調用
Python
from google import genai
client = genai.Client(api_key="YOUR_API_KEY")
response = client.models.generate_content(
model="gemini-3.1-pro-preview",
contents="Write a Python function that finds the longest common subsequence of two strings. Include type hints and docstring."
)
print(response.text)
Node.js
import { GoogleGenAI } from "@google/genai";
const ai = new GoogleGenAI({ apiKey: "YOUR_API_KEY" });
const response = await ai.models.generateContent({
model: "gemini-3.1-pro-preview",
contents: "Write a TypeScript Express middleware that validates JWT tokens and extracts user info.",
});
console.log(response.text);
使用思考層級 (Thinking Levels)
# 對於複雜的除錯使用高思考層級
response = client.models.generate_content(
model="gemini-3.1-pro-preview",
contents="""
This Go server has a race condition that causes intermittent 500 errors
under load. Here's the relevant code:
[paste your code here]
Find the race condition and explain the fix.
""",
config={
"thinking_config": {"thinking_level": "HIGH"}
}
)
使用 Gemini 3.1 Pro 進行程式編寫
基準測試背景
在深入探討功能之前,以下是 Gemini 3.1 Pro 在程式碼模型中的地位:
| 基準測試 | Gemini 3.1 Pro | GPT-5.3-Codex | Claude Opus 4.6 |
|---|---|---|---|
| SWE-Bench Verified | 80.6% | 76.2% | 72.6% |
| Terminal-Bench 2.0 | 68.5% | 77.3% | — |
| LiveCodeBench Pro | 2887 Elo | — | — |
相比於之前的 Gemini 3 Pro Preview,它有 15% 的提升,且能使用更少的輸出 Token 產生更好的結果。
程式碼生成
Gemini 3.1 Pro 能生成跨語言的生產級程式碼。100 萬 Token 的上下文意味著您可以包含現有的程式碼庫,以進行上下文感知的生成:
# 載入您的程式碼庫上下文
with open("codebase_context.txt", "r") as f:
codebase = f.read()
response = client.models.generate_content(
model="gemini-3.1-pro-preview",
contents=f"""
Here is my current codebase:
{codebase}
Add a new API endpoint POST /api/users/bulk-import that:
- Accepts a CSV file upload
- Validates each row against the User schema
- Inserts valid records in batches of 100
- Returns a summary of successes and failures
- Follow the existing patterns and coding style
""",
config={
"thinking_config": {"thinking_level": "MEDIUM"}
}
)
除錯 (Debugging)
將錯誤日誌、堆疊追蹤和原始碼一起輸入。對於複雜的 Bug,「高(High)」思考層級絕對值得額外的成本:
response = client.models.generate_content(
model="gemini-3.1-pro-preview",
contents="""
Error: Connection pool exhausted after 30 seconds
Stack trace:
[paste stack trace]
Relevant source files:
[paste db.py, connection_pool.py, api_handler.py]
This only happens under concurrent requests (>50 rps).
Find the root cause.
""",
config={
"thinking_config": {"thinking_level": "HIGH"}
}
)
程式碼審查 (Code Review)
「中(Medium)」思考層級提供了平衡的審查,而不會過度分析瑣碎的程式碼:
response = client.models.generate_content(
model="gemini-3.1-pro-preview",
contents=f"""
Review this pull request diff for:
1. Bugs or logic errors
2. Security vulnerabilities (SQL injection, XSS, etc.)
3. Performance issues
4. Adherence to project conventions
Diff:
{diff_content}
""",
config={
"thinking_config": {"thinking_level": "MEDIUM"}
}
)
100 萬 Token 上下文的優勢
Gemini 3.1 Pro 的 100 萬個 Token 上下文窗口改變了您與程式碼互動的方式。您不再需要提供程式碼片段,而是可以加載 整個專案。
上下文大小參考
| 您可以加載的內容 | 大約 Token 數 |
|---|---|
| 單一文件 (500 行) | ~2K tokens |
| 小型專案 (50 個文件) | ~100K tokens |
| 中型專案 (200 個文件) | ~400K tokens |
| 大型專案 (500 個文件) | ~1M tokens |
全程式碼庫分析
import os
def load_codebase(root_dir, extensions=('.py', '.js', '.ts', '.jsx', '.tsx')):
"""將所有源文件加載到單個上下文字符串中。"""
files = []
for dirpath, _, filenames in os.walk(root_dir):
for filename in filenames:
if any(filename.endswith(ext) for ext in extensions):
filepath = os.path.join(dirpath, filename)
with open(filepath, 'r', errors='ignore') as f:
content = f.read()
files.append(f"=== {filepath} ===\n{content}\n")
return "\n".join(files)
codebase = load_codebase("./src")
response = client.models.generate_content(
model="gemini-3.1-pro-preview",
contents=f"""
Analyze this entire codebase and identify:
1. Architectural issues or anti-patterns
2. Dead code that can be removed
3. Functions that should be refactored
4. Missing error handling at system boundaries
Codebase:
{codebase}
"""
)
這是您在使用 20 萬上下文的模型時,如果不進行分塊並失去跨文件上下文,就無法做到的事情。
思考層級:低、中、高
思考層級讓您可以控制每次請求的 成本與品質之間的權衡。
| 層級 | 使用場景 | Token 開銷 | 成本影響 |
|---|---|---|---|
| 低 (Low) | 自動補全、簡單查詢、格式化、分類 | 極小 | ~1x |
| 中 (Medium) | 程式碼審查、摘要、中度分析、內容生成 | 中等 | ~2-3x |
| 高 (High) | 複雜除錯、多步驟推理、架構決策 | 顯著 | ~5-10x |
實務準則
- 低:「將此 JSON 轉換為 TypeScript 介面」—— 不需要深度推理。
- 中:「審查此 PR 以查找 Bug 和安全問題」—— 需要分析但不需要詳盡無遺。
- 高:「此分佈式系統在負載下存在間歇性的等效性 Bug。這裡有 15 個文件……」—— 需要深度的跨文件推理。
# 根據任務複雜度切換思考層級
def ask_gemini(prompt, complexity="medium"):
levels = {"low": "LOW", "medium": "MEDIUM", "high": "HIGH"}
return client.models.generate_content(
model="gemini-3.1-pro-preview",
contents=prompt,
config={
"thinking_config": {"thinking_level": levels[complexity]}
}
)
成本優化
上下文快取 (Context Caching)
如果您的應用程式重複查詢相同的程式碼庫或文件,上下文快取可將輸入成本降低 75%:
| 定價 | 標準 | 快取 |
|---|---|---|
| 輸入 (每 1M tokens) | $2.00 | $0.50 |
| 輸出 (每 1M tokens) | $12.00 | $12.00 |
# 為您的程式碼庫建立快取上下文
cached_content = client.caches.create(
model="gemini-3.1-pro-preview",
contents=[{"role": "user", "parts": [{"text": codebase}]}],
ttl="3600s" # 快取 1 小時
)
# 後續查詢使用快取的上下文
response = client.models.generate_content(
model="gemini-3.1-pro-preview",
contents="Find all SQL injection vulnerabilities in this codebase",
cached_content=cached_content.name
)
程式編寫工作流程的成本比較
假設 50 萬 Token 的程式碼庫上下文 + 1K 查詢,每天 100 次查詢:
| 策略 | 每日成本 |
|---|---|
| Gemini 3.1 Pro (無快取) | ~$100 |
| Gemini 3.1 Pro (有快取) | ~$27 |
| Claude Opus 4.6 (無快取) | ~$750 |
更多優化技巧
- 選擇合適的思考層級:80% 的任務使用「低」,15% 使用「中」,5% 使用「高」。
- 批量處理相似請求:分組程式碼審查任務以攤銷上下文加載成本。
- 積極使用快取:如果您對同一份文件/程式碼查詢超過 3 次,請快取它。
- 使用 Gemini 3 Flash 處理不需要 Pro 等級推理的簡單任務。
Gemini 3.1 Pro 的 Vibe Coding
Vibe coding 是一種開發實踐,您用自然語言描述您想要的東西,然後讓 AI 生成程式碼。Gemini 3.1 Pro 在這方面特別強大,因為它理解 設計意圖,而不僅僅是語法。
Gemini 如何理解 "Vibe"
Hostinger 的團隊指出,Gemini 3.1 Pro 能將「方向、風格和產品意圖」轉化為程式碼。當被要求為一個憂鬱的文學主題建立作品集網站時,它會透過大氣的基調進行推理,以設計出相配的介面。
SVG 生成
一個亮點功能:Gemini 3.1 Pro 能直接從文本描述生成 動畫 SVG。由於 SVG 是程式碼,它們在任何解析度下都能保持清晰:
response = client.models.generate_content(
model="gemini-3.1-pro-preview",
contents="""
Create an animated SVG logo for a tech startup called "Pulse AI".
Design requirements:
- Minimalist, modern style
- Blue-to-purple gradient
- Subtle pulse animation on the icon
- 200x60px viewport
- Clean, sharp edges
"""
)
# 直接儲存 SVG
with open("logo.svg", "w") as f:
f.write(response.text)
構建完整應用程式
將 Gemini 3.1 Pro 的程式碼編寫能力與像 NxCode 這樣的 AI 應用構建器結合,即可從想法直接轉向已部署的應用程式:
- 用自然語言描述您的應用程式
- Gemini 生成 程式碼庫(前端 + 後端 + 資料庫)
- 通過 Vibe Coding 提示詞進行審查和迭代
- 直接部署 到生產環境
這種工作流程特別強大,因為 Gemini 的 1M 上下文窗口可以在您迭代時容納整個不斷增長的程式碼庫。
平台整合
GitHub Copilot
Gemini 3.1 Pro 現在已在 GitHub Copilot 中提供:
- 開啟 GitHub Copilot 設定
- 從模型選擇器中選擇 Gemini 3.1 Pro
- 像往常一樣使用內聯補全和聊天功能
Gemini CLI
對於基於終端的開發:
# 安裝
npm install -g @anthropic-ai/gemini-cli
# 使用
gemini --model gemini-3.1-pro-preview "Refactor this function to use async/await"
# 管道傳輸程式碼
cat src/server.js | gemini --model gemini-3.1-pro-preview "Review this code"
VS Code
通過 Copilot 擴充功能提供。在模型下拉選單中選擇 Gemini 3.1 Pro 即可獲得內聯建議和聊天服務。
Google Antigravity
這是 Google 的 Agent 開發平台,與 Gemini 有深度整合。最適合構建需要工具使用和長時間執行工作流的複雜、多步驟 AI Agent。
技巧與最佳實踐
- 從「中」思考層級開始,僅在需要時升級到「高」——這可以節省 3-5 倍的 Token。
- 預先載入完整上下文 —— Gemini 處理 100 萬個 Token 的效果很好;不要過度預過濾。
- 對任何重複的分析使用上下文快取(程式碼審查、文件 Q&A、測試生成)。
- 明確指定輸出格式 —— 「僅返回程式碼,不要解釋」可以節省輸出 Token。
- 與 Gemini 3 Flash 結合使用,建立兩層系統:Flash 用於簡單補全,Pro 用於複雜推理。
- 在提示詞中包含範例 —— Gemini 3.1 Pro 非常擅長遵循模式。
- 明確指定語言和框架 —— 「使用帶有 App Router 的 Next.js 15 並以 TypeScript 編寫」。
- 審查生成的程式碼 —— 80.6% 的 SWE-Bench 雖然令人印象深刻,但並非 100%。務必進行測試和審查。
總結
Gemini 3.1 Pro 為開發者提供了 以預算友好價格獲得的前沿程式碼編寫能力。100 萬 Token 的上下文窗口是程式碼庫級別分析的真正遊戲規則改變者,而思考層級則提供了對成本和品質的精細控制。
有關 AI 如何改變開發的更多資訊,請查看我們的 Vibe Coding 指南 以及 Cursor vs Windsurf vs Claude Code 比較。若想全面了解 Gemini 3.1 Pro 除程式碼編寫以外的功能,請參閱我們的 完整指南。

