Google Gemini 使用指南¶
Google Gemini 系列模型具有业界领先的 1M+ 超长上下文、原生视频理解和极低的价格,特别适合长文档分析和多模态任务。
模型概览¶
推荐模型¶
| 模型 | 上下文 | 特色 | 适用场景 |
|---|---|---|---|
| gemini-2.0-flash-exp | 1M | 最新模型、极低价格、视频理解 | 通用对话、长文档分析、多模态 |
| gemini-1.5-pro | 1M | 平衡性能和成本 | 复杂推理、代码生成 |
| gemini-1.5-flash | 1M | 极低价格、快速响应 | 简单对话、快速响应 |
模型选择建议¶
from tfrobot.brain.chain.llms import Gemini
# 通用场景(推荐)
llm = Gemini(name="gemini-2.0-flash-exp")
# 成本敏感
llm = Gemini(name="gemini-1.5-flash")
# 复杂推理
llm = Gemini(name="gemini-1.5-pro")
配置参数¶
核心参数¶
from tfrobot.brain.chain.llms import Gemini
llm = Gemini(
name="gemini-2.0-flash-exp",
temperature=0.7, # 0.0-2.0,控制随机性
max_tokens=4096, # 最大输出 tokens
top_p=0.95, # 0.0-1.0,核采样
top_k=40, # 1-∞,top-k 采样
stream=False, # 是否流式输出
)
API 配置¶
from tfrobot.brain.chain.llms import Gemini
llm = Gemini(
name="gemini-2.0-flash-exp",
google_api_key="...", # API 密钥(推荐使用环境变量)
google_api_base="https://...", # API 基础 URL
timeout=60.0, # 请求超时时间
max_retries=3, # 最大重试次数
)
代理配置¶
Gemini 支持 SOCKS5 和 HTTP 代理:
from tfrobot.brain.chain.llms import Gemini
# SOCKS5 代理
llm = Gemini(
name="gemini-2.0-flash-exp", proxies={"http": "socks5://127.0.0.1:1080", "https": "socks5://127.0.0.1:1080"}
)
# 或使用 HTTP 代理
llm = Gemini(name="gemini-2.0-flash-exp", proxies={"http": "http://127.0.0.1:7890", "https": "http://127.0.0.1:7890"})
思考模式(Thinking Mode)¶
Gemini 2.0 系列模型支持思考模式,可以查看模型的推理过程。
配置参数¶
from tfrobot.brain.chain.llms import Gemini
llm = Gemini(
name="gemini-2.0-flash-exp",
thinking_budget=10000, # 思考 token 预算(整数或 "low"|"high")
include_thoughts=True, # 是否在输出中包含思考过程
)
# 结果中的 reasoning_content 字段会包含推理过程
# result = llm.complete(current_input=user_input)
# print(result.generations[0].reasoning_content) # 推理过程
# print(result.generations[0].text) # 最终答案
参数说明¶
| 参数 | 类型 | 默认值 | 说明 |
|---|---|---|---|
thinking_budget |
int|"low" | "high" | - |
include_thoughts |
bool | False | 是否在输出中包含思考过程 |
模型版本差异¶
不同 Gemini 模型对 thinking_budget 的支持范围不同:
| 模型 | budget 范围 | 特殊说明 |
|---|---|---|
| gemini-2.5-pro | 128-32768 或 -1 | -1 表示自动 |
| gemini-2.5-flash | 0-24576 或 -1 | 0 表示关闭 |
| gemini-2.5-flash-lite | 512-24576 或 0 或 -1 | 0 表示关闭,-1 表示自动 |
| gemini-2.0-flash-exp | 0-24576 或 -1 | 0 表示关闭,-1 表示自动 |
注意:TFRobot 会自动根据模型名称验证 thinking_budget 是否在有效范围内,如果超出范围会抛出 ValueError。
简化配置¶
使用 "low" 或 "high" 字符串可以自动设置预算:
from tfrobot.brain.chain.llms import Gemini
# 快速配置
llm = Gemini(
name="gemini-2.0-flash-exp",
thinking_budget="high", # 使用高预算
include_thoughts=True,
)
# 等价于手动设置
llm = Gemini(
name="gemini-2.0-flash-exp",
thinking_budget=20000, # 具体数值
include_thoughts=True,
)
模型支持检测¶
通过 LLMeta 机制自动检测模型是否支持思考模式:
from whosellm import LLMeta
llm_meta = LLMeta("gemini-2.0-flash-exp")
if llm_meta.capabilities.supports_thinking:
print("该模型支持思考模式")
#> 该模型支持思考模式
API 映射¶
TFRobot 参数会自动转换为 Gemini API 格式:
from tfrobot.brain.chain.llms import Gemini
# TFRobot 配置
llm = Gemini(
name="gemini-2.0-flash-exp",
thinking_budget=10000,
include_thoughts=True,
)
# 转换为 Gemini API 请求
{"model": "gemini-2.0-flash-exp", "thinking_spec": {"include_thoughts": True, "thinking_budget": 10000}}
工具调用¶
原生模式(推荐)¶
from tfrobot.brain.chain.llms import GeminiWithTools
from tfrobot.brain.chain.prompt.tool_prompt import ToolPrompt
from tfrobot.drive.tool.tool import tool
@tool
def get_weather(city: str) -> str:
"""获取指定城市的天气"""
return f"{city} 今天晴天,温度 25°C"
llm = GeminiWithTools(name="gemini-2.0-flash-exp")
llm.system_msg_prompt = [ToolPrompt()]
# result = llm.complete(
# current_input=TextMessage(content="北京今天的天气怎么样?"),
# tools=[get_weather]
# )
Gemini vs GeminiWithTools¶
- Gemini:基础模型,需要手动配置
ToolPrompt - GeminiWithTools:预配置
ToolPrompt,更方便
from tfrobot.brain.chain.llms import Gemini, GeminiWithTools
from tfrobot.brain.chain.prompt.tool_prompt import ToolPrompt
# 方式一:使用 Gemini
llm = Gemini(name="gemini-2.0-flash-exp")
llm.system_msg_prompt.append(ToolPrompt())
# 方式二:使用 GeminiWithTools(推荐)
llm = GeminiWithTools(name="gemini-2.0-flash-exp")
多模态支持¶
图片理解¶
from tfrobot.schema.message.conversation.message_dto import MultiPartMessage
from tfrobot.schema.message.msg_part import ImagePart, ImgUrl, TextPart
from tfrobot.schema.users import BaseUser
user = BaseUser(name="用户", uid="1")
msg = MultiPartMessage(
content=[
TextPart(text="这张图片里有什么?"),
ImagePart(
image_url=ImgUrl(url="path/to/image.jpg", mime_type="image/jpeg"), detail="high"
), # "low" | "high" | "auto"
],
creator=user,
)
# result = llm.complete(current_input=msg)
视频理解¶
Gemini 原生支持视频理解(业界领先):
from tfrobot.schema.message.conversation.message_dto import MultiPartMessage
from tfrobot.schema.message.msg_part import TextPart, VideoPart, VideoUrl
from tfrobot.schema.users import BaseUser
user = BaseUser(name="用户", uid="1")
msg = MultiPartMessage(
content=[
TextPart(text="描述这个视频的内容"),
VideoPart(video_url=VideoUrl(url="path/to/video.mp4", mime_type="video/mp4")),
],
creator=user,
)
# result = llm.complete(current_input=msg)
音频处理¶
from pathlib import Path
from tfrobot.schema.message.conversation.message_dto import AudioMessage
from tfrobot.schema.users import BaseUser
msg = AudioMessage(content=Path("path/to/audio.mp3"), creator=BaseUser(name="User", uid="1"))
# result = llm.complete(current_input=msg)
PDF 文档分析¶
from tfrobot.schema.message.conversation.message_dto import MultiPartMessage
from tfrobot.schema.message.msg_part import PdfPart, TextPart, VideoUrl
from tfrobot.schema.users import BaseUser
user = BaseUser(name="用户", uid="1")
msg = MultiPartMessage(
content=[
TextPart(text="总结这个 PDF 文档的主要内容"),
PdfPart(pdf_url=VideoUrl(url="path/to/document.pdf", mime_type="application/pdf")),
],
creator=user,
)
# result = llm.complete(current_input=msg)
成本优化¶
Token 计费¶
from tfrobot.brain.chain.llms import Gemini
# 设置价格(用于计费统计)
llm = Gemini(
name="gemini-2.0-flash-exp",
input_price=0.00007, # ¥0.07/百万tokens(示例)
output_price=0.00028, # ¥0.28/百万tokens(示例)
)
节省 Token 的技巧¶
- 利用超长上下文:一次性输入长文档,避免分批处理
- 控制图片分辨率:合理设置
detail参数 - 使用 Flash 模型:简单任务使用
gemini-1.5-flash节省成本
上下文管理¶
设置上下文窗口¶
from tfrobot.brain.chain.llms import Gemini
llm = Gemini(name="gemini-2.0-flash-exp", context_window=1_000_000) # 1M tokens
超长上下文场景¶
Gemini 的 1M 上下文特别适合:
# 长文档分析示例
# with open("large_document.txt", "r") as f:
# long_text = f.read()
#
# msg = TextMessage(content=f"分析以下文档:\n{long_text}")
# result = llm.complete(current_input=msg)
上下文压缩¶
当上下文超出限制时,Chain 会自动触发压缩:
from tfrobot.brain.chain.chain import Chain
from tfrobot.brain.chain.llms import Gemini
# Chain 自动处理
llm = Gemini(name="gemini-2.0-flash-exp")
chain = Chain(llm=llm)
# result = chain.run(input_message=user_input)
错误处理¶
常见错误¶
| 错误类型 | 原因 | 解决方案 |
|---|---|---|
context_length_exceeded |
上下文超长 | 使用 Chain 的 compact 功能 |
rate_limit_error |
API 限流 | 自动重试(已配置) |
invalid_api_key |
API 密钥错误 | 检查环境变量 |
quota_exceeded |
配额不足 | 检查 Google Cloud 配额 |
手动错误处理¶
# 手动错误处理示例
# try:
# result = llm.complete(current_input=user_input)
# except Exception as e:
# if "context" in str(e).lower():
# # 手动压缩
# compacted, _, _, _, _ = llm.collapse_context(
# current_input=user_input,
# conversation=conversation,
# to_size=800_000
# )
# result = llm.complete(current_input=user_input, conversation=compacted)
高级用法¶
流式输出¶
from tfrobot.brain.chain.llms import Gemini
llm = Gemini(name="gemini-2.0-flash-exp", stream=True)
# result = llm.complete(current_input=user_input)
# result.generations[0].text 会逐步生成
思考模式应用¶
from tfrobot.brain.chain.llms import Gemini
# 需要展示推理过程的任务
llm = Gemini(name="gemini-2.0-flash-exp", thinking_budget=5000, include_thoughts=True)
# result = llm.complete(
# current_input=TextMessage(content="解释量子纠缠的原理")
# )
# 思考过程可以在 result.meta_info 中查看
并行处理¶
import asyncio
async def batch_process(llm, inputs):
tasks = [llm.async_complete(current_input=inp) for inp in inputs]
results = await asyncio.gather(*tasks)
return results
最佳实践¶
1. Temperature 设置¶
from tfrobot.brain.chain.llms import Gemini
# 需要创造性(如写作)
llm = Gemini(name="gemini-2.0-flash-exp", temperature=1.0)
# 需要稳定性(如代码生成)
llm = Gemini(name="gemini-2.0-flash-exp", temperature=0.0)
2. Prompt 工程¶
from tfrobot.brain.chain.llms import Gemini
from tfrobot.brain.chain.prompt.memo_prompt import MemoPrompt
from tfrobot.brain.chain.prompt.template.jinja2_template import Jinja2PromptTemplate
from tfrobot.brain.chain.prompt.tool_prompt import ToolPrompt
from tfrobot.schema.types import Locale
llm = Gemini(name="gemini-2.0-flash-exp")
llm.system_msg_prompt = [
MemoPrompt(template=Jinja2PromptTemplate(templates={Locale.DEFAULT: "你是一个专业的 Python 开发者。"})),
ToolPrompt(),
]
llm.after_input_msg_prompt = [
MemoPrompt(template=Jinja2PromptTemplate(templates={Locale.DEFAULT: "请使用 Markdown 格式回复,代码块标明语言。"})),
]
3. 利用视频理解¶
from tfrobot.brain.chain.llms import Gemini
from tfrobot.schema.message.conversation.message_dto import MultiPartMessage
from tfrobot.schema.message.msg_part import TextPart, VideoPart, VideoUrl
from tfrobot.schema.users import BaseUser
# 视频分析场景
llm = Gemini(name="gemini-2.0-flash-exp")
user = BaseUser(name="用户", uid="1")
video_msg = MultiPartMessage(
content=[
TextPart(text="分析这个视频中的关键动作和时间线"),
VideoPart(video_url=VideoUrl(url="tutorial.mp4", mime_type="video/mp4")),
],
creator=user,
)
# result = llm.complete(current_input=video_msg)
4. 长文档处理¶
from tfrobot.brain.chain.llms import Gemini
# 一次性处理整本书
llm = Gemini(name="gemini-2.0-flash-exp")
# with open("book.txt", "r") as f:
# book_content = f.read()
#
# summary = llm.complete(
# current_input=TextMessage(content=f"为这本书写详细的摘要:\n{book_content}")
# )