Skip to main content
Open In Colab在 GitHub 上打开

Streamlit (流式)

Streamlit 是一个开源 Python 库,可以轻松创建和共享美观、 用于机器学习和数据科学的自定义 Web 应用程序。

此笔记本介绍了如何在Streamlit应用程序。StreamlitChatMessageHistory将消息存储在指定的 Streamlit 会话状态key=.默认键为"langchain_messages".

集成位于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?")
history.messages

我们可以轻松地将此消息历史类与 LCEL Runnables 结合使用。

在给定用户会话中重新运行 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)

查看最终应用程序