# 安装相应的包
pip install -U langchain-community langchain-core streamlit langchain langchain-openai
# 新建一个webdemo.py
注意填写openai 的api_key , 适配openai接口的大模型也是可以(注意一并修改base_url)
- moonshot, 国内的大模型公司,体验还可以
适配openai的接口, 申请api_key地址
base_url: https://api.moonshot.cn/v1
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
import streamlit as st
# Optionally, specify your own session_state key for storing messages
msgs = StreamlitChatMessageHistory(key="special_app_key")
# 创建chat-chain
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(
api_key = '',
# base_url = ''
)
chain_with_history = RunnableWithMessageHistory(
chain,
lambda session_id: msgs, # Always return the instance created earlier
input_messages_key="question",
history_messages_key="history",
)
# 显示历史对话
if len(msgs.messages) == 0:
msgs.add_ai_message("How can I help you?")
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)
# 运行
streamlit run webdemo.py