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

传入Content对象列表启动Gemini对话仍报ValueError的解决咨询

解决方案

一、排查Content对象类型不匹配问题

你遇到的ValueError: history must be a list of Content objects,大概率是因为导入的Content/Part类并非Vertex AI官方库提供的正确类型。请确保导入语句正确:

from vertexai.generative_models import GenerativeModel, Content, Part

如果导入了其他模块的同名类(比如自定义或其他第三方库的),即使结构一致,也会被判定为非合法的Content对象,触发类型校验错误。

修正导入后,你的原代码应该可以正常运行,完整示例如下:

import json
from vertexai.generative_models import GenerativeModel, Content, Part

# 假设retail_tool和data已提前定义
model = GenerativeModel("gemini-1.0-pro", generation_config={"temperature": 0}, tools=[retail_tool])
context = [
    Content(role="user", parts=[
        Part(text="System prompt: You are an assistant who can process json and answers off that."),
        Part(text=f"json is provided here {json.dumps(data)}")
    ]),
    Content(role="model", parts=[Part(text="understood")])
]
chat2 = model.start_chat(history=context)

二、使用字典列表简化历史记录传入

根据Vertex AI的start_chat函数定义,history参数支持直接传入字典列表(无需构造Content对象),这正是你想要的简化方式。字典结构需对应Content的属性:

  • 每个字典包含role(取值为"user"或"model")和parts字段
  • parts是包含text字段的字典列表

示例代码如下:

import json
from vertexai.generative_models import GenerativeModel

# 假设retail_tool和data已提前定义
model = GenerativeModel("gemini-1.0-pro", generation_config={"temperature": 0}, tools=[retail_tool])
context = [
    {
        "role": "user",
        "parts": [
            {"text": "System prompt: You are an assistant who can process json and answers off that."},
            {"text": f"json is provided here {json.dumps(data)}"}
        ]
    },
    {
        "role": "model",
        "parts": [{"text": "understood"}]
    }
]
chat2 = model.start_chat(history=context)

三、额外注意事项

  • 确保role字段的取值严格为"user"或"model",传入其他值会触发类型错误
  • parts中的每个元素必须包含text键(纯文本对话场景),若涉及多媒体内容则需对应其他字段(如inline_data)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 15:15:57