{ "cells": [ { "cell_type": "markdown", "id": "992c4695-ec4f-428d-bd05-fb3b5fbd70f4", "metadata": {}, "source": [ "# How to add memory to the prebuilt ReAct agent\n", "\n", "
\n", "

Prerequisites

\n", "

\n", " This guide assumes familiarity with the following:\n", "

\n", "

\n", "
\n", "\n", "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", "\n", "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." ] }, { "cell_type": "markdown", "id": "7be3889f-3c17-4fa1-bd2b-84114a2c7247", "metadata": {}, "source": [ "## Setup\n", "\n", "First, let's install the required packages and set our API keys" ] }, { "cell_type": "code", "execution_count": 1, "id": "a213e11a-5c62-4ddb-a707-490d91add383", "metadata": {}, "outputs": [], "source": [ "%%capture --no-stderr\n", "%pip install -U langgraph langchain-openai" ] }, { "cell_type": "code", "execution_count": 2, "id": "23a1885c-04ab-4750-aefa-105891fddf3e", "metadata": {}, "outputs": [], "source": [ "import getpass\n", "import os\n", "\n", "\n", "def _set_env(var: str):\n", " if not os.environ.get(var):\n", " os.environ[var] = getpass.getpass(f\"{var}: \")\n", "\n", "\n", "_set_env(\"OPENAI_API_KEY\")" ] }, { "cell_type": "markdown", "id": "87a00ce9", "metadata": {}, "source": [ "
\n", "

Set up LangSmith for LangGraph development

\n", "

\n", " 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 here. \n", "

\n", "
" ] }, { "cell_type": "markdown", "id": "03c0f089-070c-4cd4-87e0-6c51f2477b82", "metadata": {}, "source": [ "## Code" ] }, { "cell_type": "code", "execution_count": 3, "id": "7a154152-973e-4b5d-aa13-48c617744a4c", "metadata": {}, "outputs": [], "source": [ "# First we initialize the model we want to use.\n", "from langchain_openai import ChatOpenAI\n", "\n", "model = ChatOpenAI(model=\"gpt-4o\", temperature=0)\n", "\n", "\n", "# For this tutorial we will use custom tool that returns pre-defined values for weather in two cities (NYC & SF)\n", "\n", "from typing import Literal\n", "\n", "from langchain_core.tools import tool\n", "\n", "\n", "@tool\n", "def get_weather(city: Literal[\"nyc\", \"sf\"]):\n", " \"\"\"Use this to get weather information.\"\"\"\n", " if city == \"nyc\":\n", " return \"It might be cloudy in nyc\"\n", " elif city == \"sf\":\n", " return \"It's always sunny in sf\"\n", " else:\n", " raise AssertionError(\"Unknown city\")\n", "\n", "\n", "tools = [get_weather]\n", "\n", "# We can add \"chat memory\" to the graph with LangGraph's checkpointer\n", "# to retain the chat context between interactions\n", "from langgraph.checkpoint.memory import MemorySaver\n", "\n", "memory = MemorySaver()\n", "\n", "# Define the graph\n", "\n", "from langgraph.prebuilt import create_react_agent\n", "\n", "graph = create_react_agent(model, tools=tools, checkpointer=memory)" ] }, { "cell_type": "markdown", "id": "00407425-506d-4ffd-9c86-987921d8c844", "metadata": {}, "source": [ "## Usage\n", "\n", "Let's interact with it multiple times to show that it can remember" ] }, { "cell_type": "code", "execution_count": 5, "id": "16636975-5f2d-4dc7-ab8e-d0bea0830a28", "metadata": {}, "outputs": [], "source": [ "def print_stream(stream):\n", " for s in stream:\n", " message = s[\"messages\"][-1]\n", " if isinstance(message, tuple):\n", " print(message)\n", " else:\n", " message.pretty_print()" ] }, { "cell_type": "code", "execution_count": 6, "id": "9ffff6c3-a4f5-47c9-b51d-97caaee85cd6", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "================================\u001b[1m Human Message \u001b[0m=================================\n", "\n", "What's the weather in NYC?\n", "==================================\u001b[1m Ai Message \u001b[0m==================================\n", "Tool Calls:\n", " get_weather (call_xM1suIq26KXvRFqJIvLVGfqG)\n", " Call ID: call_xM1suIq26KXvRFqJIvLVGfqG\n", " Args:\n", " city: nyc\n", "=================================\u001b[1m Tool Message \u001b[0m=================================\n", "Name: get_weather\n", "\n", "It might be cloudy in nyc\n", "==================================\u001b[1m Ai Message \u001b[0m==================================\n", "\n", "The weather in NYC might be cloudy.\n" ] } ], "source": [ "config = {\"configurable\": {\"thread_id\": \"1\"}}\n", "inputs = {\"messages\": [(\"user\", \"What's the weather in NYC?\")]}\n", "\n", "print_stream(graph.stream(inputs, config=config, stream_mode=\"values\"))" ] }, { "cell_type": "markdown", "id": "838a043f-90ad-4e69-9d1d-6e22db2c346c", "metadata": {}, "source": [ "Notice that when we pass the same the same thread ID, the chat history is preserved" ] }, { "cell_type": "code", "execution_count": 7, "id": "187479f9-32fa-4611-9487-cf816ba2e147", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "================================\u001b[1m Human Message \u001b[0m=================================\n", "\n", "What's it known for?\n", "==================================\u001b[1m Ai Message \u001b[0m==================================\n", "\n", "New York City (NYC) is known for a variety of iconic landmarks, cultural institutions, and vibrant neighborhoods. Some of the most notable aspects include:\n", "\n", "1. **Statue of Liberty**: A symbol of freedom and democracy.\n", "2. **Times Square**: Known for its bright lights, Broadway theaters, and bustling atmosphere.\n", "3. **Central Park**: A large urban park offering a green oasis in the middle of the city.\n", "4. **Empire State Building**: An iconic skyscraper with an observation deck offering panoramic views of the city.\n", "5. **Broadway**: Famous for its world-class theater productions.\n", "6. **Wall Street**: The financial hub of the United States.\n", "7. **Museums**: Including the Metropolitan Museum of Art, the Museum of Modern Art (MoMA), and the American Museum of Natural History.\n", "8. **Diverse Cuisine**: A melting pot of culinary experiences from around the world.\n", "9. **Cultural Diversity**: A rich tapestry of cultures, languages, and traditions.\n", "10. **Fashion**: A global fashion capital, home to New York Fashion Week.\n", "\n", "These are just a few highlights of what makes NYC a unique and vibrant city.\n" ] } ], "source": [ "inputs = {\"messages\": [(\"user\", \"What's it known for?\")]}\n", "print_stream(graph.stream(inputs, config=config, stream_mode=\"values\"))" ] }, { "cell_type": "code", "execution_count": null, "id": "c461eb47-b4f9-406f-8923-c68db7c5687f", "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "Python 3 (ipykernel)", "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.4" } }, "nbformat": 4, "nbformat_minor": 5 }