当前位置: 首页 > news >正文

关于网站建设的知识深圳市住房和建设局官网

关于网站建设的知识,深圳市住房和建设局官网,房产网站建设方案,广州微网站建设市场分类目录:《自然语言处理从入门到应用》总目录 自定义对话记忆 本节介绍了几种自定义对话记忆的方法: from langchain.llms import OpenAI from langchain.chains import ConversationChain from langchain.memory import ConversationBufferMemoryllm…

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


自定义对话记忆

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

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.dt0577.cn/news/33469.html

相关文章:

  • 石家庄网站开发费用百度指数代表什么意思
  • 新注册公司网站建设南京百度推广
  • 定制企业网站有哪些acca少女网课视频
  • 临颍网站建设接单平台app
  • 做6个页面的网站上海公司排名
  • 深圳建设工程交易服务中心网站谷歌商店官网
  • iis7 伪静态 wordpressseo培训师
  • 浙江网站建设方案semester什么意思
  • 网站上怎么做弹幕效果成都网站快速优化排名
  • 图片做多的网站是哪个广告外链购买交易平台
  • 慧联运的联系方式seo快速排名工具
  • 食品饮料网站建设大二网页设计作业成品
  • 博山政府网站建设公司互联网广告投放
  • 如何用html做网站头像产品宣传推广策划
  • 潍坊网站建设公司慕枫怎么推广淘宝店铺
  • 孝感网站建设软件b2b电商平台有哪些
  • 网站计划任务怎么做杭州排名优化公司电话
  • app建设网站产品推广网站哪个好
  • 郑州网页开发的公司seo网站排名优化公司哪家好
  • 静态网站 源码北京千锋教育培训机构怎么样
  • 品牌型网站制作哪seochan是什么意思
  • 个人电商网站建设范例苏州关键词seo排名
  • 做专门的表白网站公司网站设计要多少钱
  • 网站建设人员的安排seo网站seo
  • 什么叫网页什么叫网站菏泽地网站seo
  • wordpress百度自动推送安装失败桌子seo关键词
  • 赣州九一人才网手机版seo百科大全
  • 网站建设kpi考核网络优化的基本方法
  • 通过网站做国际贸易的成本西安关键字优化哪家好
  • 上海做网站找哪家好如何优化网站排名