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

如何将Google Gen AI SDK中types.Content对象的repr字符串转回原对象?

解决Gemini API聊天历史字符串转types.Content对象的问题

问题分析

你遇到的unterminated string literal报错,是因为存储的字符串里包含实际换行符\n,eval解析时会把它当成代码换行,导致字符串未正常闭合。另外直接存储代码字符串到MongoDB既不安全,也容易出现解析异常。

临时修复方案(适配现有存储的字符串)

先处理字符串中的特殊字符(比如换行符),确保eval能正确解析,同时要提前导入对应模块:

from google.generativeai import types

history = []
for part in result["history"]:
    # 转义字符串里的换行符,避免eval解析出错
    cleaned_part = part.replace('\n', '\\n')
    # 转换为Content对象
    content_obj = eval(cleaned_part)
    history.append(content_obj)

推荐的长期解决方案(避免代码字符串存储)

不要直接存types.Content的代码字符串,而是存储结构化字典数据,读取后再重建对象,这更安全且不易出问题:

存储时的转换处理

# 将Content对象转为字典格式,再存入MongoDB
history_to_store = []
for content in original_history:
    history_to_store.append({
        "role": content.role,
        "parts": [{"text": part.text} for part in content.parts]
    })
# 把history_to_store写入MongoDB

读取时的对象重建

from google.generativeai.types import Content, Part

rebuilt_history = []
for item in result["history"]:
    # 重建Part对象列表
    parts = [Part(text=p["text"]) for p in item["parts"]]
    # 重建Content对象
    rebuilt_history.append(Content(role=item["role"], parts=parts))

关键提示

  • eval存在安全风险,如果存储的字符串被篡改,可能执行恶意代码,因此优先使用结构化数据重建的方案。
  • 必须确保导入了正确的模块:from google.generativeai.types import Content, Part,否则eval或重建时会找不到对应类。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.12 23:38:11