自然語言處理從入門到應用——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.pswp.cn/news/42243.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/42243.shtml
英文地址,請注明出處:http://en.pswp.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; 對齊方式選擇居中右…