langchain/docs/modules/memory/examples/zep_memory.ipynb
Davis Chase 8966f61ca5
Zep memory (#4898)
Co-authored-by: Daniel Chalef <daniel.chalef@private.org>
Co-authored-by: Daniel Chalef <131175+danielchalef@users.noreply.github.com>
2023-05-17 20:01:01 -07:00

440 lines
17 KiB
Plaintext
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

{
"cells": [
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"# Zep Memory\n",
"\n",
"## REACT Agent Chat Message History Example\n",
"\n",
"This notebook demonstrates how to use the [Zep Long-term Memory Store](https://getzep.github.io/) as memory for your chatbot.\n",
"\n",
"We'll demonstrate:\n",
"\n",
"1. Adding conversation history to the Zep memory store.\n",
"2. Running an agent and having message automatically added to the store.\n",
"3. Viewing the enriched messages.\n",
"4. Vector search over the conversation history.\n",
"\n",
"More on Zep:\n",
"\n",
"Zep stores, summarizes, embeds, indexes, and enriches conversational AI chat histories, and exposes them via simple, low-latency APIs.\n",
"\n",
"Key Features:\n",
"\n",
"- Long-term memory persistence, with access to historical messages irrespective of your summarization strategy.\n",
"- Auto-summarization of memory messages based on a configurable message window. A series of summaries are stored, providing flexibility for future summarization strategies.\n",
"- Vector search over memories, with messages automatically embedded on creation.\n",
"- Auto-token counting of memories and summaries, allowing finer-grained control over prompt assembly.\n",
"- Python and JavaScript SDKs.\n",
"\n",
"Zep project: [https://github.com/getzep/zep](https://github.com/getzep/zep)\n",
"Docs: [https://getzep.github.io](https://getzep.github.io/)\n"
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {
"ExecuteTime": {
"end_time": "2023-05-17T05:12:58.500164Z",
"start_time": "2023-05-17T05:12:57.688886Z"
}
},
"outputs": [],
"source": [
"from langchain.memory.chat_message_histories import ZepChatMessageHistory\n",
"from langchain.memory import ConversationBufferMemory\n",
"from langchain import OpenAI\n",
"from langchain.schema import HumanMessage, AIMessage\n",
"from langchain.tools import DuckDuckGoSearchRun\n",
"from langchain.agents import initialize_agent, AgentType\n",
"from uuid import uuid4\n",
"\n",
"\n",
"# Set this to your Zep server URL\n",
"ZEP_API_URL = \"http://localhost:8000\"\n",
"\n",
"session_id = str(uuid4()) # This is a unique identifier for the user\n"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {
"ExecuteTime": {
"end_time": "2023-05-17T05:12:58.506469Z",
"start_time": "2023-05-17T05:12:58.501324Z"
}
},
"outputs": [],
"source": [
"# Zep is async-first. Our sync APIs use an asyncio wrapper to run outside of an app's event loop.\n",
"# This interferes with Jupyter's event loop, so we need to install nest_asyncio to run the\n",
"# Zep client in a notebook.\n",
"\n",
"# !pip install nest_asyncio\n",
"\n",
"import nest_asyncio\n",
"\n",
"nest_asyncio.apply()"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {
"ExecuteTime": {
"end_time": "2023-05-17T05:12:58.514638Z",
"start_time": "2023-05-17T05:12:58.503811Z"
}
},
"outputs": [
{
"data": {
"text/plain": "True"
},
"execution_count": 3,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Load your OpenAI key from a .env file\n",
"from dotenv import load_dotenv\n",
"\n",
"load_dotenv()"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"### Initialize the Zep Chat Message History Class and initialize the Agent\n"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {
"ExecuteTime": {
"end_time": "2023-05-17T05:12:58.618633Z",
"start_time": "2023-05-17T05:12:58.510414Z"
}
},
"outputs": [],
"source": [
"ddg = DuckDuckGoSearchRun()\n",
"tools = [ddg]\n",
"\n",
"# Set up Zep Chat History\n",
"zep_chat_history = ZepChatMessageHistory(\n",
" session_id=session_id,\n",
" url=ZEP_API_URL,\n",
")\n",
"\n",
"# Use a standard ConversationBufferMemory to encapsulate the Zep chat history\n",
"memory = ConversationBufferMemory(\n",
" memory_key=\"chat_history\", chat_memory=zep_chat_history\n",
")\n",
"\n",
"# Initialize the agent\n",
"llm = OpenAI(temperature=0)\n",
"agent_chain = initialize_agent(\n",
" tools,\n",
" llm,\n",
" agent=AgentType.CONVERSATIONAL_REACT_DESCRIPTION,\n",
" verbose=True,\n",
" memory=memory,\n",
")\n"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"### Add some history data\n"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {
"ExecuteTime": {
"end_time": "2023-05-17T05:12:58.764097Z",
"start_time": "2023-05-17T05:12:58.622528Z"
}
},
"outputs": [],
"source": [
"# Preload some messages into the memory. The default message window is 12 messages. We want to push beyond this to demonstrate auto-summarization.\n",
"test_history = [\n",
" {\"role\": \"human\", \"content\": \"Who was Octavia Butler?\"},\n",
" {\n",
" \"role\": \"ai\",\n",
" \"content\": (\n",
" \"Octavia Estelle Butler (June 22, 1947 February 24, 2006) was an American\"\n",
" \" science fiction author.\"\n",
" ),\n",
" },\n",
" {\"role\": \"human\", \"content\": \"Which books of hers were made into movies?\"},\n",
" {\n",
" \"role\": \"ai\",\n",
" \"content\": (\n",
" \"The most well-known adaptation of Octavia Butler's work is the FX series\"\n",
" \" Kindred, based on her novel of the same name.\"\n",
" ),\n",
" },\n",
" {\"role\": \"human\", \"content\": \"Who were her contemporaries?\"},\n",
" {\n",
" \"role\": \"ai\",\n",
" \"content\": (\n",
" \"Octavia Butler's contemporaries included Ursula K. Le Guin, Samuel R.\"\n",
" \" Delany, and Joanna Russ.\"\n",
" ),\n",
" },\n",
" {\"role\": \"human\", \"content\": \"What awards did she win?\"},\n",
" {\n",
" \"role\": \"ai\",\n",
" \"content\": (\n",
" \"Octavia Butler won the Hugo Award, the Nebula Award, and the MacArthur\"\n",
" \" Fellowship.\"\n",
" ),\n",
" },\n",
" {\n",
" \"role\": \"human\",\n",
" \"content\": \"Which other women sci-fi writers might I want to read?\",\n",
" },\n",
" {\n",
" \"role\": \"ai\",\n",
" \"content\": \"You might want to read Ursula K. Le Guin or Joanna Russ.\",\n",
" },\n",
" {\n",
" \"role\": \"human\",\n",
" \"content\": (\n",
" \"Write a short synopsis of Butler's book, Parable of the Sower. What is it\"\n",
" \" about?\"\n",
" ),\n",
" },\n",
" {\n",
" \"role\": \"ai\",\n",
" \"content\": (\n",
" \"Parable of the Sower is a science fiction novel by Octavia Butler,\"\n",
" \" published in 1993. It follows the story of Lauren Olamina, a young woman\"\n",
" \" living in a dystopian future where society has collapsed due to\"\n",
" \" environmental disasters, poverty, and violence.\"\n",
" ),\n",
" },\n",
"]\n",
"\n",
"for msg in test_history:\n",
" zep_chat_history.append(\n",
" HumanMessage(content=msg[\"content\"])\n",
" if msg[\"role\"] == \"human\"\n",
" else AIMessage(content=msg[\"content\"])\n",
" )\n"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"### Run the agent\n",
"\n",
"Doing so will automatically add the input and response to the Zep memory.\n"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {
"ExecuteTime": {
"end_time": "2023-05-17T05:13:08.226487Z",
"start_time": "2023-05-17T05:12:58.760795Z"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"\n",
"\n",
"\u001B[1m> Entering new AgentExecutor chain...\u001B[0m\n",
"\u001B[32;1m\u001B[1;3mAI: Parable of the Sower is a powerful exploration of the challenges facing contemporary society, such as environmental disasters, poverty, and violence. It examines how these issues can lead to the breakdown of society and how individuals can take action to create a better future. The novel also explores themes of faith, hope, and resilience in the face of adversity.\u001B[0m\n",
"\n",
"\u001B[1m> Finished chain.\u001B[0m\n"
]
},
{
"data": {
"text/plain": "'Parable of the Sower is a powerful exploration of the challenges facing contemporary society, such as environmental disasters, poverty, and violence. It examines how these issues can lead to the breakdown of society and how individuals can take action to create a better future. The novel also explores themes of faith, hope, and resilience in the face of adversity.'"
},
"execution_count": 6,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"agent_chain.run(\n",
" input=\"WWhat is the book's relevance to the challenges facing contemporary society?\"\n",
")\n"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"### Inspect the Zep memory\n",
"\n",
"Note the summary, and that the history has been enriched with token counts, UUIDs, and timestamps.\n",
"\n",
"Summaries are biased towards the most recent messages.\n"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {
"ExecuteTime": {
"end_time": "2023-05-17T05:13:08.240995Z",
"start_time": "2023-05-17T05:13:08.227744Z"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"The AI provides a summary of Octavia Butler's science fiction novel, Parable of the Sower, which follows the story of Lauren Olamina in a dystopian future. When asked for recommendations of other women sci-fi writers, the AI suggests Ursula K. Le Guin and Joanna Russ. The AI also mentions Butler's awards, including the Hugo Award, the Nebula Award, and the MacArthur Fellowship.\n",
"\n",
"\n",
"{'role': 'ai', 'content': 'Parable of the Sower is a powerful exploration of the challenges facing contemporary society, such as environmental disasters, poverty, and violence. It examines how these issues can lead to the breakdown of society and how individuals can take action to create a better future. The novel also explores themes of faith, hope, and resilience in the face of adversity.', 'uuid': '50836d01-9dfe-4dd9-8245-3dd67c4c5c73', 'created_at': '2023-05-17T05:13:08.221879Z', 'token_count': 0}\n",
"{'role': 'human', 'content': \"WWhat is the book's relevance to the challenges facing contemporary society?\", 'uuid': '4249ee05-22df-41b5-a8e3-e2f9386f9ca8', 'created_at': '2023-05-17T05:13:08.211224Z', 'token_count': 0}\n",
"{'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.', 'uuid': 'd4806cc0-c75e-4c36-80e9-2d74b23aece0', 'created_at': '2023-05-17T05:12:58.757654Z', 'token_count': 56}\n",
"{'role': 'human', 'content': \"Write a short synopsis of Butler's book, Parable of the Sower. What is it about?\", 'uuid': '378f8b63-8ef8-4fe7-b0b2-abc3e73ce1b2', 'created_at': '2023-05-17T05:12:58.754882Z', 'token_count': 23}\n",
"{'role': 'ai', 'content': 'You might want to read Ursula K. Le Guin or Joanna Russ.', 'uuid': 'b9e52976-3417-4d12-868c-34a197e8111d', 'created_at': '2023-05-17T05:12:58.75184Z', 'token_count': 18}\n",
"{'role': 'human', 'content': 'Which other women sci-fi writers might I want to read?', 'uuid': '64c606c8-3c4b-424b-855e-df71825c15d7', 'created_at': '2023-05-17T05:12:58.746194Z', 'token_count': 14}\n",
"{'role': 'ai', 'content': 'Octavia Butler won the Hugo Award, the Nebula Award, and the MacArthur Fellowship.', 'uuid': '39dab3bd-351b-45df-abec-bba056516700', 'created_at': '2023-05-17T05:12:58.743281Z', 'token_count': 21}\n"
]
}
],
"source": [
"def print_messages(messages):\n",
" for m in messages:\n",
" print(m.to_dict())\n",
"\n",
"\n",
"print(zep_chat_history.zep_summary)\n",
"print(\"\\n\")\n",
"print_messages(zep_chat_history.zep_messages)"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"### Vector search over the Zep memory\n",
"\n",
"Zep provides native vector search over historical conversation memory. Embedding happens automatically.\n"
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {
"ExecuteTime": {
"end_time": "2023-05-17T05:13:08.382204Z",
"start_time": "2023-05-17T05:13:08.240341Z"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"{'uuid': '64c606c8-3c4b-424b-855e-df71825c15d7', 'created_at': '2023-05-17T05:12:58.746194Z', 'role': 'human', 'content': 'Which other women sci-fi writers might I want to read?', 'token_count': 14} 0.9119339814710342\n",
"{'uuid': 'b9e52976-3417-4d12-868c-34a197e8111d', 'created_at': '2023-05-17T05:12:58.75184Z', 'role': 'ai', 'content': 'You might want to read Ursula K. Le Guin or Joanna Russ.', 'token_count': 18} 0.8533797599308901\n",
"{'uuid': 'e33fd150-d7f1-4539-84cd-61422208c991', 'created_at': '2023-05-17T05:12:58.718873Z', 'role': 'ai', 'content': \"Octavia Butler's contemporaries included Ursula K. Le Guin, Samuel R. Delany, and Joanna Russ.\", 'token_count': 27} 0.8523616510364422\n",
"{'uuid': '727327f0-b3a9-4564-bd07-1f6bf9e344f0', 'created_at': '2023-05-17T05:12:58.671189Z', 'role': 'human', 'content': 'Who was Octavia Butler?', 'token_count': 8} 0.8235829604682462\n",
"{'uuid': 'db4ecb8c-b887-4de4-bf50-1e497b242fa7', 'created_at': '2023-05-17T05:12:58.699086Z', 'role': 'ai', 'content': 'Octavia Estelle Butler (June 22, 1947 February 24, 2006) was an American science fiction author.', 'token_count': 31} 0.8205039511484328\n",
"{'uuid': '39dab3bd-351b-45df-abec-bba056516700', 'created_at': '2023-05-17T05:12:58.743281Z', 'role': 'ai', 'content': 'Octavia Butler won the Hugo Award, the Nebula Award, and the MacArthur Fellowship.', 'token_count': 21} 0.8197832181782329\n",
"{'uuid': 'b809efd0-0611-4f22-b0a6-acfd19f99078', 'created_at': '2023-05-17T05:12:58.706624Z', 'role': 'human', 'content': 'Which books of hers were made into movies?', 'token_count': 11} 0.7955720292889512\n",
"{'uuid': 'a77a9b03-2eaa-45d0-8883-3fbf6e069a84', 'created_at': '2023-05-17T05:12:58.714159Z', 'role': 'human', 'content': 'Who were her contemporaries?', 'token_count': 8} 0.7943586007524974\n",
"{'uuid': 'd4806cc0-c75e-4c36-80e9-2d74b23aece0', 'created_at': '2023-05-17T05:12:58.757654Z', '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.', 'token_count': 56} 0.7815872510788034\n",
"{'uuid': '7800b21b-00aa-4f60-a30a-e1c645507e66', 'created_at': '2023-05-17T05:12:58.711137Z', '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.\", 'token_count': 29} 0.781267456930058\n"
]
}
],
"source": [
"search_results = zep_chat_history.search(\"who are some famous women sci-fi authors?\")\n",
"for r in search_results:\n",
" print(r.message, r.dist)"
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {
"ExecuteTime": {
"end_time": "2023-05-17T05:13:08.382385Z",
"start_time": "2023-05-17T05:13:08.380270Z"
}
},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": 8,
"outputs": [],
"source": [],
"metadata": {
"collapsed": false,
"ExecuteTime": {
"end_time": "2023-05-17T05:13:08.384260Z",
"start_time": "2023-05-17T05:13:08.381802Z"
}
}
},
{
"cell_type": "code",
"execution_count": null,
"outputs": [],
"source": [],
"metadata": {
"collapsed": false
}
}
],
"metadata": {
"kernelspec": {
"display_name": ".venv",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.11.3"
},
"orig_nbformat": 4
},
"nbformat": 4,
"nbformat_minor": 2
}