Gemini 3 开发者使用指南
API 调用方法
Gemini 3 是谷歌迄今为止最智能的模型系列,以先进的推理能力为基础。它旨在通过掌握智能体工作流、自主编码和复杂的多模态任务,将任何想法变为现实。本指南介绍了 Gemini 3 模型系列的主要功能,以及如何充分利用这些功能。
提示
使用前请先更新 Google SDK 到最新版本!
快速开始
动态思考模型
Gemini 3 Pro 默认使用动态思考来推理提示。如果不需要复杂的推理,您可以将模型的思维水平限制为 low,以获得更快、更低延迟的响应。
示例代码
# ============================================================================
# DMXAPI Gemini API 测试脚本
# 描述: 通过 Google Genai 库调用 DMXAPI Gemini 3 Pro 预览版模型进行内容生成
# ============================================================================
from google import genai
# ─────────────────────────────────────────────────────────────────────────
# DMXAPI 配置
# ─────────────────────────────────────────────────────────────────────────
# DMXAPI 密钥:用于身份验证和授权
API_KEY = "sk-*******************************************"
# DMXAPI 基础 URL:指定 API 服务的端点地址
BASE_URL = "https://www.dmxapi.cn"
# ─────────────────────────────────────────────────────────────────────────
# 初始化 Gemini 客户端
# ─────────────────────────────────────────────────────────────────────────
client = genai.Client(
api_key=API_KEY, # 使用配置的 DMXAPI 密钥
http_options={'base_url': BASE_URL} # 设置自定义 DMXAPI 端点
)
# ─────────────────────────────────────────────────────────────────────────
# 生成内容请求
# ─────────────────────────────────────────────────────────────────────────
response = client.models.generate_content(
model="gemini-3-pro-preview", # 指定使用的模型版本
contents="Find the race condition in this multi-threaded C++ snippet: [code here]", # 输入提示词
)
# ─────────────────────────────────────────────────────────────────────────
# 输出结果
# ─────────────────────────────────────────────────────────────────────────
print(response.text) # 打印 API 返回的生成内容返回示例
You haven't pasted the code snippet yet! **[code here]** is just a placeholder.
Please paste the C++ code you want me to analyze, and I will examine it for:
1. **Data Races:** Multiple threads accessing the same memory location without synchronization, where at least one access is a write.
2. **Check-Then-Act issues:** Checking a condition (like `if (!queue.empty())`) and acting on it later, where the state might have changed in between.
3. **Memory Ordering issues:** Assuming operations happen in the exact order written without memory barriers (relevant in lock-free programming).
**Paste the code below, and I'll find the bug.**低思考模型
低思考非常适合以速度为优先的高吞吐量任务,其延迟时间大致与 Gemini 2.5 Flash 相当,但可提供更出色的响应质量。
示例代码
# ============================================================================
# Google Generative AI API 测试脚本
# 功能:调用 Gemini 3 Pro Preview 模型进行内容生成
# ============================================================================
from google import genai
from google.genai import types
# API 配置信息
# ============================================================================
API_KEY = "sk-*******************************************" # API 密钥
BASE_URL = "https://www.dmxapi.cn" # 服务器基础 URL
# 初始化 API 客户端
# ============================================================================
client = genai.Client(
api_key=API_KEY,
http_options={'base_url': BASE_URL}
)
# 生成内容请求
# ============================================================================
response = client.models.generate_content(
model="gemini-3-pro-preview", # 使用的模型
contents="How does AI work?", # 提示词
config=types.GenerateContentConfig(
thinking_config=types.ThinkingConfig(thinking_level="low") # 思考等级设置为低
),
)
# 输出结果
# ============================================================================
print(response.text)返回示例
At its simplest level, Artificial Intelligence (AI) works through **probability** and **pattern recognition**, not by "thinking" the way a human does.
Instead of being explicitly programmed with rules for every possible scenario (like traditional software), AI systems are designed to **learn** from data.
Here is a breakdown of how it works, step-by-step.
---
### 1. It Starts with Data (The "Food")
Imagine you want to teach a computer to recognize a cat.
* **Traditional Programming:** You would have to write code defining a cat: "It has triangular ears, whiskers, and four legs." (This fails because some cats have folded ears, or are missing a leg, or are hiding their whiskers).
* **AI Approach:** You feed the computer 100,000 photos labeled "Cat" and 100,000 photos labeled "Not Cat."
### 2. The Training Process (The "Learning")
The AI processes these images using an algorithm. This phase is called **Machine Learning**.
During training, the AI guesses what is in the picture.
1. It looks at a picture of a cat and guesses "Dog."
2. The system is told, "Wrong. That is a cat."
3. The AI makes a tiny mathematical adjustment to its internal settings.
4. It repeats this millions of times.
Eventually, the AI stops looking for specific rules (like "triangular ears") and starts recognizing complex mathematical patterns in the pixels that humans might not even consciously notice.
### 3. Neural Networks (The "Brain")
Most modern AI (including ChatGPT and image generators) uses something called a **Neural Network**. This is inspired by the human brain.
Imagine a series of layers, like a stack of filters:
* **Layer 1:** Looks at the raw pixels.
* **Layer 2:** Identifies simple edges and lines.
* **Layer 3:** Identifies shapes (circles, squares).
* **Layer 4:** Identifies textures (fur, eyes).
* **Layer 5:** Asks, "Does this collection of shapes and textures look like the 'Cat' pattern I learned?"
Each connection between these layers has a "weight." If the AI guesses right, the connections used to make that guess get stronger. If it guesses wrong, they get weaker.
### 4. Types of Learning
AI learns in three main ways:
* **Supervised Learning (Flashcards):** Humans label the data. "This is a picture of a tumor; this is a picture of healthy tissue." The AI learns to distinguish between them.
* **Unsupervised Learning (Pattern Hunting):** The AI is given a massive amount of data with *no* labels and told to find structure. For example, "Here is a year's worth of purchase data from a grocery store; group the customers into types."
* **Reinforcement Learning (Trial and Error):** The AI is placed in an environment (like a video game or a chess match) and gets "points" for winning and loses points for losing. It plays against itself millions of times to figure out the winning strategy.
### 5. Inference (The "Test")
Once the AI is trained, the learning phase stops. The model is now "frozen." This is the version of AI you use.
When you ask ChatGPT a question or show your phone a picture of your face to unlock it, the AI isn't "learning" in that moment. It is performing **Inference**. It is applying the patterns it learned previously to new data to make a prediction.
***
### A Note on Generative AI (like ChatGPT)
Large Language Models (LLMs) work slightly differently. They are **prediction machines**.
They have read almost everything on the internet. When you type "The cat sat on the...", the AI analyzes the mathematical relationships between words. It calculates that there is a:
* 0.01% chance the next word is "moon."
* 0.1% chance the next word is "table."
* 95% chance the next word is "mat."
It selects "mat" not because it knows what a cat or a mat is, but because statistically, those words appear together in that order. It does this one word at a time, billions of times, to generate full essays.
### Summary
AI does not "know" anything. It is a massive mathematical engine that looks at the past (data) to predict the future (answers).探索
Gemini 3 Pro 是新系列中的首款模型。gemini-3-pro-preview 最适合需要广泛的世界知识和跨模态的高级推理的复杂任务。
模型规格
| 模型 ID | 上下文窗口(输入 / 输出) | 知识截止时间 | 原厂价格(输入 / 输出)* |
|---|---|---|---|
| gemini-3-pro-preview | 100 万 / 6.4 万 | 2025 年 1 月 | 2 美元 / 12 美元(< 20 万 tokens) 4 美元 / 18 美元(> 20 万 tokens) |
* 价格按每 100 万个 tokens 计算。所列价格为标准文本价格;多模态输入费率可能会有所不同。
新功能
Gemini 3 引入了新的参数,旨在让开发者更好地控制延迟时间、费用和多模态保真度。
思考等级
thinking_level 参数用于控制模型在生成响应之前进行内部推理过程的最大深度。Gemini 3 将这些级别视为相对的思考许可,而不是严格的 token 保证。如果未指定 thinking_level,Gemini 3 Pro 将默认为 high。
可用级别:
low:尽可能缩短延迟时间并降低费用。最适合简单的指令遵循、聊天或高吞吐量应用。medium:(即将推出)发布时不支持。high(默认):最大限度地提高推理深度。模型可能需要更长时间才能生成第一个 token,但输出结果会经过更仔细的推理。
警告
您不能在同一请求中同时使用 thinking_level 和旧版 thinking_budget 参数。这样做会返回 400 错误。
媒体分辨率
Gemini 3 通过 media_resolution 参数引入了对多模态视觉处理的精细控制。分辨率越高,模型读取细小文本或识别细微细节的能力就越强,但会增加 token 用量和延迟时间。media_resolution 参数用于确定为每个输入图片或视频帧分配的 token 数量上限。
现在,您可以为每个媒体部分单独设置分辨率,也可以通过 generation_config 全局设置分辨率,分辨率可设置为 media_resolution_low、media_resolution_medium 或 media_resolution_high。如果未指定,模型会根据媒体类型使用最佳默认值。
推荐设置
| 媒体类型 | 推荐设置 | Token 数量上限 | 使用指南 |
|---|---|---|---|
| 图片 | media_resolution_high | 1120 | 建议用于大多数图片分析任务,以确保获得最佳质量。 |
media_resolution_medium | 560 | 非常适合文档理解;质量通常在 medium 时达到饱和。增加到 high 很少能改进标准文档的 OCR 结果。 | |
| 视频(常规) | media_resolution_low(或 media_resolution_medium) | 70(每帧) | 注意:对于视频,low 和 medium 设置的处理方式相同(70 个 tokens),以优化上下文使用情况。这对于大多数动作识别和描述任务来说已经足够。 |
| 视频(文字较多) | media_resolution_high | 280(每帧) | 仅当用例涉及读取密集文本(OCR)或视频帧中的微小细节时才需要。 |
注意
media_resolution 参数会根据输入类型映射到不同的 token 数量。虽然图片是线性缩放的(media_resolution_low:280,media_resolution_medium:560,media_resolution_high:1120),但视频的压缩程度更高。对于视频,media_resolution_low 和 media_resolution_medium 的上限均为每帧 70 个 tokens,media_resolution_high 的上限为 280 个 tokens。
示例代码
"""
Gemini 3 Pro 图片分析示例
使用 DMXAPI 调用 Gemini 3 Pro 模型进行图片内容识别
"""
from google import genai
from google.genai import types
# ===========================================
# DMXAPI 配置
# ===========================================
API_KEY = "sk-*******************************************"
BASE_URL = "https://www.dmxapi.cn"
# 初始化客户端
client = genai.Client(
api_key=API_KEY,
http_options={'base_url': BASE_URL}
)
# ===========================================
# 读取图片
# ===========================================
# 支持的图片格式: JPEG, PNG, GIF, WebP
# 对应的 mime_type:
# - JPEG: "image/jpeg"
# - PNG: "image/png"
# - GIF: "image/gif"
# - WebP: "image/webp"
image_path = "test/example.jpg" # 替换为你的图片路径
with open(image_path, "rb") as f:
image_data = f.read()
# ===========================================
# 调用模型
# ===========================================
# media_resolution 参数说明:
# - media_resolution_low: 280 tokens, 适合快速处理
# - media_resolution_medium: 560 tokens, 平衡质量与速度
# - media_resolution_high: 1120 tokens, 最佳质量, 适合细节识别
response = client.models.generate_content(
model="gemini-3-pro-preview",
contents=[
types.Content(
parts=[
types.Part(text="这张图片里有什么?"),
types.Part(
inline_data=types.Blob(
mime_type="image/jpeg",
data=image_data
),
media_resolution={"level": "media_resolution_high"}
)
]
)
]
)
# ===========================================
# 输出结果
# ===========================================
print(response.text)返回示例
这张图片主要展示了一个**电子计算器**。以下是图片中可见物品的详细描述:
1. **计算器(主体)**:
* **品牌**:Canon(佳能)。
* **型号**:WS-1212H(在显示屏上方可见)。
* **外观**:机身呈灰白色。键盘区域包括浅灰色的数字键(0-9, 00)、深灰色的功能键(如 +, -, x, ÷, MU, GT等)以及两个红色的控制键(ON/CA 和 CI/C)。
* **屏幕**:顶部有一个长条形的液晶显示屏,屏幕上方稍微有些反光。
2. **背景/底部**:
* 计算器放置在一个带有**抽象艺术图案的垫子**上(很可能是鼠标垫或桌垫)。图案由蓝色、白色和金黄色的流体漩涡纹理组成。
3. **周边物品**:
* **右上角**:有一团**浅蓝色(或薄荷绿)的毛绒织物**,看起来像是一块毛巾或抹布。
* **正上方**:可以看到一根黑色的**数据线**(接头部分可见,像是USB-C或Lightning接口),以及一个白色物体的边缘(可能是书本、纸盒或电子设备的包装)。温度参数
对于 Gemini 3,Google 强烈建议将温度参数保留为默认值 1.0。
虽然之前的模型通常可以通过调整温度来控制创造性与确定性,但 Gemini 3 的推理能力已针对默认设置进行了优化。更改温度(将其设置为低于 1.0)可能会导致意外行为,例如循环或性能下降,尤其是在复杂的数学或推理任务中。
使用工具生成结构化输出(联网搜索)
Gemini 3 可让您将结构化输出与内置工具(包括依托 Google 搜索进行接地、网址上下文和代码执行)结合使用。
示例代码
"""
DMXAPI Gemini 3 Pro 工具调用联网搜索示例
====================================
本示例演示如何使用 Gemini 3 Pro 的 Google Search 工具进行联网搜索,
并将搜索结果转换为结构化的 JSON 输出。
主要功能:
- 调用 Google Search 工具获取实时天气信息
- 使用 Pydantic 模型定义输出结构
- 自动将 AI 响应解析为结构化数据
"""
import os
from google import genai
from google.genai import types
from pydantic import BaseModel, Field
from typing import List
# ==================== 配置部分 ====================
# 从环境变量读取 DMXAPI 配置,如果环境变量不存在则使用默认值
api_key = os.getenv("GEMINI_API_KEY", "sk-*******************************************")
BASE_URL = os.getenv("GEMINI_API_BASE_URL", "https://www.dmxapi.cn")
# ==================== 数据模型定义 ====================
# 使用 Pydantic 定义天气信息的结构化输出模型
# 这个模型将作为 JSON Schema 传递给 AI,确保返回符合预期格式的数据
class WeatherInfo(BaseModel):
"""天气信息数据模型"""
city: str = Field(description="城市名称")
temperature: str = Field(description="当前温度")
weather_condition: str = Field(description="天气状况,例如晴、多云、雨等")
humidity: str = Field(description="湿度百分比", default="")
wind_speed: str = Field(description="风速", default="")
forecast: List[str] = Field(description="未来几天的天气预报", default_factory=list)
# ==================== 初始化客户端 ====================
# 创建 Gemini AI 客户端实例
client = genai.Client(api_key=api_key, http_options={'base_url': BASE_URL})
# ==================== 开始测试 ====================
print("开始测试 Gemini 3 Pro 工具调用生成结构化输出...")
print("=" * 60)
try:
# ==================== 调用 AI 模型 ====================
# 使用 Gemini 3 Pro 模型生成内容
# 关键配置说明:
# 1. tools: 启用 google_search 工具,允许模型进行实时联网搜索
# 2. response_mime_type: 指定返回 JSON 格式
# 3. response_json_schema: 传入 Pydantic 模型的 JSON Schema,确保输出符合预定义结构
response = client.models.generate_content(
model="gemini-3-pro-preview",
contents="搜索今天上海的详细天气信息,包括温度、天气状况、湿度、风速和未来几天的预报。",
config={
"tools": [
{"google_search": {}}, # 启用 Google 搜索工具
],
"response_mime_type": "application/json", # 要求返回 JSON 格式
"response_json_schema": WeatherInfo.model_json_schema(), # 指定 JSON 结构
},
)
# ==================== 处理原始响应 ====================
print("原始响应文本:")
print(response.text)
print("\n" + "=" * 60)
# ==================== 清理 JSON 文本 ====================
# AI 可能返回包含 ```json 或 ``` 标记的文本,需要清理这些标记
# 确保文本可以被正确解析为 JSON
cleaned_text = response.text.strip()
if cleaned_text.startswith("```json"):
cleaned_text = cleaned_text[7:] # 移除开头的 ```json
if cleaned_text.startswith("```"):
cleaned_text = cleaned_text[3:] # 移除开头的 ```
if cleaned_text.endswith("```"):
cleaned_text = cleaned_text[:-3] # 移除末尾的 ```
cleaned_text = cleaned_text.strip()
print("清理后的 JSON:")
print(cleaned_text)
print("\n" + "=" * 60)
# ==================== 解析为结构化对象 ====================
# 使用 Pydantic 将 JSON 文本解析为 WeatherInfo 对象
# 这将自动验证数据是否符合模型定义的结构
result = WeatherInfo.model_validate_json(cleaned_text)
# ==================== 输出结构化数据 ====================
print("\n解析后的结构化数据:")
print(f"城市: {result.city}")
print(f"温度: {result.temperature}")
print(f"天气状况: {result.weather_condition}")
print(f"湿度: {result.humidity}")
print(f"风速: {result.wind_speed}")
print(f"未来天气预报: {', '.join(result.forecast) if result.forecast else '无'}")
print("\n" + "=" * 60)
print("测试成功!")
except Exception as e:
# ==================== 错误处理 ====================
print(f"测试失败,错误信息: {str(e)}")
print(f"错误类型: {type(e).__name__}")返回示例
开始测试 Gemini 3 Pro 工具调用生成结构化输出...
============================================================
原始响应文本:
```json
{
"city": "上海",
"temperature": "12°C",
"weather_condition": "多云",
"forecast": [
"11月21日 (周五): 晴, 8°C - 16°C",
"11月22日 (周六): 晴, 9°C - 17°C",
"11月23日 (周日): 多云, 10°C - 20°C",
"11月24日 (周一): 晴, 7°C - 18°C"
],
"humidity": "45%",
"wind_speed": "西北风1级"
}
============================================================
清理后的 JSON:
{
"city": "上海",
"temperature": "12°C",
"weather_condition": "多云",
"forecast": [
"11月21日 (周五): 晴, 8°C - 16°C",
"11月22日 (周六): 晴, 9°C - 17°C",
"11月23日 (周日): 多云, 10°C - 20°C",
"11月24日 (周一): 晴, 7°C - 18°C"
],
"humidity": "45%",
"wind_speed": "西北风1级"
}
============================================================
解析后的结构化数据:
城市: 上海
温度: 12°C
天气状况: 多云
湿度: 45%
风速: 西北风1级
未来天气预报: 11月21日 (周五): 晴, 8°C - 16°C, 11月22日 (周六): 晴, 9°C - 17°C, 11月23日 (周日): 多云, 10°C - 20°C, 11月24日 (周一): 晴, 7°C - 18°C
============================================================
测试成功!OpenAI 兼容性
对于使用 OpenAI 兼容层的用户,标准参数会自动映射到 Gemini 等效参数:
reasoning_effort(OpenAI)映射到 thinking_level(Gemini)。请注意,reasoning_effort medium 映射到 thinking_level high。
提示最佳实践
Gemini 3 是一种推理模型,因此您需要改变提示方式。
精确的指令: 输入提示应简洁明了。Gemini 3 最适合处理直接、清晰的指令。它可能会过度分析用于旧模型的冗长或过于复杂的提示工程技术。
输出详细程度: 默认情况下,Gemini 3 的输出详细程度较低,更倾向于提供直接、高效的答案。如果您的使用情形需要更具对话性或"聊天"风格的角色,您必须在提示中明确引导模型(例如,"以友善健谈的助理的身份解释一下")。
上下文管理: 处理大型数据集(例如整本书、代码库或长视频)时,请将具体指令或问题放在提示末尾的数据上下文之后。在提问时,以"根据上述信息…"之类的短语开头,将模型的推理锚定到提供的数据。
常见问题解答
Q: Gemini 3 Pro 的知识截止日期是什么? A: Gemini 3 的知识截止日期为 2025 年 1 月。
Q: 上下文窗口有哪些限制? A: Gemini 3 Pro 支持 100 万个 tokens 的输入上下文窗口,输出最多可达 6.4 万个 tokens。
Q: 我的旧 thinking_budget 代码是否仍然有效? A: 可以,为了实现向后兼容性,我们仍支持 thinking_budget,但建议您迁移到 thinking_level 以获得更可预测的性能。请勿在同一请求中同时使用这两个参数。
