使用LangChain实现聊天机器人,掌握聊天机 器人的实现方式--6

1的时候-使用Python实现问答机器人,掌握OpenAl(zhipuai)接口使用

 

前面章节一步一实现,还需要自定义 两天历史数组等。

https://www.cnblogs.com/edeny/p/18628319

 

MessagesPlaceholder

是跟promt 先关的一个组件

在 prompt 中使用的消息列表占位符。这时候就会使用 MessagesPlaceholder。这些对象通过一个名为 variable_name 的参数来指定。与这个 variable name 值相同的输入应该是一个消息列表。

from langchain_core.prompts import MessagesPlaceholder
from langchain.schema import HumanMessage, AIMessage

message_placeholer = MessagesPlaceholder(variable_name="chat_history")

res = message_placeholer.format_messages(chat_history=[
    HumanMessage(content="你好"),
    AIMessage(content="您啊"),

    ]
)
print(res)

可以看返回是一个消息列表

MessagesPlaceholder 对比 ChatPromptTemplate

from langchain_core.prompts import MessagesPlaceholder, ChatPromptTemplate
from langchain.schema import HumanMessage, AIMessage


message_placeholer = MessagesPlaceholder(variable_name="chat_history")
res = message_placeholer.format_messages(chat_history=[
    HumanMessage(content="你好"),
    AIMessage(content="您啊"),

    ]
)
print(res)


# chat_prompt_template
chat_prompt_template = ChatPromptTemplate.from_messages([

    HumanMessage(content="你好"),
    AIMessage(content="您好"),
    ]
)

res1 = chat_prompt_template.format_messages()

print(res1)

同样也返回一个列表

那么问题来了,都是列表为啥还用ChatPromptTemplate。对比前面的ConversationBufferMemory 也是可以自定义 key。这样它两个key的值可以任意填充,互相取值。

 

使用LangChain结合Memory构建聊天机器人

 对比之前代码要简洁不少,功能还实现了,还标准化了。这就是框架的作用。呼应开头与结尾。这就是持续学习,豁然开朗的魅力

from langchain_community.chat_models.tongyi import ChatTongyi
from langchain.prompts import ChatPromptTemplate, MessagesPlaceholder
from langchain.schema import SystemMessage, AIMessage, HumanMessage
from langchain.memory import ConversationBufferMemory
# 将所有串联起来 ChatTongyi,ChatPromptTemplate
from langchain.chains import ConversationChain

# 获取apikey
from dotenv import find_dotenv, load_dotenv
import os

load_dotenv(find_dotenv())
DASHSCOPE_API_KEY = os.environ["DASHSCOPE_API_KEY"]

# 1model,定义模型
model = ChatTongyi(model_name='qwen-max', model_kwargs={'temperature': 0.01},)  # 开启  streaming=True 流失输出就有问题,后需要在验证是否是版本问题

# 定义memory的共用key. 保证 ConversationBufferMemory和MessagesPlaceholder的key值是一样的
memory_key = 'history'

# 2.prompt,定义提示词模版
chat_prompt_template = ChatPromptTemplate.from_messages(
    [
        ('system', '你是一个聊天机器人'),
        MessagesPlaceholder(variable_name=memory_key),   #占位聊天内容
        ('human', '{input}'),

    ]
)


# 3定义memory存储用户和大模型的聊天历史。 这里就体现共用key的作用。 可以根据key取值 MessagesPlaceholder
memory = ConversationBufferMemory(memory_key=memory_key, return_messages=True)

# 4定义chain。 这里不再是表达式。而是可以串联起来的converstationChain

chain = ConversationChain(
    llm=model,
    prompt=chat_prompt_template,
    memory=memory,
)

while True:
    user_input = input("user: ")
    if user_input == 'quit':
        break
    print("AI:", end="")
    # 解析流式输出
    for chunk in chain.stream({"input": user_input}):
        print(chunk["response"], end=""),
    print()

 

end...

posted @   王竹笙  阅读(20)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
点击右上角即可分享
微信分享提示