EN

Gemini 2.0 API 教程 2026:拥有 200 万 Token 上下文的 multimodal AI

使用 Gemini 2.0 Flash 和 Pro 构建 multimodal AI 应用:视觉、音频、文档

返回教程列表🌐 Read in English
进阶35 分钟
AI Skill Navigation 编辑团队发布于 2026年5月28日

Gemini 2.0 API 教程 2026:拥有 200 万 Token 上下文的 multimodal AI

使用 Gemini 2.0 Flash 和 Pro 构建 multimodal AI 应用:视觉、音频、文档

完整的 Gemini 2.0 API 教程,涵盖 multimodal 输入、200 万 token 上下文、函数调用、Google 搜索接地以及代码执行。

Gemini 2.0 API 教程 2026:拥有 200 万 Token 上下文的 multimodal AI

Gemini 2.0 是 Google 最强大的 multimodal 模型,拥有 200 万 token 的上下文窗口。

模型

模型上下文最佳用途每百万成本

Gemini 2.0 Flash1M快速、经济高效$0.075/$0.30 Gemini 2.0 Pro2M复杂、大型文档$3.50/$10.50 Gemini 2.0 Thinking1M推理$0.15/$0.60

设置

bash
pip install google-generativeai

python
import google.generativeai as genai
genai.configure(api_key='your-key')

文本生成

python
model = genai.GenerativeModel('gemini-2.0-flash')
response = model.generate_content('解释 RAG 与微调的区别')
print(response.text)

流式输出

for chunk in model.generate_content('编写一个 FastAPI 教程', stream=True): print(chunk.text, end='', flush=True)

图像理解

python
import PIL.Image

model = genai.GenerativeModel('gemini-2.0-flash') image = PIL.Image.open('screenshot.png')

response = model.generate_content([ image, '哪些 UI 元素可见?描述所有交互组件。' ]) print(response.text)

比较多张图片

chart1 = PIL.Image.open('q1_sales.png') chart2 = PIL.Image.open('q2_sales.png') response = model.generate_content([chart1, chart2, '比较 Q1 和 Q2 的趋势'])

大型文档分析(200 万上下文)

python

处理整个 PDF 报告

with open('annual_report.pdf', 'rb') as f: pdf = f.read()

response = model.generate_content([ {'mime_type': 'application/pdf', 'data': pdf}, '总结关键财务亮点、风险和增长机会。' ])

处理整个代码库(50 万+ token)

with open('codebase.txt') as f: code = f.read() response = model.generate_content(f'代码库:\n{code}\n\n找出所有安全漏洞。')

音频处理

python
import base64

with open('meeting.mp3', 'rb') as f: audio = f.read()

response = model.generate_content([ {'mime_type': 'audio/mp3', 'data': base64.b64encode(audio).decode()}, '转录此音频并提供摘要及行动项。' ])

函数调用

python
tools = genai.protos.Tool(
    function_declarations=[genai.protos.FunctionDeclaration(
        name='get_stock_price',
        description='获取当前股票价格',
        parameters=genai.protos.Schema(
            type=genai.protos.Type.OBJECT,
            properties={'symbol': genai.protos.Schema(type=genai.protos.Type.STRING)},
            required=['symbol']
        )
    )]
)

model = genai.GenerativeModel('gemini-2.0-pro', tools=[tools]) response = model.generate_content('AAPL 的价格是多少?') fc = response.candidates[0].content.parts[0].function_call print(f'{fc.name}({dict(fc.args)})')

使用 Google 搜索接地

python
model = genai.GenerativeModel('gemini-2.0-flash', tools=['google_search_retrieval'])
response = model.generate_content('2026 年 5 月最新发布的 AI 模型有哪些?')
print(response.text)  # 基于实时搜索

结论

Gemini 2.0 在 multimodal 任务和大型文档分析方面表现出色。其 200 万 token 的上下文窗口是处理整个代码库或完整文档档案的真正差异化优势。

相关工具

google-aipython
所属主题:API 与集成开发