【streamlit & langchain 搭建一个超简单的具有记忆能力的对话应用】

# 安装相应的包

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

# 参考 

Streamlit | 🦜️🔗 Langchainicon-default.png?t=N7T8https://python.langchain.com/docs/integrations/memory/streamlit_chat_message_history

  • 9
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

放飞自我的Coder

你的鼓励很棒棒哦~

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值