Skip to content

Commit e8b89e9

Browse files
committed
docs: more notebook examples
1 parent 0de9ae4 commit e8b89e9

File tree

4 files changed

+1092
-79
lines changed

4 files changed

+1092
-79
lines changed
Lines changed: 276 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,276 @@
1+
{
2+
"cells": [
3+
{
4+
"cell_type": "markdown",
5+
"id": "992c4695-ec4f-428d-bd05-fb3b5fbd70f4",
6+
"metadata": {},
7+
"source": [
8+
"# How to add thread-level memory to a ReAct Agent\n",
9+
"\n",
10+
"<div class=\"admonition tip\">\n",
11+
" <p class=\"admonition-title\">Prerequisites</p>\n",
12+
" <p>\n",
13+
" This guide assumes familiarity with the following:\n",
14+
" <ul>\n",
15+
" <li> \n",
16+
" <a href=\"https://langchain-ai.github.io/langgraph/concepts/persistence/\">\n",
17+
" LangGraph Persistence\n",
18+
" </a>\n",
19+
" </li>\n",
20+
" <li> \n",
21+
" <a href=\"https://langchain-ai.github.io/langgraph/concepts/persistence/#checkpointer-interface\">\n",
22+
" Checkpointer interface\n",
23+
" </a>\n",
24+
" </li>\n",
25+
" <li>\n",
26+
" <a href=\"https://langchain-ai.github.io/langgraph/concepts/agentic_concepts/\">\n",
27+
" Agent Architectures\n",
28+
" </a> \n",
29+
" </li>\n",
30+
" <li>\n",
31+
" <a href=\"https://python.langchain.com/docs/concepts/chat_models/\">\n",
32+
" Chat Models\n",
33+
" </a>\n",
34+
" </li>\n",
35+
" <li>\n",
36+
" <a href=\"https://python.langchain.com/docs/concepts/tools/\">\n",
37+
" Tools\n",
38+
" </a>\n",
39+
" </li>\n",
40+
" </ul>\n",
41+
" </p>\n",
42+
"</div> \n",
43+
"\n",
44+
"This guide will show how to add memory to the prebuilt ReAct agent. Please see [this tutorial](../create-react-agent) for how to get started with the prebuilt ReAct agent\n",
45+
"\n",
46+
"We can add memory to the agent, by passing a [checkpointer](https://langchain-ai.github.io/langgraph/reference/checkpoints/) to the [create_react_agent](https://langchain-ai.github.io/langgraph/reference/prebuilt/#langgraph.prebuilt.chat_agent_executor.create_react_agent) function."
47+
]
48+
},
49+
{
50+
"cell_type": "markdown",
51+
"id": "7be3889f-3c17-4fa1-bd2b-84114a2c7247",
52+
"metadata": {},
53+
"source": [
54+
"## Setup\n",
55+
"\n",
56+
"First, let's install the required packages and set our API keys"
57+
]
58+
},
59+
{
60+
"cell_type": "code",
61+
"execution_count": 9,
62+
"id": "a213e11a-5c62-4ddb-a707-490d91add383",
63+
"metadata": {},
64+
"outputs": [],
65+
"source": [
66+
"%%capture --no-stderr\n",
67+
"%pip install -U langgraph langchain-openai"
68+
]
69+
},
70+
{
71+
"cell_type": "code",
72+
"execution_count": 10,
73+
"id": "23a1885c-04ab-4750-aefa-105891fddf3e",
74+
"metadata": {},
75+
"outputs": [],
76+
"source": [
77+
"import getpass\n",
78+
"import os\n",
79+
"\n",
80+
"\n",
81+
"def _set_env(var: str):\n",
82+
" if not os.environ.get(var):\n",
83+
" os.environ[var] = getpass.getpass(f\"{var}: \")\n",
84+
"\n",
85+
"\n",
86+
"_set_env(\"OPENAI_API_KEY\")"
87+
]
88+
},
89+
{
90+
"cell_type": "markdown",
91+
"id": "87a00ce9",
92+
"metadata": {},
93+
"source": [
94+
"<div class=\"admonition tip\">\n",
95+
" <p class=\"admonition-title\">Set up <a href=\"https://smith.langchain.com\">LangSmith</a> for LangGraph development</p>\n",
96+
" <p style=\"padding-top: 5px;\">\n",
97+
" Sign up for LangSmith to quickly spot issues and improve the performance of your LangGraph projects. LangSmith lets you use trace data to debug, test, and monitor your LLM apps built with LangGraph — read more about how to get started <a href=\"https://docs.smith.langchain.com\">here</a>. \n",
98+
" </p>\n",
99+
"</div>"
100+
]
101+
},
102+
{
103+
"cell_type": "markdown",
104+
"id": "03c0f089-070c-4cd4-87e0-6c51f2477b82",
105+
"metadata": {},
106+
"source": [
107+
"## Code"
108+
]
109+
},
110+
{
111+
"cell_type": "code",
112+
"execution_count": 11,
113+
"id": "7a154152-973e-4b5d-aa13-48c617744a4c",
114+
"metadata": {},
115+
"outputs": [],
116+
"source": [
117+
"# First we initialize the model we want to use.\n",
118+
"from langchain_openai import ChatOpenAI\n",
119+
"\n",
120+
"model = ChatOpenAI(model=\"gpt-4o\", temperature=0)\n",
121+
"\n",
122+
"\n",
123+
"# For this tutorial we will use custom tool that returns pre-defined values for weather in two cities (NYC & SF)\n",
124+
"\n",
125+
"from typing import Literal\n",
126+
"\n",
127+
"from langchain_core.tools import tool\n",
128+
"\n",
129+
"\n",
130+
"@tool\n",
131+
"def get_weather(city: Literal[\"nyc\", \"sf\"]):\n",
132+
" \"\"\"Use this to get weather information.\"\"\"\n",
133+
" if city == \"nyc\":\n",
134+
" return \"It might be cloudy in nyc\"\n",
135+
" elif city == \"sf\":\n",
136+
" return \"It's always sunny in sf\"\n",
137+
" else:\n",
138+
" raise AssertionError(\"Unknown city\")\n",
139+
"\n",
140+
"\n",
141+
"tools = [get_weather]\n",
142+
"\n",
143+
"# We can add \"chat memory\" to the graph with LangGraph's Redi checkpointer\n",
144+
"# to retain the chat context between interactions\n",
145+
"from langgraph.checkpoint.redis import RedisSaver\n",
146+
"\n",
147+
"REDIS_URI = \"redis://redis:6379\"\n",
148+
"memory = None\n",
149+
"with RedisSaver.from_conn_string(REDIS_URI) as cp:\n",
150+
" cp.setup()\n",
151+
" memory = cp\n",
152+
"\n",
153+
"# Define the graph\n",
154+
"\n",
155+
"from langgraph.prebuilt import create_react_agent\n",
156+
"\n",
157+
"graph = create_react_agent(model, tools=tools, checkpointer=memory)"
158+
]
159+
},
160+
{
161+
"cell_type": "markdown",
162+
"id": "00407425-506d-4ffd-9c86-987921d8c844",
163+
"metadata": {},
164+
"source": [
165+
"## Usage\n",
166+
"\n",
167+
"Let's interact with it multiple times to show that it can remember"
168+
]
169+
},
170+
{
171+
"cell_type": "code",
172+
"execution_count": 12,
173+
"id": "16636975-5f2d-4dc7-ab8e-d0bea0830a28",
174+
"metadata": {},
175+
"outputs": [],
176+
"source": [
177+
"def print_stream(stream):\n",
178+
" for s in stream:\n",
179+
" message = s[\"messages\"][-1]\n",
180+
" if isinstance(message, tuple):\n",
181+
" print(message)\n",
182+
" else:\n",
183+
" message.pretty_print()"
184+
]
185+
},
186+
{
187+
"cell_type": "code",
188+
"execution_count": 13,
189+
"id": "9ffff6c3-a4f5-47c9-b51d-97caaee85cd6",
190+
"metadata": {},
191+
"outputs": [
192+
{
193+
"name": "stdout",
194+
"output_type": "stream",
195+
"text": [
196+
"================================\u001b[1m Human Message \u001b[0m=================================\n",
197+
"\n",
198+
"What's the weather in NYC?\n",
199+
"==================================\u001b[1m Ai Message \u001b[0m==================================\n",
200+
"Tool Calls:\n",
201+
" get_weather (call_RHv6T6OBCn7eKOlm5qEpLK4P)\n",
202+
" Call ID: call_RHv6T6OBCn7eKOlm5qEpLK4P\n",
203+
" Args:\n",
204+
" city: nyc\n",
205+
"=================================\u001b[1m Tool Message \u001b[0m=================================\n",
206+
"Name: get_weather\n",
207+
"\n",
208+
"It might be cloudy in nyc\n",
209+
"==================================\u001b[1m Ai Message \u001b[0m==================================\n",
210+
"\n",
211+
"The weather in NYC might be cloudy.\n"
212+
]
213+
}
214+
],
215+
"source": [
216+
"config = {\"configurable\": {\"thread_id\": \"1\"}}\n",
217+
"inputs = {\"messages\": [(\"user\", \"What's the weather in NYC?\")]}\n",
218+
"\n",
219+
"print_stream(graph.stream(inputs, config=config, stream_mode=\"values\"))"
220+
]
221+
},
222+
{
223+
"cell_type": "markdown",
224+
"id": "838a043f-90ad-4e69-9d1d-6e22db2c346c",
225+
"metadata": {},
226+
"source": [
227+
"Notice that when we pass the same the same thread ID, the chat history is preserved"
228+
]
229+
},
230+
{
231+
"cell_type": "code",
232+
"execution_count": 14,
233+
"id": "187479f9-32fa-4611-9487-cf816ba2e147",
234+
"metadata": {},
235+
"outputs": [
236+
{
237+
"name": "stdout",
238+
"output_type": "stream",
239+
"text": [
240+
"================================\u001b[1m Human Message \u001b[0m=================================\n",
241+
"\n",
242+
"What's it known for?\n",
243+
"==================================\u001b[1m Ai Message \u001b[0m==================================\n",
244+
"\n",
245+
"Could you please specify what \"it\" refers to? Are you asking about a specific place, person, event, or something else?\n"
246+
]
247+
}
248+
],
249+
"source": [
250+
"inputs = {\"messages\": [(\"user\", \"What's it known for?\")]}\n",
251+
"print_stream(graph.stream(inputs, config=config, stream_mode=\"values\"))"
252+
]
253+
}
254+
],
255+
"metadata": {
256+
"kernelspec": {
257+
"display_name": "Python 3 (ipykernel)",
258+
"language": "python",
259+
"name": "python3"
260+
},
261+
"language_info": {
262+
"codemirror_mode": {
263+
"name": "ipython",
264+
"version": 3
265+
},
266+
"file_extension": ".py",
267+
"mimetype": "text/x-python",
268+
"name": "python",
269+
"nbconvert_exporter": "python",
270+
"pygments_lexer": "ipython3",
271+
"version": "3.11.11"
272+
}
273+
},
274+
"nbformat": 4,
275+
"nbformat_minor": 5
276+
}

0 commit comments

Comments
 (0)