
谷歌最近发布了其最智能的模型,该模型能够跨多种模态进行创建、推理和理解。Google Gemini 3 Pro 不仅仅是一次小幅更新,它实际上是人工智能能力的一次重大飞跃。这款模型拥有尖端的推理、多模态理解和智能体功能,将成为改变开发者创建智能应用方式的关键因素。借助全新的 Gemini 3 Pro API,开发者现在可以创建比以往任何时候都更智能、更动态的系统。
如果您正在构建复杂的 AI 工作流程、处理多模态数据或开发能够自主管理多步骤任务的智能体系统,本指南将教您如何通过其 API 使用 Gemini 3 Pro。
Gemini 3 Pro的独特之处是什么?
我们暂且不谈技术细节,先来探讨一下这款模型为何在开发者中引起如此热议。经过一段时间的开发,谷歌 Gemini 3 Pro 模型如今已跻身 AI 基准测试榜首,Elo 评分高达 1501 分。它的设计不仅旨在提供极致性能,更着重于为开发者打造卓越的体验。
主要特性包括:
- 高级推理:该模型现在能够以极其精细的思维解决复杂的多步骤问题。
- 海量上下文窗口:高达 100 万个词元的输入上下文,足以支持输入完整的代码库、完整的书籍或长视频内容。
- 多模态处理:能够流畅地同时处理文本、图像、视频、PDF 和代码。
- 智能体工作流:运行多步骤任务,模型能够协调、检查并调整其作为机器人的行动。
- 动态思维:根据具体情况,模型可以逐步解决问题,也可以直接给出答案。
您可以在以下文章中了解更多关于 Gemini 3 Pro 型号及其功能的信息:Gemini 3 Pro
入门指南:首次调用Gemini 3 Pro API
步骤 1:获取API密钥
前往 Google AI Studio 并使用您的 Google 帐户登录。然后,点击右上角的个人资料图标,并选择“Get API key”选项。如果是首次使用,请选择“Create API key in new project”;否则,请导入现有密钥。请立即备份 API 密钥,因为您将无法再次查看它。
步骤 2:安装SDK
选择您偏好的语言,并使用以下命令安装官方 SDK:
Python:
pip install google-genai
Node.js/JavaScript:
npm install @google/genai
步骤 3:设置环境变量
将您的 API 密钥安全地存储在环境变量中:
export GEMINI_API_KEY="your-api-key-here"
Gemini 3 Pro API定价
Gemini 3 Pro API 采用按需付费模式,费用主要根据您输入(提示)和模型输出(响应)所消耗的 tokens 数量计算。
定价层级的关键决定因素是请求的上下文窗口长度。上下文窗口越长,模型可以同时处理的信息就越多(例如大型文档或较长的对话历史记录),因此费用也越高。
以下费率适用于通过 Gemini API 调用的 geomini-3-pro-preview 模型,并以每百万令牌 (1M) 为单位计费。
| 功能 (Feature) | 免费层级 (Free Tier) | 付费层级 (Paid Tier) (每 100 万 token,单位:美元) |
|---|---|---|
| 输入价格 (Input price) | 免费(每日用量有限制) | $2.00 (提示词 ≤ 200k token)<br>$4.00 (提示词 > 200k token) |
| 输出价格 (含思维 token)<br>(Output price including thinking tokens) | 免费(每日用量有限制) | $12.00 (提示词 ≤ 200k token)<br>$18.00 (提示词 > 200k token) |
| 上下文缓存价格 (Context caching price) | 不可用 | $0.20 – $0.40 / 100 万 token (取决于提示词大小)<br>$4.50 / 100 万 token / 小时 (存储价格) |
| Google 搜索 grounding (Grounding with Google Search) | 不可用 | 1,500 次/天 (免费)<br>即将推出: $14 / 1,000 次搜索查询 |
| Google 地图 grounding (Grounding with Google Maps) | 不可用 | 不可用 |
了解Gemini 3 Pro的新参数
API 引入了多个革命性的参数,其中之一是“思考级别”参数,它赋予请求者非常精细的完全控制权。
思考级别参数
这个新参数很可能是最重要的参数。您不再需要猜测模型应该“思考”到什么程度,而是可以完全由您控制:
- thinking_level: “low”:适用于分类、问答或聊天等基本任务。延迟极低,成本也更低,非常适合高吞吐量应用。
- thinking_level: “high”(默认值):适用于复杂的推理任务。模型需要更长时间,但输出结果将包含更严谨的论证。这是解决问题和进行分析的最佳时机。
提示:请勿将 thinking_level 与旧的 thinking_budget 参数一起使用,因为它们不兼容,会导致 400 错误。
媒体分辨率控制
在分析图像、PDF 文档或视频时,您现在可以调节分析视觉输入时的虚拟处理器使用率:
- 图像:
media_resolution_high可获得最佳质量(每图像 1120 个标记)。 - PDF:
media_resolution_medium用于文档理解(每帧 560 个标记)。 - 视频:
media_resolution_low用于动作识别(每帧 70 个标记),media_resolution_high用于对话密集型文本(每帧 280 个标记)。
这使您可以自行优化质量和标记使用率。
温度设置
您可能会对以下功能感兴趣:您可以将温度设置为默认值 1.0。与以往型号通常会有效利用温度调整不同,Gemini 3 的推理是围绕此默认设置进行优化的。降低温度可能会导致奇怪的循环或降低更复杂任务的性能。
跟我一起构建:Gemini 3 Pro API实战示例
演示 1:构建智能代码分析器
让我们使用一个实际用例来构建一个程序。我们将创建一个系统,该系统首先分析代码,识别差异,然后使用 Gemini 3 Pro 的高级推理功能提出改进建议。
Python实现
import os
from google import genai
# Initialize the Gemini API client with your API key
# You can set this directly or via environment variable
api_key = "api-key" # Replace with your actual API key
client = genai.Client(api_key=api_key)
def analyze_code(code_snippet: str) -> str:
"""
Analyzes code for discrepancies and suggests improvements using Gemini 3 Pro.
Args:
code_snippet: The code to analyze
Returns:
Analysis and improvement suggestions from the model
"""
response = client.models.generate_content(
model="gemini-3-pro-preview",
contents=[
{
"text": f"""Analyze this code for issues, inefficiencies, and potential improvements.
Provide:
1. Issues found (bugs, logic errors, security concerns)
2. Performance optimizations
3. Code quality improvements
4. Best practices violations
5. Refactored version with explanations
Code to analyze:
{code_snippet}
Be direct and concise in your analysis."""
}
]
)
return response.text
# Example usage
sample_code = """
def calculate_total(items):
total = 0
for i in range(len(items)):
total = total + items[i]['price'] * items[i]['quantity']
return total
def get_user_data(user_id):
import requests
response = requests.get(f"http://api.example.com/user/{user_id}")
data = response.json()
return data
"""
print("=" * 60)
print("GEMINI 3 PRO - SMART CODE ANALYZER")
print("=" * 60)
print("\nAnalyzing code...\n")
# Run the analysis
analysis = analyze_code(sample_code)
print(analysis)
print("\n" + "=" * 60)
输出:

