本地Jupyter运行Gemini API教程遇两类错误求助
Gemini API本地Jupyter环境运行异常排查建议
我正在学习Gemini API的Python版Jupyter Notebook教程,该教程在Google Colab中运行正常,但在本地Python 3.11的Anaconda Jupyter环境中运行时出现两个异常,以下是问题详情及排查解决建议:
错误1:执行模型列表代码时触发AttributeError
触发场景
执行以下代码时出错:
for m in genai.list_models(): if 'generateContent' in m.supported_generation_methods: print(m.name)
错误日志
--------------------------------------------------------------------------- AttributeError Traceback (most recent call last) Cell In[28], line 1 ----> 1 for m in genai.list_models(): 2 if 'generateContent' in m.supported_generation_methods: 3 print(m.name) File /opt/anaconda3/envs/base_ML_AI/lib/python3.11/site-packages/google/generativeai/models.py:191, in list_models(page_size, client, request_options) 188 client = get_default_model_client() 190 for model in client.list_models(page_size=page_size, **request_options): --> 191 model = type(model).to_dict(model) 192 yield model_types.Model(**model) AttributeError: to_dict
排查与解决建议
- 检查并升级
google-generativeai库:Colab环境通常保持最新版本,本地环境可能版本滞后。执行以下命令更新到最新稳定版:pip install --upgrade google-generativeai - 清理依赖冲突:Anaconda环境可能存在旧版Google客户端库冲突,更新核心依赖确保兼容性:
pip install --upgrade google-api-core google-auth - 手动处理模型对象:若升级后仍有问题,显式转换模型对象格式绕过
to_dict方法:import google.generativeai as genai from google.generativeai.client import get_default_model_client client = get_default_model_client() for model in client.list_models(): model_dict = dict(model) m = genai.types.Model(**model_dict) if 'generateContent' in m.supported_generation_methods: print(m.name)
错误2:提取响应文本时触发TypeError
触发场景
执行to_markdown(response.text)时出错。
错误日志
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[42], line 1 ----> 1 to_markdown(response.text) File /opt/anaconda3/envs/base_ML_AI/lib/python3.11/site-packages/google/generativeai/types/generation_types.py:407, in BaseGenerateContentResponse.text(self) 400 if not parts: 401 raise ValueError( 402 "The `response.text` quick accessor only works when the response contains a valid " 403 "`Part`, but none was returned. Check the `candidate.safety_ratings` to see if the " 404 "response was blocked." 405 ) --> 407 if len(parts) != 1 or "text" not in parts[0]: 408 raise ValueError( 409 "The `response.text` quick accessor only works for " 410 "simple (single-`Part`) text responses. This response is not simple text. " (...) 413 "instead." 414 ) 415 return parts[0].text TypeError: argument of type 'Part' is not iterable
排查与解决建议
- 升级
google-generativeai库:该错误多为旧版本库中Part对象的迭代判断逻辑bug导致,升级到最新版本即可修复。 - 手动提取响应文本:若暂时无法升级,绕过
response.text快捷属性,直接从响应结构中提取:# 替代response.text的手动提取方式 text = response.candidates[0].content.parts[0].text to_markdown(text) - 验证响应结构:打印
response.candidates[0].content.parts确认返回内容为纯文本类型Part,排除因安全拦截或格式不匹配导致的异常。
内容的提问来源于stack exchange,提问作者Janek Podwysocki
相关产品推荐
相关产品推荐

