How to add memory to the prebuilt ReAct agent¶
This tutorial will show how to add memory to the prebuilt ReAct agent. Please see this tutorial for how to get started with the prebuilt ReAct agent
All we need to do to enable memory is pass in a checkpointer to create_react_agents
Setup¶
First, let's install the required packages and set our API keys
In [1]:
Copied!
%%capture --no-stderr
%pip install -U langgraph langchain-openai
%%capture --no-stderr
%pip install -U langgraph langchain-openai
In [ ]:
Copied!
import getpass
import os
def _set_env(var: str):
if not os.environ.get(var):
os.environ[var] = getpass.getpass(f"{var}: ")
_set_env("OPENAI_API_KEY")
import getpass
import os
def _set_env(var: str):
if not os.environ.get(var):
os.environ[var] = getpass.getpass(f"{var}: ")
_set_env("OPENAI_API_KEY")
Code¶
In [3]:
Copied!
# First we initialize the model we want to use.
from langchain_openai import ChatOpenAI
model = ChatOpenAI(model="gpt-4o", temperature=0)
# For this tutorial we will use custom tool that returns pre-defined values for weather in two cities (NYC & SF)
from typing import Literal
from langchain_core.tools import tool
@tool
def get_weather(city: Literal["nyc", "sf"]):
"""Use this to get weather information."""
if city == "nyc":
return "It might be cloudy in nyc"
elif city == "sf":
return "It's always sunny in sf"
else:
raise AssertionError("Unknown city")
tools = [get_weather]
# We can add "chat memory" to the graph with LangGraph's checkpointer
# to retain the chat context between interactions
from langgraph.checkpoint.memory import MemorySaver
memory = MemorySaver()
# Define the graph
from langgraph.prebuilt import create_react_agent
graph = create_react_agent(model, tools=tools, checkpointer=memory)
# First we initialize the model we want to use.
from langchain_openai import ChatOpenAI
model = ChatOpenAI(model="gpt-4o", temperature=0)
# For this tutorial we will use custom tool that returns pre-defined values for weather in two cities (NYC & SF)
from typing import Literal
from langchain_core.tools import tool
@tool
def get_weather(city: Literal["nyc", "sf"]):
"""Use this to get weather information."""
if city == "nyc":
return "It might be cloudy in nyc"
elif city == "sf":
return "It's always sunny in sf"
else:
raise AssertionError("Unknown city")
tools = [get_weather]
# We can add "chat memory" to the graph with LangGraph's checkpointer
# to retain the chat context between interactions
from langgraph.checkpoint.memory import MemorySaver
memory = MemorySaver()
# Define the graph
from langgraph.prebuilt import create_react_agent
graph = create_react_agent(model, tools=tools, checkpointer=memory)
Usage¶
Let's interact with it multiple times to show that it can remember
In [4]:
Copied!
def print_stream(stream):
for s in stream:
message = s["messages"][-1]
if isinstance(message, tuple):
print(message)
else:
message.pretty_print()
def print_stream(stream):
for s in stream:
message = s["messages"][-1]
if isinstance(message, tuple):
print(message)
else:
message.pretty_print()
In [5]:
Copied!
config = {"configurable": {"thread_id": "1"}}
inputs = {"messages": [("user", "What's the weather in NYC?")]}
print_stream(graph.stream(inputs, config=config, stream_mode="values"))
config = {"configurable": {"thread_id": "1"}}
inputs = {"messages": [("user", "What's the weather in NYC?")]}
print_stream(graph.stream(inputs, config=config, stream_mode="values"))
================================ Human Message ================================= What's the weather in NYC? ================================== Ai Message ================================== Tool Calls: get_weather (call_mdovy4yXSSYrmSlnlVSUacVn) Call ID: call_mdovy4yXSSYrmSlnlVSUacVn Args: city: nyc ================================= Tool Message ================================= Name: get_weather It might be cloudy in nyc ================================== Ai Message ================================== The weather in NYC might be cloudy.
Notice that when we pass the same the same thread ID, the chat history is preserved
In [6]:
Copied!
inputs = {"messages": [("user", "What's it known for?")]}
print_stream(graph.stream(inputs, config=config, stream_mode="values"))
inputs = {"messages": [("user", "What's it known for?")]}
print_stream(graph.stream(inputs, config=config, stream_mode="values"))
================================ Human Message ================================= What's it known for? ================================== Ai Message ================================== New York City (NYC) is known for many things, including: 1. **Landmarks and Attractions**: The Statue of Liberty, Times Square, Central Park, Empire State Building, and Brooklyn Bridge. 2. **Cultural Institutions**: Broadway theaters, Metropolitan Museum of Art, Museum of Modern Art (MoMA), and the American Museum of Natural History. 3. **Diverse Neighborhoods**: Areas like Chinatown, Little Italy, Harlem, and Greenwich Village. 4. **Financial Hub**: Wall Street and the New York Stock Exchange. 5. **Cuisine**: A melting pot of global cuisines, famous for its pizza, bagels, and street food. 6. **Media and Entertainment**: Home to major media companies, TV networks, and film studios. 7. **Fashion**: A global fashion capital, hosting New York Fashion Week. 8. **Sports**: Teams like the New York Yankees, New York Mets, New York Knicks, and New York Rangers. 9. **Public Transportation**: An extensive subway system and iconic yellow taxis. 10. **Events**: New Year's Eve celebration in Times Square, Macy's Thanksgiving Day Parade, and various cultural festivals.