自然语言处理从入门到应用——LangChain:记忆(Memory)-[自定义对话记忆与自定义记忆类]

分类目录:《自然语言处理从入门到应用》总目录


自定义对话记忆

本节介绍了几种自定义对话记忆的方法:

from langchain.llms import OpenAI
from langchain.chains import ConversationChain
from langchain.memory import ConversationBufferMemoryllm = OpenAI(temperature=0)
AI前缀

第一种方法是通过更改对话摘要中的AI前缀来实现。默认情况下,它设置为AI,但你可以将其设置为任何你想要的内容。需要注意的是,如果我们更改了这个前缀,我们还应该相应地更改链条中使用的提示来反映这个命名更改。让我们通过下面的示例来演示这个过程。

# Here it is by default set to "AI"
conversation = ConversationChain(llm=llm, verbose=True, memory=ConversationBufferMemory()
)
conversation.predict(input="Hi there!")

日志输出:

> Entering new ConversationChain chain...
Prompt after formatting:
The following is a friendly conversation between a human and an AI. The AI is talkative and provides lots of specific details from its context. If the AI does not know the answer to a question, it truthfully says it does not know.Current conversation:Human: Hi there!
AI:> Finished ConversationChain chain.

输出:

" Hi there! It's nice to meet you. How can I help you today?"

输入:

conversation.predict(input="What's the weather?")

日志输出:

> Entering new ConversationChain chain...
Prompt after formatting:
The following is a friendly conversation between a human and an AI. The AI is talkative and provides lots of specific details from its context. If the AI does not know the answer to a question, it truthfully says it does not know.Current conversation:Human: Hi there!
AI:  Hi there! It's nice to meet you. How can I help you today?
Human: What's the weather?
AI:> Finished ConversationChain chain.

输出:

' The current weather is sunny and warm with a temperature of 75 degrees Fahrenheit. The forecast for the next few days is sunny with temperatures in the mid-70s.'

输入:

# Now we can override it and set it to "AI Assistant"
from langchain.prompts.prompt import PromptTemplatetemplate = """The following is a friendly conversation between a human and an AI. The AI is talkative and provides lots of specific details from its context. If the AI does not know the answer to a question, it truthfully says it does not know.Current conversation:
{history}
Human: {input}
AI Assistant:"""
PROMPT = PromptTemplate(input_variables=["history", "input"], template=template
)
conversation = ConversationChain(prompt=PROMPT,llm=llm, verbose=True, memory=ConversationBufferMemory(ai_prefix="AI Assistant")
)
conversation.predict(input="Hi there!")

日志输出:

> Entering new ConversationChain chain...
Prompt after formatting:
The following is a friendly conversation between a human and an AI. The AI is talkative and provides lots of specific details from its context. If the AI does not know the answer to a question, it truthfully says it does not know.Current conversation:Human: Hi there!
AI Assistant:> Finished ConversationChain chain.
" Hi there! It's nice to meet you. How can I help you today?"
conversation.predict(input="What's the weather?")
> Entering new ConversationChain chain...
Prompt after formatting:
The following is a friendly conversation between a human and an AI. The AI is talkative and provides lots of specific details from its context. If the AI does not know the answer to a question, it truthfully says it does not know.Current conversation:Human: Hi there!
AI Assistant:  Hi there! It's nice to meet you. How can I help you today?
Human: What's the weather?
AI Assistant:> Finished ConversationChain chain.

输出:

The current weather is sunny and warm with a temperature of 75 degrees Fahrenheit. The forecast for the rest of the day is sunny with a high of 78 degrees and a low of 65 degrees.'
人类前缀

第二种方法是通过更改对话摘要中的人类前缀来实现。默认情况下,它设置为Human,但我们可以将其设置为任何我们想要的内容。需要注意的是,如果我们更改了这个前缀,我们还应该相应地更改链条中使用的提示来反映这个命名更改。让我们通过下面的示例来演示这个过程。

# Now we can override it and set it to "Friend"
from langchain.prompts.prompt import PromptTemplatetemplate = """The following is a friendly conversation between a human and an AI. The AI is talkative and provides lots of specific details from its context. If the AI does not know the answer to a question, it truthfully says it does not know.Current conversation:
{history}
Friend: {input}
AI:"""
PROMPT = PromptTemplate(input_variables=["history", "input"], template=template
)
conversation = ConversationChain(prompt=PROMPT,llm=llm, verbose=True, memory=ConversationBufferMemory(human_prefix="Friend")
)
conversation.predict(input="Hi there!")

