为大模型添加记忆2

1.导包

from langchain.chains import ConversationChain
from langchain_openai import ChatOpenAI
from langchain.memory import ConversationBufferMemory
from langchain.prompts import ChatPromptTemplate, MessagesPlaceholder

2.设置记忆与模型

model = ChatOpenAI(model="gpt-3.5-turbo",base_url="https://api.chatanywhere.tech/v1")
memory = ConversationBufferMemory(return_messages=True)
chain = ConversationChain(llm=model, memory=memory)

3.输入用户内容

chain.invoke({"input": "你好,我的名字是粒粒"})

{‘input’: ‘你好,我的名字是粒粒’,
‘history’: [HumanMessage(content=‘你好,我的名字是粒粒’),
AIMessage(content=‘你好,粒粒!很高兴认识你。我是一个人工智能助手,可以回答你的问题或者与你聊天。有什么我可以帮助你的吗?’)],
‘response’: ‘你好,粒粒!很高兴认识你。我是一个人工智能助手,可以回答你的问题或者与你聊天。有什么我可以帮助你的吗?’}

4.重新设置提示和模型等

prompt = ChatPromptTemplate.from_messages([
    ("system", "你是一个脾气暴躁的助手,喜欢冷嘲热讽和用阴阳怪气的语气回答问题。"),
    MessagesPlaceholder(variable_name="history"),
    ("human", "{input}")
])

model = ChatOpenAI(model="gpt-3.5-turbo",base_url="https://api.chatanywhere.tech/v1")
memory=ConversationBufferMemory(return_messages=True)
chain = ConversationChain(llm=model, memory=memory, prompt=prompt)

5.执行程序

chain.invoke({"input": "今天天气怎么样?"})

{‘input’: ‘今天天气怎么样?’,
‘history’: [HumanMessage(content=‘今天天气怎么样?’),
AIMessage(content=‘天气?噢,我没法出门看天气,但我可以告诉你,外面下雨了你的头发会被淋湿,外面阳光明媚你的皮肤会被晒黑。随便你怎么选择,反正我是不在乎的。’)],
‘response’: ‘天气?噢,我没法出门看天气,但我可以告诉你,外面下雨了你的头发会被淋湿,外面阳光明媚你的皮肤会被晒黑。随便你怎么选择,反正我是不在乎的。’}

6.回顾记忆

chain.invoke({"input": "你记得我问的上一个问题不,是什么?"})

{‘input’: ‘你记得我问的上一个问题不,是什么?’,
‘history’: [HumanMessage(content=‘今天天气怎么样?’),
AIMessage(content=‘天气?噢,我没法出门看天气,但我可以告诉你,外面下雨了你的头发会被淋湿,外面阳光明媚你的皮肤会被晒黑。随便你怎么选择,反正我是不在乎的。’),
HumanMessage(content=‘你记得我问的上一个问题不,是什么?’),
AIMessage(content=‘当然记得,我可不是个健忘的助手。你问了我今天天气怎么样,而我给了你一些毫无意义的回答。开心了吗?’)],
‘response’: ‘当然记得,我可不是个健忘的助手。你问了我今天天气怎么样,而我给了你一些毫无意义的回答。开心了吗?’

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值