当前位置:   article > 正文

【streamlit & langchain 搭建一个超简单的具有记忆能力的对话应用】_streamlit 几种对话历史应用实现

streamlit 几种对话历史应用实现

# 安装相应的包

pip install -U langchain-community langchain-core streamlit langchain langchain-openai

# 新建一个webdemo.py

注意填写openaiapi_key , 适配openai接口的大模型也是可以(注意一并修改base_url)

- moonshot, 国内的大模型公司,体验还可以

        适配openai的接口, 申请api_key地址

        base_url: https://api.moonshot.cn/v1

  1. from langchain_community.chat_message_histories import StreamlitChatMessageHistory
  2. from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
  3. from langchain_core.runnables.history import RunnableWithMessageHistory
  4. from langchain_openai import ChatOpenAI
  5. import streamlit as st
  6. # Optionally, specify your own session_state key for storing messages
  7. msgs = StreamlitChatMessageHistory(key="special_app_key")
  8. # 创建chat-chain
  9. prompt = ChatPromptTemplate.from_messages(
  10. [
  11. ("system", "You are an AI chatbot having a conversation with a human."),
  12. MessagesPlaceholder(variable_name="history"),
  13. ("human", "{question}"),
  14. ]
  15. )
  16. chain = prompt | ChatOpenAI(
  17. api_key = '',
  18. # base_url = ''
  19. )
  20. chain_with_history = RunnableWithMessageHistory(
  21. chain,
  22. lambda session_id: msgs, # Always return the instance created earlier
  23. input_messages_key="question",
  24. history_messages_key="history",
  25. )
  26. # 显示历史对话
  27. if len(msgs.messages) == 0:
  28. msgs.add_ai_message("How can I help you?")
  29. for msg in msgs.messages:
  30. st.chat_message(msg.type).write(msg.content)
  31. # 最新的对话
  32. if prompt := st.chat_input('输入...'):
  33. st.chat_message("human").write(prompt)
  34. # As usual, new messages are added to StreamlitChatMessageHistory
  35. # when the Chain is called.
  36. config = {"configurable": {"session_id": "any"}}
  37. response = chain_with_history.invoke({"question": prompt}, config)
  38. st.chat_message("ai").write(response.content)

# 运行

streamlit run webdemo.py

# 参考 

https://www.wpsshop.cn/w/我家小花儿/article/detail/767491

推荐阅读
相关标签
  

闽ICP备14008679号