日志输出:

> Entering new ConversationChain chain...
Prompt after formatting:
The following is a friendly conversation between a human and an AI. The AI is talkative and provides lots of specific details from its context. If the AI does not know the answer to a question, it truthfully says it does not know.Current conversation:Friend: Hi there!
AI:> Finished ConversationChain chain.
" Hi there! It's nice to meet you. How can I help you today?"
conversation.predict(input="What's the weather?")
> Entering new ConversationChain chain...
Prompt after formatting:
The following is a friendly conversation between a human and an AI. The AI is talkative and provides lots of specific details from its context. If the AI does not know the answer to a question, it truthfully says it does not know.Current conversation:Friend: Hi there!
AI:  Hi there! It's nice to meet you. How can I help you today?
Friend: What's the weather?
AI:> Finished ConversationChain chain.

输出:

  ' The weather right now is sunny and warm with a temperature of 75 degrees Fahrenheit. The forecast for the rest of the day is mostly sunny with a high of 82 degrees.'

创建自定义记忆类

尽管在LangChain中有几种预定义的记忆类型,但我们很可能希望添加自己的记忆类型,以使其适用于我们的应用程序。在本节中,我们将向ConversationChain添加一个自定义的记忆类型。为了添加自定义的记忆类,我们需要导入基本的记忆类并对其进行子类化。

from langchain import OpenAI, ConversationChain
from langchain.schema import BaseMemory
from pydantic import BaseModel
from typing import List, Dict, Any

在这个示例中,我们将编写一个自定义的记忆类,使用spacy提取实体并将有关它们的信息保存在一个简单的哈希表中。然后,在对话过程中,我们将查看输入文本,提取任何实体,并将关于它们的任何信息放入上下文中。需要注意的是,这种实现相当简单且脆弱,可能在生产环境中不太有用。它的目的是展示我们可以添加自定义的记忆实现。为此,我们需要首先安装spacy

# !pip install spacy
# !python -m spacy download en_core_web_lg
import spacy
nlp = spacy.load('en_core_web_lg')
class SpacyEntityMemory(BaseMemory, BaseModel):"""Memory class for storing information about entities."""# Define dictionary to store information about entities.entities: dict = {}# Define key to pass information about entities into prompt.memory_key: str = "entities"def clear(self):self.entities = {}@propertydef memory_variables(self) -> List[str]:"""Define the variables we are providing to the prompt."""return [self.memory_key]def load_memory_variables(self, inputs: Dict[str, Any]) -> Dict[str, str]:"""Load the memory variables, in this case the entity key."""# Get the input text and run through spacydoc = nlp(inputs[list(inputs.keys())[0]])# Extract known information about entities, if they exist.entities = [self.entities[str(ent)] for ent in doc.ents if str(ent) in self.entities]# Return combined information about entities to put into context.return {self.memory_key: "\n".join(entities)}def save_context(self, inputs: Dict[str, Any], outputs: Dict[str, str]) -> None:"""Save context from this conversation to buffer."""# Get the input text and run through spacytext = inputs[list(inputs.keys())[0]]doc = nlp(text)# For each entity that was mentioned, save this information to the dictionary.for ent in doc.ents:ent_str = str(ent)if ent_str in self.entities:self.entities[ent_str] += f"\n{text}"else:self.entities[ent_str] = text

我们现在定义一个提示,其中包含有关实体的信息以及用户的输入:

from langchain.prompts.prompt import PromptTemplatetemplate = """The following is a friendly conversation between a human and an AI. The AI is talkative and provides lots of specific details from its context. If the AI does not know the answer to a question, it truthfully says it does not know. You are provided with information about entities the Human mentions, if relevant.Relevant entity information:
{entities}Conversation:
Human: {input}
AI:"""
prompt = PromptTemplate(input_variables=["entities", "input"], template=template
)

现在,我们把它们整合起来:

llm = OpenAI(temperature=0)
conversation = ConversationChain(llm=llm, prompt=prompt, verbose=True, memory=SpacyEntityMemory())

在第一个例子中,由于对Harrison没有先前的了解,"Relevant entity information"部分是空的:

conversation.predict(input="Harrison likes machine learning")

日志输出:

> Entering new ConversationChain chain...
Prompt after formatting:
The following is a friendly conversation between a human and an AI. The AI is talkative and provides lots of specific details from its context. If the AI does not know the answer to a question, it truthfully says it does not know. You are provided with information about entities the Human mentions, if relevant.Relevant entity information:Conversation:
Human: Harrison likes machine learning
AI:> Finished ConversationChain chain.

