跳到主要內容
Open In ColabOpen on GitHub

ZepCloudChatMessageHistory

從聊天記錄中回想、理解和提取資料。 強化個人化 AI 體驗。

Zep 是一種適用於 AI 助理應用程式的長期記憶體服務。 透過 Zep,您可以讓 AI 助理具備回想過去對話的能力(無論多麼久遠),同時減少幻覺、延遲和成本。

請參閱Zep Cloud 安裝指南 和更多 Zep Cloud Langchain 範例

範例

此筆記本示範如何使用 Zep 持續保存聊天記錄,並將 Zep Memory 與您的鏈結搭配使用。

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.output_parsers import StrOutputParser
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
from langchain_core.runnables import (
RunnableParallel,
)
from langchain_core.runnables.history import RunnableWithMessageHistory
from langchain_openai import ChatOpenAI

session_id = str(uuid4()) # This is a unique identifier for the session

提供您的 OpenAI 金鑰

import getpass

openai_key = getpass.getpass()

提供您的 Zep API 金鑰。請參閱 https://help.getzep.com/projects#api-keys

zep_api_key = getpass.getpass()

將一些訊息預先載入到記憶體中。預設訊息視窗為 4 則訊息。 我們希望超越這個限制,以示範自動摘要。

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."
),
},
{"role": "human", "content": "Which books of hers were made into movies?"},
{
"role": "ai",
"content": (
"The most well-known adaptation of Octavia Butler's work is the FX series"
" Kindred, based on her novel of the same name."
),
},
{"role": "human", "content": "Who were her contemporaries?"},
{
"role": "ai",
"content": (
"Octavia Butler's contemporaries included Ursula K. Le Guin, Samuel R."
" Delany, and Joanna Russ."
),
},
{"role": "human", "content": "What awards did she win?"},
{
"role": "ai",
"content": (
"Octavia Butler won the Hugo Award, the Nebula Award, and the MacArthur"
" Fellowship."
),
},
{
"role": "human",
"content": "Which other women sci-fi writers might I want to read?",
},
{
"role": "ai",
"content": "You might want to read Ursula K. Le Guin or Joanna Russ.",
},
{
"role": "human",
"content": (
"Write a short synopsis of Butler's book, Parable of the Sower. What is it"
" about?"
),
},
{
"role": "ai",
"content": (
"Parable of the Sower is a science fiction novel by Octavia Butler,"
" published in 1993. It follows the story of Lauren Olamina, a young woman"
" living in a dystopian future where society has collapsed due to"
" environmental disasters, poverty, and violence."
),
"metadata": {"foo": "bar"},
},
]

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"])
)

import time

time.sleep(
10
) # Wait for the messages to be embedded and summarized, this happens asynchronously.

MessagesPlaceholder - 我們在這裡使用變數名稱 chat_history。 這會將聊天記錄納入提示中。 重要的是,此變數名稱需與 RunnableWithMessageHistory 鏈中的 history_messages_key 對齊,以實現無縫整合。

question 必須與 `RunnableWithMessageHistory“ 鏈中的 input_messages_key 相符。

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}"),
]
)

我們使用 RunnableWithMessageHistory 將 Zep 的聊天記錄納入我們的鏈結中。 當您啟用鏈結時,此類別需要 session_id 作為參數。

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, # This uniquely identifies the conversation, note that we are getting session id as chain configurable field
api_key=zep_api_key,
memory_type="perpetual",
),
input_messages_key="question",
history_messages_key="chat_history",
)
chain.invoke(
{
"question": "What is the book's relevance to the challenges facing contemporary society?"
},
config={"configurable": {"session_id": session_id}},
)
Parent run 622c6f75-3e4a-413d-ba20-558c1fea0d50 not found for run af12a4b1-e882-432d-834f-e9147465faf6. Treating as a root run.
'"Parable of the Sower" is relevant to the challenges facing contemporary society as it explores themes of environmental degradation, economic inequality, social unrest, and the search for hope and community in the face of chaos. The novel\'s depiction of a dystopian future where society has collapsed due to environmental and economic crises serves as a cautionary tale about the potential consequences of our current societal and environmental challenges. By addressing issues such as climate change, social injustice, and the impact of technology on humanity, Octavia Butler\'s work prompts readers to reflect on the pressing issues of our time and the importance of resilience, empathy, and collective action in building a better future.'

此頁面是否實用?