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

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 00:25:56