输出:

" That's great to hear! Machine learning is a fascinating field of study. It involves using algorithms to analyze data and make predictions. Have you ever studied machine learning, Harrison?"

现在在第二个例子中,我们可以看到它提取了关于Harrison的信息。

conversation.predict(input="What do you think Harrison's favorite subject in college was?")

日志输出:

> Entering new ConversationChain chain...
Prompt after formatting:
The following is a friendly conversation between a human and an AI. The AI is talkative and provides lots of specific details from its context. If the AI does not know the answer to a question, it truthfully says it does not know. You are provided with information about entities the Human mentions, if relevant.Relevant entity information:
Harrison likes machine learningConversation:
Human: What do you think Harrison's favorite subject in college was?
AI:> Finished ConversationChain chain.

输出:

' From what I know about Harrison, I believe his favorite subject in college was machine learning. He has expressed a strong interest in the subject and has mentioned it often.'

这个实现方式相对简单且容易出错,可能在实际生产环境中没有太大的用途,但它展示了我们可以添加自定义的内存实现方式。

参考文献:
[1] LangChain官方网站:https://www.langchain.com/
[2] LangChain 🦜️🔗 中文网,跟着LangChain一起学LLM/GPT开发:https://www.langchain.com.cn/
[3] LangChain中文网 - LangChain 是一个用于开发由语言模型驱动的应用程序的框架:http://www.cnlangchain.com/

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/42243.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

QT 使用第三方库QtXlsx操作Excel表

1.简介 一直以来,都想学习一下C/C如何操作excel表,在网上调研了一下,觉得使用C/C去操作很麻烦,遂转向QT这边;QT有一个自带的类QAxObject,可以使用他去操作,但随着了解的深入,觉得他…

c++游戏制作指南(四):c++实现数据的存储和读取(输入流fstream)

🍿*★,*:.☆( ̄▽ ̄)/$:*.★* 🍿 🍟欢迎来到静渊隐者的csdn博文,本文是c游戏制作指南的一部🍟 🍕更多文章请点击下方链接🍕 🍨 c游戏制作指南&#x1f3…

最长重复子数组(力扣)动态规划 JAVA

给两个整数数组 nums1 和 nums2 ,返回 两个数组中 公共的 、长度最长的子数组的长度 。 示例 1: 输入:nums1 [1,2,3,2,1], nums2 [3,2,1,4,7] 输出:3 解释:长度最长的公共子数组是 [3,2,1] 。 示例 2: 输…

新宝马M5谍照曝光,侵略感十足,将与奥迪、梅赛德斯-AMG正面竞争

报道称,宝马即将推出全新一代M5,该车的谍照最近再次曝光。早先,宝马 M5 Touring 旅行汽车的赛道测试图片已经在网络上流传开来,预计该车将与奥迪的RS6 Avant和梅赛德斯-AMG E63 Estate展开正面竞争。 从最新曝光的照片来看&#x…

【操作系统考点汇集】操作系统考点汇集

关于操作系统可能考察的知识点 操作系统基本原理 什么是操作系统? 操作系统是指控制和管理整个计算机系统的硬件和软件资源,并合理地组织调度计算机的工作和资源的分配,以提供给用户和它软件方便的接口和环境,是计算机系统中最基…

Python土力学与基础工程计算.PDF-钻探泥浆制备

Python 求解代码如下: 1. rho1 2.5 # 黏土密度,单位:t/m 2. rho2 1.0 # 泥浆密度,单位:t/m 3. rho3 1.0 # 水的密度,单位:t/m 4. V 1.0 # 泥浆容积,单位:…

神经网络基础-神经网络补充概念-53-将batch norm拟合进神经网络

代码实现 import numpy as np import tensorflow as tf from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense, BatchNormalization, Activation from tensorflow.keras.optimizers import SGD# 生成随机数据 np.random.seed(0) X np.…

【0基础入门Python笔记】一、python 之基础语法、基础数据类型、复合数据类型及基本操作

一、python 之基础语法、基础数据类型、复合数据类型及基本操作 基础语法规则基础数据类型数字类型(Numbers)字符串类型(String)布尔类型(Boolean) 复合数据类型List(列表)Tuple&…

代码随想录DAY62

