## 技术背景介绍
在人工智能助手应用中,长时间记忆是一个关键特性。Zep 是一个专为 AI 助手设计的长时记忆服务,能够帮助 AI 记住和理解过去的对话,减少幻觉、降低延迟并节约成本。本篇文章将介绍如何使用 Zep 开源项目检索聊天历史,帮助您在开发中更好地应用长时记忆特性。
## 核心原理解析
Zep 通过使用向量搜索和相似性搜索的技术,对保存的对话数据进行高效检索。通过使用会话/用户特定的 session_id,确保检索结果的内容是针对特定用户或会话的。Zep 的检索功能不仅支持普通检索,还支持使用最大边际相关性(MMR)进行结果重排序,从而提升结果的多样性和相关性。
## 代码实现演示
我们将展示如何在 Zep 中添加对话历史、进行向量搜索检索以及使用 MMR 技术对结果进行重排序。假设您已经设置了 Zep 服务器并获得了访问权限。
```python
import getpass
import time
from uuid import uuid4
from langchain.memory import ZepMemory
from langchain_core.messages import AIMessage, HumanMessage
# Set your Zep server URL
ZEP_API_URL = "http://localhost:8000"
# Optional authentication
AUTHENTICATE = False
zep_api_key = None
if AUTHENTICATE:
zep_api_key = getpass.getpass()
session_id = str(uuid4()) # Unique identifier for the session/user
# Initialize Zep Memory Class
zep_memory = ZepMemory(session_id=session_id, url=ZEP_API_URL, api_key=zep_api_key)
# Add messages to Zep memory store
test_history = [
{"role": "human", "content": "Who was Octavia Butler?"},
{"role": "ai", "content": "Octavia Estelle Butler was an American science fiction author."},
# More history...
]
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) # Waiting for message embedding and summarization
from langchain_community.retrievers.zep import SearchScope, SearchType, ZepRetriever
# Initialize Zep Retriever
zep_retriever = ZepRetriever(
session_id=session_id, # Ensure session_id is set
url=ZEP_API_URL,
top_k=5,
api_key=zep_api_key,
)
# Perform a query with maximal marginal relevance (MMR)
zep_retriever = ZepRetriever(
session_id=session_id,
url=ZEP_API_URL,
api_key=zep_api_key,
search_type=SearchType.mmr,
mmr_lambda=0.5,
)
await zep_retriever.ainvoke("Who wrote Parable of the Sower?")
应用场景分析
通过 Zep 检索可以提高 AI 助手的交互质量,尤其适用于需要长期记住用户上下文的情境,比如客服机器人、教育应用等。借助 Zep 的过滤和重排序功能,还能根据特定搜索条件精确锁定目标信息。
实践建议
在使用 Zep 进行开发时,可以考虑以下几点建议:
- 确保您的 Zep 实例稳定运行,以保证会话数据的持久性。
- 在调用 Zep API 时,确保正确使用 session_id,以保证检索的准确性。
- 如果需要高度相关的搜索结果,可使用 MMR 技术进行结果重排序。
如果遇到问题欢迎在评论区交流。
---END---