引言
在构建智能AI助手时,让AI能够回忆起过去的对话是至关重要的。这不仅可以减少幻觉和延迟,还能降低成本。Zep 提供了一个长效记忆服务,能帮助开发者实现这一目标。本文将介绍如何通过Zep来持久化聊天记录,并与Langchain集成。
主要内容
Zep简介
Zep是一项长效记忆服务,专为AI助手应用而设计。它能够存储和检索历史聊天记录,以便AI在后续对话中参考,从而提升用户体验。
为什么使用Zep?
- 减少幻觉:不准确的信息引发的幻觉可以通过历史记忆的质询来减少。
- 降低延迟:通过提前存储和检索聊天记录,减少实时处理的负担。
- 降低成本:使用API调用次数减少,节省费用。
如何集成Zep
通过Zep的API,您可以将聊天记录存储到Zep的云服务中,并在需要时检索这些记录。以下是基本的集成步骤:
- 设置Zep API Key。
- 使用
ZepCloudChatMessageHistory来管理聊天历史。 - 使用
ZepCloudMemory来与Langchain集成。
代码示例
以下是一个完整的代码示例,演示如何使用Zep来持久化聊天记忆:
from uuid import uuid4
from langchain_community.chat_message_histories import ZepCloudChatMessageHistory
from langchain_community.memory.zep_cloud_memory import ZepCloudMemory
from langchain_core.messages import AIMessage, HumanMessage
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
from langchain_core.runnables import RunnableParallel, RunnableWithMessageHistory
from langchain_openai import ChatOpenAI
import getpass
import time
# 获取API密钥
openai_key = getpass.getpass('Provide your OpenAI key:')
zep_api_key = getpass.getpass('Provide your Zep API key. See https://help.getzep.com/projects#api-keys')
session_id = str(uuid4())
# 预加载一些历史消息
test_history = [
{"role": "human", "content": "Who was Octavia Butler?"},
{"role": "ai", "content": "Octavia Estelle Butler was an American science fiction author."},
]
zep_memory = ZepCloudMemory(
session_id=session_id,
api_key=zep_api_key,
)
for msg in test_history:
zep_memory.chat_memory.add_message(
HumanMessage(content=msg["content"]) if msg["role"] == "human" else AIMessage(content=msg["content"])
)
time.sleep(10) # 等待消息嵌入和汇总,这是异步完成的
template = "Be helpful and answer the question below using the provided context:"
answer_prompt = ChatPromptTemplate.from_messages(
[
("system", template),
MessagesPlaceholder(variable_name="chat_history"),
("user", "{question}"),
]
)
inputs = RunnableParallel(
{
"question": lambda x: x["question"],
"chat_history": lambda x: x["chat_history"],
}
)
chain = RunnableWithMessageHistory(
inputs | answer_prompt | ChatOpenAI(openai_api_key=openai_key) | StrOutputParser(),
lambda s_id: ZepCloudChatMessageHistory(
session_id=s_id,
api_key=zep_api_key,
memory_type="perpetual",
),
input_messages_key="question",
history_messages_key="chat_history",
)
response = chain.invoke(
{
"question": "What is the book's relevance to contemporary challenges?"
},
config={"configurable": {"session_id": session_id}},
)
print(response)
# 使用API代理服务提高访问稳定性
常见问题和解决方案
- 网络访问问题:在某些地区可能需要使用API代理服务以提高访问的稳定性。
- API密钥管理:确保妥善管理和存储API密钥,避免泄露。
总结和进一步学习资源
Zep的集成可以大大增强AI助手的长效记忆功能,让用户体验更流畅。了解更多信息和示例,您可以访问以下资源:
参考资料
如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力!
---END---