这个移动0的问题还是比较重要的 因为涉及到一种思想&#xff1a;快慢指针&#xff01; class Solution { public: void moveZeroes(vector<int>& nums) { int slow0,fast0; for(;fast<nums.size();fast){ if(nums[fast]!0){ swap(nums[slow],nums[fast]); slow;…

Kafka 什么速度那么快

批量发送消息 Kafka 采用了批量发送消息的方式&#xff0c;通过将多条消息按照分区进行分组&#xff0c;然后每次发送一个消息集合&#xff0c;看似很平常的一个手段&#xff0c;其实它大大提升了 Kafka 的吞吐量。 消息压缩 消息压缩的目的是为了进一步减少网络传输带宽。而…

故障012:定时备份作业-6007悬案

故障012&#xff1a;定时备份作业-6007悬案 1. 问题描述2. 解决过程2.1 大胆推想2.2 找规律2.3 尝试换掉AP2.4 检查资源限制2.5 资源放宽SYSDBA 3. 精神感悟 DM技术交流QQ群&#xff1a;940124259 1. 问题描述 诡异的现象总是伴随着隐藏的功能被打开&#xff0c;可能耽误你很…

比ChatGPT更强的星火大模型V2版本发布!

初体验 测试PPT生成 结果&#xff1a; 达到了我的预期&#xff0c;只需要微调就可以直接交付&#xff0c;这点比ChatGPT要强很多. 测试文档问答 结果&#xff1a; 这点很新颖&#xff0c;现在类似这种文档问答的AI平台收费都贵的离谱&#xff0c;星火不但免费支持而且效果也…

opencv图片换背景色

#include <iostream> #include<opencv2/opencv.hpp> //引入头文件using namespace cv; //命名空间 using namespace std;//opencv这个机器视觉库&#xff0c;它提供了很多功能&#xff0c;都是以函数的形式提供给我们 //我们只需要会调用函数即可in…

uniapp评论列表插件获取

从评论列表&#xff0c;回复&#xff0c;点赞&#xff0c;删除&#xff0c;留言板 - DCloud 插件市场里导入&#xff0c;并使用。 代码样式优化及接入如下&#xff1a; <template><view class"hb-comment"><!-- 阅读数-start --><view v-if&q…

5.利用matlab完成 符号矩阵的转置和 符号方阵的幂运算(matlab程序)

1.简述 Matlab符号运算中的矩阵转置 转置向量或矩阵 B A. B transpose(A) 说明 B A. 返回 A 的非共轭转置&#xff0c;即每个元素的行和列索引都会互换。如果 A 包含复数元素&#xff0c;则 A. 不会影响虚部符号。例如&#xff0c;如果 A(3,2) 是 12i 且 B A.&#xff0…

java中excel文件下载

1、System.getProperty(user.dir) 获取的是启动项目的容器位置 2、 Files.copy(sourceFile.toPath(), destinationFile.toPath(), StandardCopyOption.REPLACE_EXISTING); StandardCopyOption.REPLACE_EXISTING 来忽略文件已经存在的异常&#xff0c;如果存在就去覆盖掉它Sta…

00-认识C++

2、认识C 2.1、例子 一个简单的C例子 #include <iostream>int main() {using namespace std; //使用名称空间cout << "Com up and C me some time.";cout << endl; //换行符&#xff0c;还可以cout<<"\n";cout <…

驱动DAY5

1.实现设备文件和设备的绑定&#xff0c;编写LED驱动 2.复习竞态的解决方法和阻塞IO实现 第一个任务 头文件 #ifndef __HEAD_H__ #define __HEAD_H__ typedef struct{unsigned int MODER;unsigned int OTYPER;unsigned int OSPEEDR;unsigned int PUPDR;unsigned int IDR;u…

【MySQL系列】表内容的基本操作(增删查改)

「前言」文章内容大致是对MySQL表内容的基本操作&#xff0c;即增删查改。 「归属专栏」MySQL 「主页链接」个人主页 「笔者」枫叶先生(fy) 目录 一、MySQL表内容的增删查改1.1 Create1.1.1 单行数据全列插入1.1.2 多行数据指定列插入1.1.3 插入否则更新1.1.4 数据替换 1.2 Ret…

MS Word表格宽度自适应

x.1 问题&#xff1a; 你的表格可能并没有占满整行&#xff0c;且右对齐&#xff0c;例如如下&#xff0c; x.2 解决方式 这个时候你想右对齐&#xff0c;你可以这么操作&#xff0c;点左上角的十字全选表格&#xff0c; 在布局里选择自动对齐&#xff0c; 对齐方式选择居中右…