Gemini 3.1 Pro API:开发者指南及代码示例(2026)
Gemini 3.1 Pro API 完整开发者指南。涵盖模型 ID(gemini-3.1-pro-preview-customtools)、价格、Python 和 JavaScript 代码示例、自定义工具、函数调用以及如何与你的应用集成。
概要
| Gemini 3.1 Pro | |
|---|---|
| 模型 ID | gemini-3.1-pro、gemini-3.1-pro-preview-customtools |
| 上下文窗口 | 1M token |
| 输入价格 | $2/1M token |
| 输出价格 | $12/1M token |
| 核心功能 | 自定义工具、函数调用、grounding、多模态(文本 + 图片 + 音频 + 视频) |
| API | Google AI Studio / Vertex AI |
Gemini 3.1 Pro 是 Google 最新的 frontier 模型,于 2026 年 3 月发布。每 token 最便宜的 frontier API,原生 1M 上下文,并引入了自定义工具 — 一种用结构化 schema 让模型访问外部函数的新方式。
模型 ID
Google 提供两个 Gemini 3.1 Pro 变体:
| 模型 ID | 描述 | 状态 |
|---|---|---|
gemini-3.1-pro | 稳定版本,正式发布 | GA |
gemini-3.1-pro-preview-customtools | 增强自定义工具支持的预览版 | Preview |
customtools 预览变体对复杂的函数调用链具有更好的可靠性。一般使用推荐稳定版 gemini-3.1-pro。
# Google AI Studio
model = "gemini-3.1-pro"
# Vertex AI
model = "gemini-3.1-pro@001"
快速开始:Python
安装
pip install google-genai
基本文本生成
from google import genai
client = genai.Client(api_key="YOUR_API_KEY")
response = client.models.generate_content(
model="gemini-3.1-pro",
contents="Explain quantum computing in 3 sentences."
)
print(response.text)
流式传输
for chunk in client.models.generate_content_stream(
model="gemini-3.1-pro",
contents="Write a Python function to merge two sorted arrays."
):
print(chunk.text, end="")
快速开始:JavaScript
安装
npm install @google/genai
基本文本生成
import { GoogleGenAI } from "@google/genai";
const ai = new GoogleGenAI({ apiKey: "YOUR_API_KEY" });
const response = await ai.models.generateContent({
model: "gemini-3.1-pro",
contents: "Explain quantum computing in 3 sentences.",
});
console.log(response.text);
流式传输
const stream = await ai.models.generateContentStream({
model: "gemini-3.1-pro",
contents: "Write a JavaScript function to merge two sorted arrays.",
});
for await (const chunk of stream) {
process.stdout.write(chunk.text);
}
Be first to build with AI
Y Build is the AI-era operating system for startups. Join the waitlist and get early access.
价格
Gemini 3.1 Pro 是截至 2026 年 3 月最便宜的 frontier 模型 API。
| Gemini 3.1 Pro | GPT-5.2 | Claude Sonnet 4.6 | |
|---|---|---|---|
| 输入 | $2/1M | $5/1M | $3/1M |
| 输出 | $12/1M | $15/1M | $15/1M |
| 上下文 | 1M | 400K | 1M(beta) |
| 每 100K 输入 + 20K 输出成本 | $0.44 | $0.80 | $0.60 |
大规模使用时,Gemini 3.1 Pro 比 GPT-5.2 便宜约 45%,比 Sonnet 4.6 便宜约 27%。
免费计划
Google AI Studio 提供免费计划:
- 每分钟 60 个请求
- 每分钟 1M token
- 无需信用卡
这是三大供应商中最慷慨的免费 API 计划。
核心功能
1M Token 上下文窗口
Gemini 3.1 Pro 原生支持 100 万 token 上下文 — 足以处理:
- ~70 万字文本
- ~3 万行代码
- ~1 小时视频
- ~11 小时音频
自定义工具(函数调用)
自定义工具让你定义 Gemini 在生成过程中可以调用的外部函数。模型决定何时调用工具,构建参数,并将结果纳入响应。
Google Search Grounding
Gemini 可以用实时 Google Search 结果来锚定其响应。
原生多模态
在单个请求中处理文本、图片、音频和视频。无需单独的视觉或音频模型。
代码示例:自定义工具/函数调用
Python
from google import genai
from google.genai import types
client = genai.Client(api_key="YOUR_API_KEY")
weather_tool = types.Tool(
function_declarations=[
types.FunctionDeclaration(
name="get_weather",
description="Get the current weather for a city",
parameters=types.Schema(
type=types.Type.OBJECT,
properties={
"city": types.Schema(
type=types.Type.STRING,
description="City name, e.g. 'San Francisco'"
),
"unit": types.Schema(
type=types.Type.STRING,
enum=["celsius", "fahrenheit"],
description="Temperature unit"
),
},
required=["city"],
),
)
]
)
response = client.models.generate_content(
model="gemini-3.1-pro-preview-customtools",
contents="What's the weather like in Tokyo?",
config=types.GenerateContentConfig(
tools=[weather_tool],
),
)
for part in response.candidates[0].content.parts:
if part.function_call:
print(f"Function: {part.function_call.name}")
print(f"Arguments: {part.function_call.args}")
JavaScript
import { GoogleGenAI } from "@google/genai";
const ai = new GoogleGenAI({ apiKey: "YOUR_API_KEY" });
const weatherTool = {
functionDeclarations: [
{
name: "get_weather",
description: "Get the current weather for a city",
parameters: {
type: "OBJECT",
properties: {
city: {
type: "STRING",
description: "City name, e.g. 'San Francisco'",
},
unit: {
type: "STRING",
enum: ["celsius", "fahrenheit"],
description: "Temperature unit",
},
},
required: ["city"],
},
},
],
};
const response = await ai.models.generateContent({
model: "gemini-3.1-pro-preview-customtools",
contents: "What's the weather like in Tokyo?",
config: {
tools: [weatherTool],
},
});
for (const part of response.candidates[0].content.parts) {
if (part.functionCall) {
console.log(`Function: ${part.functionCall.name}`);
console.log(`Arguments:`, part.functionCall.args);
}
}
代码示例:多模态(图片 + 文本)
Python
from google import genai
from google.genai import types
import base64
client = genai.Client(api_key="YOUR_API_KEY")
with open("screenshot.png", "rb") as f:
image_data = f.read()
response = client.models.generate_content(
model="gemini-3.1-pro",
contents=[
types.Content(
parts=[
types.Part(text="What's in this screenshot? Describe the UI elements."),
types.Part(
inline_data=types.Blob(
mime_type="image/png",
data=image_data,
)
),
]
)
],
)
print(response.text)
JavaScript
import { GoogleGenAI } from "@google/genai";
import fs from "fs";
const ai = new GoogleGenAI({ apiKey: "YOUR_API_KEY" });
const imageData = fs.readFileSync("screenshot.png");
const base64Image = imageData.toString("base64");
const response = await ai.models.generateContent({
model: "gemini-3.1-pro",
contents: [
{
parts: [
{ text: "What's in this screenshot? Describe the UI elements." },
{
inlineData: {
mimeType: "image/png",
data: base64Image,
},
},
],
},
],
});
console.log(response.text);
API 对比:Gemini 3.1 Pro vs GPT-5.2 vs Claude Sonnet 4.6
| 功能 | Gemini 3.1 Pro | GPT-5.2 | Claude Sonnet 4.6 |
|---|---|---|---|
| 输入价格 | $2/1M | $5/1M | $3/1M |
| 输出价格 | $12/1M | $15/1M | $15/1M |
| 上下文窗口 | 1M(GA) | 400K | 1M(beta) |
| 函数调用 | 是(自定义工具) | 是 | 是(tool use) |
| 多模态 | 文本 + 图片 + 音频 + 视频 | 文本 + 图片 + 音频 | 文本 + 图片 |
| Grounding | Google Search | 网页浏览 | 无原生 grounding |
| 流式传输 | 是 | 是 | 是 |
| 免费计划 | 60 RPM、1M TPM | 有限 | 有限 |
| 编码(SWE-bench) | 76.8% | 80.0% | 79.6% |
| 计算机使用 | 无 | 38.2% | 72.5% |
| 数学(AIME) | ~88% | 100% | ~90% |
何时选择各 API
选择 Gemini 3.1 Pro: 成本是首要考虑时,需要原生视频/音频处理时,需要生产环境 1M 上下文(GA,非 beta)时,在 Google Cloud 上构建时。 选择 GPT-5.2: 数学推理至关重要时,需要带保证 JSON schema 的结构化输出时。 选择 Claude Sonnet 4.6: 编码和代理任务是主要用例时,需要计算机使用/浏览器自动化时。将 Gemini 3.1 Pro 集成到你的应用
与 Y Build 一起使用
如果你正在用 Y Build 构建产品,可以将 Gemini API 直接集成到后端。Y Build 项目部署到 Cloudflare Workers。
// In a Y Build project (Cloudflare Worker)
export async function onRequest(context) {
const response = await fetch(
"https://generativelanguage.googleapis.com/v1beta/models/gemini-3.1-pro:generateContent",
{
method: "POST",
headers: {
"Content-Type": "application/json",
"x-goog-api-key": context.env.GEMINI_API_KEY,
},
body: JSON.stringify({
contents: [{ parts: [{ text: "Your prompt here" }] }],
}),
}
);
const data = await response.json();
return new Response(JSON.stringify(data));
}
速率限制
| 层级 | 请求/分钟 | Token/分钟 |
|---|---|---|
| 免费 | 60 | 1,000,000 |
| 按量付费 | 1,000 | 4,000,000 |
| 企业 | 自定义 | 自定义 |
常见问题
gemini-3.1-pro-preview-customtools 是什么?
这是 Gemini 3.1 Pro 的预览变体,针对自定义工具和函数调用进行了优化。一般文本生成使用稳定版 gemini-3.1-pro。
Gemini 3.1 Pro 比 GPT-5.2 好吗?
取决于任务。Gemini 更便宜、上下文窗口更大、支持更多模态。GPT-5.2 在编码基准测试和数学推理上得分更高。
我可以免费使用 Gemini 3.1 Pro 吗?
可以。Google AI Studio 提供免费计划,每分钟 60 个请求和 100 万 token。无需信用卡。
Google AI Studio 和 Vertex AI 有什么区别?
Google AI Studio 是更简单的、面向开发者的 API — 用 API 密钥注册即可开始调用。Vertex AI 是企业平台 — 运行在 Google Cloud 上,提供微调、模型部署、监控和 SLA。同一模型,不同的包装。
总结
Gemini 3.1 Pro 是 2026 年 3 月性价比最高的 frontier API。每百万 token $2/$12,大约是 GPT-5.2 的一半成本,比 Claude Sonnet 4.6 便宜三分之一 — 加上原生 1M 上下文和最广泛的多模态支持。
对开发者的实用建议:多模态和成本敏感任务用 Gemini,编码和代理用 Claude,数学推理用 GPT-5.2。 跨三个模型路由可获得各自最佳表现。
正在构建 AI 产品?Y Build — AI 编码、一键部署到 Cloudflare、Demo Cut、AI SEO 和分析。将 Gemini、Claude 或 GPT API 集成到你的应用中,数小时内发布。免费开始。
来源:
Be first to build with AI
Y Build is the AI-era operating system for startups. Join the waitlist and get early access.