这里发生了什么?
- 由于代码审查需要大量的推理,因此我们采用了
thinking_level ("high")。 - 提示简洁明了。Gemini 3 在提示直接的情况下比精心设计的提示更有效。
- 模型将运用完整的推理能力审查代码,并提供包含重要修改和深入分析的响应版本。
演示 2:多模态文档智能
现在,让我们来看一个更复杂的用例:分析文档图像并提取结构化信息。
Python实现
import base64
import json
from google import genai
# Initialize the Gemini API client
api_key = "api-key-here" # Replace with your actual API key
client = genai.Client(api_key=api_key)
def analyze_document_image(image_path: str) -> dict:
"""
Analyzes a document image and extracts key information.
Handles images, PDFs, and other document formats.
Args:
image_path: Path to the document image file
Returns:
Dictionary containing extracted document information as JSON
"""
# Read and encode the image
with open(image_path, "rb") as img_file:
image_data = base64.standard_b64encode(img_file.read()).decode()
# Determine the MIME type based on file extension
mime_type = "image/jpeg" # Default
if image_path.endswith(".png"):
mime_type = "image/png"
elif image_path.endswith(".pdf"):
mime_type = "application/pdf"
elif image_path.endswith(".gif"):
mime_type = "image/gif"
elif image_path.endswith(".webp"):
mime_type = "image/webp"
# Call the Gemini API with multimodal content
response = client.models.generate_content(
model="gemini-3-pro-preview",
contents=[
{
"text": """Extract and structure all information from this document image.
Return the data as JSON with these fields:
- document_type: What type of document is this?
- key_entities: List of important names, dates, amounts, etc.
- main_content: Brief summary of the document's purpose
- action_items: Any tasks or deadlines mentioned
- confidence: How confident you are in the extraction (high/medium/low)
Return ONLY valid JSON, no markdown formatting."""
},
{
"inline_data": {
"mime_type": mime_type,
"data": image_data
}
}
]
)
# Parse the JSON response
try:
result = json.loads(response.text)
return result
except json.JSONDecodeError:
return {
"error": "Failed to parse response",
"raw": response.text
}
# Example usage with a sample document
print("=" * 70)
print("GEMINI 3 PRO - MULTI-MODAL DOCUMENT INTELLIGENCE")
print("=" * 70)
document_path = "Gemini-3-Pro-Model-Card.pdf" # Change this to your actual document path
try:
print(f"\nAnalyzing document: {document_path}")
print("Processing...\n")
document_info = analyze_document_image(document_path)
print("Extracted Document Information:")
print("-" * 70)
print(json.dumps(document_info, indent=2))
except FileNotFoundError:
print(f"Error: Document file '{document_path}' not found.")
print("Please provide a valid path to a document image (JPG, PNG, PDF, etc.)")
print("\nExample:")
print(' document_info = analyze_document_image("invoice.pdf")')
print(' document_info = analyze_document_image("contract.png")')
print(' document_info = analyze_document_image("receipt.jpg")')
except Exception as e:
print(f"Error processing document: {str(e)}")
print("\n" + "=" * 70)
输出:

