实现思路
- 使用LangChain的ConversationChain实现对话记忆
- 使用streamlit作为前端交互
实现代码
from langchain.chains import ConversationChain
from langchain.memory import ConversationBufferMemory
from langchain_community.chat_models import ChatTongyi
import streamlit as st
st.set_page_config(page_title="Conversation Streamlit App")
st.title('Conversation Streamlit App')
# 实例化一个memory
memory = ConversationBufferMemory(memory_key="chat_history")
# 创建一个大模型
llm = ChatTongyi()
# 初始化history
if 'chat_history' not in st.session_state:
st.session_state['chat_history'] = ConversationBufferMemory()
# 创建一个专用对话链
conversation = ConversationChain(
llm=llm,
memory=st.session_state['chat_history'],
)
# 加载历史对话消息
for msg in conversation.memory.chat_memory.messages:
st.chat_message(msg.type).write(msg.content)
if user_input := st.chat_input(placeholder="请输入问题"):
st.chat_message("user").write(user_input)
ai_response = conversation.invoke(user_input)
st.chat_message("ai").write(ai_response["response"])