Python调用Llama3报错:'content'键缺失问题求助
解决Ollama调用Llama3时'content'键不存在的错误
错误原因
- 消息角色设置错误:将用户提问的角色设为了
assistant,应该用user角色,错误的角色会导致模型返回的响应结构异常。 - 流式响应取值路径错误:Ollama流式返回的每个响应对象中,
content嵌套在message字段下,而非直接存在于顶层字典。
修复后的代码
import ollama message = "What is football" # 连接Llama3模型 try: response_stream = ollama.chat( model="llama3", messages=[{'role': 'user', 'content': message}], # 修正角色为user stream=True ) print("Connected to Llama3") for response in response_stream: # 从message字段中获取content,end=''保证内容连续输出 print(f"Llama3: {response['message']['content']}", end='') except Exception as e: print(f"Error connecting to Llama3: {e}")
关键修改说明
- 调整
messages中的角色为user:符合对话逻辑,用户发起的提问需要标记为user角色,模型回复对应assistant角色。 - 修正取值路径:通过
response['message']['content']获取回复内容,匹配Ollama流式响应的标准结构。 - 添加
end='':避免流式返回的内容被逐段拆分换行,保证输出的连贯性。
内容的提问来源于stack exchange,提问作者Nived Puthumana Meleppattu
相关产品推荐
相关产品推荐

