对话知识图谱记忆
这种类型的记忆使用知识图谱来重建记忆。
首先让我们了解如何使用这些工具
from langchain.memory import ConversationKGMemory
from langchain.llms import OpenAI
API 参考:
- ConversationKGMemory 来自
langchain.memory
- OpenAI 来自
langchain.llms
llm = OpenAI(temperature=0)
memory = ConversationKGMemory(llm=llm)
memory.save_context({"input": "say hi to sam"}, {"output": "who is sam"})
memory.save_context({"input": "sam is a friend"}, {"output": "okay"})
memory.load_memory_variables({"input": "who is sam"})
{'history': 'On Sam: Sam is friend.'}
我们还可以将历史记录作为消息列表获取(如果您正在与聊天模型一起使用,这将非常有用)。
memory = ConversationKGMemory(llm=llm, return_messages=True)
memory.save_context({"input": "say hi to sam"}, {"output": "who is sam"})
memory.save_context({"input": "sam is a friend"}, {"output": "okay"})
memory.load_memory_variables({"input": "who is sam"})
{'history': [SystemMessage(content='On Sam: Sam is friend.', additional_kwargs={})]}
我们还可以更模块化地从新消息中获取当前实体(将使用先前的消息作为上下文)。
memory.get_current_entities("what's Sams favorite color?")
['Sam']
我们还可以更模块化地从新消息中获取知识三元组(将使用先前的消息作为上下文)。
memory.get_knowledge_triplets("her favorite color is red")
[KnowledgeTriple(subject='Sam', predicate='favorite color', object_='red')]
在链中使用
现在让我们在链中使用它!
llm = OpenAI(temperature=0)
from langchain.prompts.prompt import PromptTemplate
from langchain.chains import ConversationChain
template = """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. The AI ONLY uses information contained in the "Relevant Information" section and does not hallucinate.
Relevant Information:
{history}
Conversation:
Human: {input}
AI:"""
prompt = PromptTemplate(input_variables=["history", "input"], template=template)
conversation_with_kg = ConversationChain(
llm=llm, verbose=True, prompt=prompt, memory=ConversationKGMemory(llm=llm)
)
API 参考:
- PromptTemplate 来自
langchain.prompts.prompt
- ConversationChain 来自
langchain.chains
conversation_with_kg.predict(input="Hi, what's up?")
> 进入新的 ConversationChain 链...
格式化后的提示:
下面是一个友好的人机对话。AI 喜欢说话,并从上下文中提供大量具体细节。
如果 AI 不知道问题的答案,它会真实地说自己不知道。AI 仅使用“相关信息”部分中包含的信息,不会产生幻觉。
相关信息:
对话:
人类:嗨,最近怎么样?
AI:
> 链结束。
"嗨!我很好。我正在学习周围的世界。我正在了解不同的文化、语言和习俗。非常有趣!你呢?"
conversation_with_kg.predict(
input="My name is James and I'm helping Will. He's an engineer."
)
> 进入新的 ConversationChain 链...
格式化后的提示:
下面是一个友好的人机对话。AI 喜欢说话,并从上下文中提供大量具体细节。
如果 AI 不知道问题的答案,它会真实地说自己不知道。AI 仅使用“相关信息”部分中包含的信息,不会产生幻觉。
相关信息:
对话:
人类:我的名字是詹姆斯,我在帮助威尔。他是一名工程师。
AI:
> 链结束。
"嗨詹姆斯,很高兴认识你。我是一个 AI,我知道你在帮助工程师威尔。他从事什么类型的工程?"
conversation_with_kg.predict(input="What do you know about Will?")
> 进入新的 ConversationChain 链...
格式化后的提示:
下面是一个友好的人机对话。AI 喜欢说话,并从上下文中提供大量具体细节。
如果 AI 不知道问题的答案,它会真实地说自己不知道。AI 仅使用“相关信息”部分中包含的信息,不会产生幻觉。
相关信息:
关于威尔:威尔是一名工程师。
对话:
人类:你知道威尔的什么情况?
AI:
> 链结束。
'威尔是一名工程师。'