1. 问题重现与错误分析
最近在使用Google Gemini Pro API进行多轮对话开发时,遇到了一个典型的类型错误。这个错误表面看起来是Blob对象创建失败,但实际上涉及更深层次的API使用问题。让我们先完整重现这个场景:
python复制import google.generativeai as genai
# 初始化模型
model = genai.GenerativeModel("gemini-pro")
# 初始对话
messages = [{'role':'user', 'parts': ['hello']}]
response = model.generate_content(messages) # 第一轮响应正常:"Hello, how can I help"
# 添加响应到对话历史
messages.append(response.candidates[0].content)
messages.append({'role':'user', 'parts': ['How does quantum physics work?']})
# 第二轮对话抛出错误
response = model.generate_content(messages) # TypeError: Could not create `Blob`
1.1 错误根源解析
这个错误的核心在于消息格式的不一致性。当我们查看Gemini Pro API的官方文档时会发现:
- 输入消息需要严格遵循特定的协议缓冲区格式
response.candidates[0].content返回的是Content对象,而不是原始的消息字典- 直接混合使用字典和
Content对象会导致序列化失败
关键提示:Gemini Pro的多轮对话要求所有消息必须保持格式一致,要么全部使用原始字典格式,要么全部使用生成的
Content对象格式。
需要模型API调用? 免费领10W Token,多模型网关一键接入 Claude、DeepSeek 等主流模型。
2. 正确的多轮对话实现方案
2.1 方案一:统一使用字典格式
这是最接近原始代码的修改方案,适合需要完全控制消息内容的场景:
python复制messages = [
{'role': 'user', 'parts': ['hello']}
]
respo
