You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Gemini-Pro多轮聊天触发TypeError错误求助

解决方案

错误原因

你直接将response.candidates[0].content(google.ai.generativelanguage_v1beta.types.content.Content类型对象)添加到了messages列表中,但Gemini的generate_content方法要求消息列表的元素必须是字典格式(结构为{'role': 'user'/'model', 'parts': [内容]}),原生的Content对象不符合要求,因此触发类型错误。

修正方案

方案1:手动转换Content对象为字典格式

提取Content对象的role和parts属性,构造成符合要求的字典后再加入消息列表:

import google.generativeai as genai

# 先配置API密钥:genai.configure(api_key="你的密钥")
model = genai.GenerativeModel("gemini-pro")
messages = [{'role':'user', 'parts': ['hello']}]

# 第一轮对话
response = model.generate_content(messages)
# 将模型响应转换为字典格式后加入消息列表
model_response = {
    'role': response.candidates[0].content.role,
    'parts': [part.text for part in response.candidates[0].content.parts]
}
messages.append(model_response)

# 第二轮对话
messages.append({'role':'user', 'parts': ['How does quantum physics work?']})
response = model.generate_content(messages)
print(response.text)

方案2:使用官方推荐的start_chat()方法(更简洁)

Gemini提供了专门的多轮对话接口start_chat(),无需手动维护消息格式,直接调用send_message()即可:

import google.generativeai as genai

genai.configure(api_key="你的API密钥")
model = genai.GenerativeModel("gemini-pro")
chat = model.start_chat(history=[])

# 第一轮对话
response = chat.send_message("hello")
print(response.text)

# 第二轮对话
response = chat.send_message("How does quantum physics work?")
print(response.text)

这个方法会自动维护聊天历史,无需手动处理消息格式,从根源避免类型错误。

内容的提问来源于stack exchange,提问作者Ron C

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.25 10:33:13