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

如何解决Ollama+Llama3构建ChatBot时的对话历史丢失问题?

问题原因

你的ChatBot无法记住对话历史,核心问题是每次调用Ollama的chat接口时,只传递了当前的用户提问,没有把之前的完整对话历史传给模型。模型没有上下文信息,自然无法理解后续提问和之前对话的关联。

修正方案

需要调整两个关键部分:

  • 修改get_llama_response函数,让它接收完整的对话历史列表,而非单个提问内容。
  • 确保会话中助手消息的角色符合Ollama接口规范(使用assistant而非自定义的llama)。
完整修正代码
import ollama
import streamlit as st

# 修改函数,接收完整对话历史作为参数
def get_llama_response(messages):
    response = ollama.chat(
        model='llama3',
        messages=messages  # 直接传入全部对话历史
    )
    return response['message']['content']

st.title("Llama Knows All")

prompt = st.chat_input("How can I help you today?")

# 初始化会话状态存储历史消息
if 'messages' not in st.session_state:
    st.session_state.messages = []

# 展示所有历史消息
for message in st.session_state.messages:
    st.chat_message(message['role']).markdown(message['content'])

if prompt:
    # 显示并存储当前用户消息
    st.chat_message('user').markdown(prompt)
    st.session_state.messages.append({'role':'user', 'content': prompt})

    # 传入完整对话历史获取模型响应
    llama_response = get_llama_response(st.session_state.messages)

    # 显示并存储助手响应,角色改为assistant
    st.chat_message('assistant').markdown(llama_response)
    st.session_state.messages.append({'role': 'assistant', 'content': llama_response})
关键修改说明
  • 传递对话历史:现在调用get_llama_response时,会把st.session_state.messages里存储的所有历史消息(包括用户之前的提问和助手的回复)一起传给Ollama,模型就能基于上下文生成连贯的回答。
  • 修正角色名称:Ollama的chat接口要求助手角色必须为assistant,之前自定义的llama可能导致接口解析异常,修正后能确保对话格式符合规范。

内容的提问来源于stack exchange,提问作者Mr.A

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 03:02:41