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

使用Gemini API调用后返回GenerateContentResponse对象求助

问题原因

model.generate_content()返回的是GenerateContentResponse类实例,直接打印该对象只会输出其类型标识,无法获取实际的响应文本内容,需要访问对象的对应属性来提取文本。

解决方案

有三种常用方式可以提取响应文本:

  • 方式1:直接访问text属性(最简便,适用于纯文本响应)
    修改代码中的print(response)为:

    print(response.text)
    
  • 方式2:用自定义函数格式化展示(适合带列表、换行等格式的响应)
    如果需要保留响应的格式并以Markdown形式展示,替换为:

    display(to_markdown(response.text))
    
  • 方式3:遍历候选内容(当响应包含多候选结果时使用)
    若API返回多个候选响应内容,可通过candidates属性遍历提取:

    for candidate in response.candidates:
        print(candidate.content.parts[0].text)
    
完整修改示例代码
import pathlib
import textwrap

import google.generativeai as genai

from IPython.display import display
from IPython.display import Markdown


def to_markdown(text):
  text = text.replace('•', '  *')
  return Markdown(textwrap.indent(text, '> ', predicate=lambda _: True))


genai.configure(api_key='YOUR_API_KEY')

model = genai.GenerativeModel('gemini-pro')
response = model.generate_content("What is the meaning of life?")
# 直接打印纯文本响应
print(response.text)
# 若需Markdown格式展示,可启用下方代码
# display(to_markdown(response.text))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 19:59:50