Skip to main content

Streamlit 聊天消息历史记录 (Streamlit Chat Message History)

本文档介绍如何在 Streamlit 应用中存储和使用聊天消息历史记录。StreamlitChatMessageHistory 将消息存储在指定的 key= 下的 Streamlit 会话状态 中。默认的键是 "langchain_messages"

  • 注意,StreamlitChatMessageHistory 仅在 Streamlit 应用中运行时有效。
  • 您可能还对 LangChain 的 StreamlitCallbackHandler 感兴趣。
  • 欲了解更多关于 Streamlit 的信息,请参阅他们的 入门文档

您可以在此处查看完整的应用示例,以及在 github.com/langchain-ai/streamlit-agent 中查看更多示例。

from langchain.memory import StreamlitChatMessageHistory

history = StreamlitChatMessageHistory(key="chat_messages")

history.add_user_message("hi!")
history.add_ai_message("whats up?")
history.messages

您可以像往常一样将 StreamlitChatMessageHistory 集成到 ConversationBufferMemory、链或代理中。在给定用户会话中,历史记录将在重新运行 Streamlit 应用时保持不变。给定的 StreamlitChatMessageHistory 不会在用户会话之间持久化或共享。

from langchain.memory import ConversationBufferMemory
from langchain.memory.chat_message_histories import StreamlitChatMessageHistory

# 可选地,为存储消息指定自己的 session_state 键
msgs = StreamlitChatMessageHistory(key="special_app_key")

memory = ConversationBufferMemory(memory_key="history", chat_memory=msgs)
if len(msgs.messages) == 0:
msgs.add_ai_message("How can I help you?")
from langchain.chains import LLMChain
from langchain.llms import OpenAI
from langchain.prompts import PromptTemplate
template = """You are an AI chatbot having a conversation with a human.

{history}
Human: {human_input}
AI: """
prompt = PromptTemplate(input_variables=["history", "human_input"], template=template)

# 像往常一样将内存添加到 LLMChain 中
llm_chain = LLMChain(llm=OpenAI(), prompt=prompt, memory=memory)

在每次重新运行时,对话式 Streamlit 应用通常会重新绘制每条先前的聊天消息。通过迭代 StreamlitChatMessageHistory.messages,这很容易实现:

import streamlit as st

for msg in msgs.messages:
st.chat_message(msg.type).write(msg.content)

if prompt := st.chat_input():
st.chat_message("human").write(prompt)

# 像往常一样,当调用 Chain 时,新消息将添加到 StreamlitChatMessageHistory 中。
response = llm_chain.run(prompt)
st.chat_message("ai").write(response)

查看最终应用