跳到主要內容
Open In ColabOpen on GitHub

Streamlit

Streamlit 是一個開放原始碼的 Python 函式庫,可以輕鬆建立和分享用於機器學習和資料科學的美觀、自訂的 Web 應用程式。

本筆記本說明如何在 Streamlit 應用程式中儲存和使用聊天訊息歷史記錄。StreamlitChatMessageHistory 會將訊息儲存在指定的 key=Streamlit 工作階段狀態 中。預設的 key 是 "langchain_messages"

  • 請注意,StreamlitChatMessageHistory 僅在 Streamlit 應用程式中執行時有效。
  • 您可能也會對 LangChain 的 StreamlitCallbackHandler 感興趣。
  • 如需更多關於 Streamlit 的資訊,請查看他們的入門文件

整合功能位於 langchain-community 套件中,因此我們需要安裝該套件。我們也需要安裝 streamlit

pip install -U langchain-community streamlit

您可以在此處查看完整應用程式範例,並在github.com/langchain-ai/streamlit-agent 中查看更多範例。

from langchain_community.chat_message_histories import (
StreamlitChatMessageHistory,
)

history = StreamlitChatMessageHistory(key="chat_messages")

history.add_user_message("hi!")
history.add_ai_message("whats up?")
API 參考文件:StreamlitChatMessageHistory
history.messages

我們可以輕鬆地將此訊息歷史記錄類別與 LCEL Runnable 結合使用。

歷史記錄將在給定使用者工作階段中跨 Streamlit 應用程式的重新執行持續存在。給定的 StreamlitChatMessageHistory 將不會跨使用者工作階段持續存在或共用。

# Optionally, specify your own session_state key for storing messages
msgs = StreamlitChatMessageHistory(key="special_app_key")

if len(msgs.messages) == 0:
msgs.add_ai_message("How can I help you?")
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
from langchain_core.runnables.history import RunnableWithMessageHistory
from langchain_openai import ChatOpenAI

prompt = ChatPromptTemplate.from_messages(
[
("system", "You are an AI chatbot having a conversation with a human."),
MessagesPlaceholder(variable_name="history"),
("human", "{question}"),
]
)

chain = prompt | ChatOpenAI()
chain_with_history = RunnableWithMessageHistory(
chain,
lambda session_id: msgs, # Always return the instance created earlier
input_messages_key="question",
history_messages_key="history",
)

對話式 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)

# As usual, new messages are added to StreamlitChatMessageHistory when the Chain is called.
config = {"configurable": {"session_id": "any"}}
response = chain_with_history.invoke({"question": prompt}, config)
st.chat_message("ai").write(response.content)

檢視最終應用程式.


此頁面是否對您有幫助?