关键技术:
- 图像处理:我们使用 base64 格式对图片进行编码以便交付。
- 最高质量选项:对于文本文件,我们应用
media_resolution_high以提供完美的 OCR 识别。 - 有序结果:我们要求提供易于与其他系统连接的 JSON 格式。
- 错误处理:我们采用能够最大限度减少 JSON 解析错误的方式。
高级功能:超越基本提示
思维签名:维护推理上下文
Gemini 3 Pro 引入了一项名为“思维签名”的强大功能,它对模型内部推理过程进行加密表示。在使用函数调用或多轮对话时,这些模型签名会在 API 调用中保留上下文信息。
如果您选择使用官方的 Python 或 Node.js SDK,则思维签名将自动且不可见地处理。但如果您进行原始 API 调用,则需要按原样返回接收到的思维签名。
上下文缓存优化成本
您是否计划多次发送类似的请求?利用上下文缓存,它可以缓存提示的前 2,048 个令牌,从而节省后续请求的成本。如果您需要处理大量文档,并且可以在处理过程中重复使用系统提示,那么上下文缓存将非常实用。
批量API:大规模处理
对于时间要求不高的工作负载,批量 API 可以节省高达 90% 的成本。这对于需要处理大量文档或需要在夜间运行大型分析的工作负载来说非常理想。
小结
Google Gemini 3 Pro 标志着 AI API 功能的一个转折点。高级推理、超大上下文窗口和经济实惠的价格相结合,意味着您现在可以构建以前难以实现的系统。
从小处着手:构建聊天机器人、分析一些文档或自动化一些例行任务。然后,随着您对 API 的熟悉程度加深,您可以探索更复杂的场景,例如自主代理、代码生成和多模态分析。


评论留言