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

迁移Gemini项目至Vertex AI遇Part类型错误,求无状态对话方案

解决Gemini从Google Generative AI迁移到Vertex AI的Part类型错误

错误原因

Vertex AI的Gemini SDK对对话消息的格式要求更严格:parts数组中的元素必须是Part类实例,而原Google Generative AI库允许直接传入字符串并自动转换为对应类型,这是触发TypeError: Parameter to MergeFrom() must be instance of same class: expected <class 'Part'> got <class 'str'>的核心原因。

解决方案

方案1:保留原无状态对话模式

无需切换到chat方法,只需将消息中parts的字符串内容包装为Part实例即可适配。

  1. 导入Part类:
from google.cloud.aiplatform.generative_models import Part
  1. 修改原有消息结构:
messages = [
    {
        "role": "user", 
        "parts": [Part.from_text(get_system_prompt(bytes_data))]
    }, 
    {
        "role": "model", 
        "parts": [Part.from_text("Hi, I'm Q, your SQL Query Building Helper. Let's get started.")]
    }
]

messages.append({"role": "user", "parts": [Part.from_text(prompt)]})

# 调用Vertex AI的generate_content方法
response = model.generate_content(messages)

方案2:切换到chat方法

如果愿意调整代码结构,使用Vertex AI提供的chat会话模式也能解决问题,该模式会自动处理消息格式细节:

from google.cloud.aiplatform.generative_models import GenerativeModel, ChatSession

# 初始化模型和对话会话
model = GenerativeModel("gemini-1.0-pro")
chat = model.start_chat(
    history=[
        {"role": "user", "parts": [Part.from_text(get_system_prompt(bytes_data))]},
        {"role": "model", "parts": [Part.from_text("Hi, I'm Q, your SQL Query Building Helper. Let's get started.")]}
    ]
)

# 发送新消息
response = chat.send_message(prompt)

总结

两种方案均可行,优先推荐方案1,无需改变原有无状态对话的代码逻辑,仅需对消息内容做简单包装即可适配Vertex AI环境。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 22:22:24