Compare commits

...
Author SHA1 Message Date
William Fu-Hinthorn 38fac0099c update
Signed-off-by: William Fu-Hinthorn <13333726+hinthornw@users.noreply.github.com>
2025-04-03 10:00:46 -07:00
William Fu-Hinthorn 3ac3fb414e Show lifespan 2025-04-03 09:23:23 -07:00
Vadym Barda e89633f30b prebuilt: release 0.1.8 (#4161) 2025-04-03 12:01:18 -04:00
Vadym Barda 0bbf5829e8 docs: add a how-to guide for managing message history in create_react_agent (#4149) 2025-04-03 16:00:11 +00:00
11 changed files with 1318 additions and 893 deletions

No files matched your search

@@ -0,0 +1 @@
eNptV3tcVHUWB3zAbr7yo1mmdZt8JM4dZphhGEAyXibKADI8xCD3zr2/YS5zX9wHMBiZtNaapo2htqW1IY9E8rGwaiVpa1k+UjNw1Tay1NxtSU1LS9d1z29meGX3j/nM3HPO97y+5/x+U9NUjmSFFYXQFlZQkUzRKvxQfDVNMirTkKL+sZFHqltk6rOzHLkbNZk9FelWVUmJj4qiJNYgSkigWAMt8lHlpijaTalR8F3ikB+m3iky3tND0xbpeKQoVAlSdPFPLNLRIrgSVF28rgAMpioEqxIeQawQCJcoz9TpdbLIIZBqCpJ11fr+BpmogigUZQ+RwqpeglX67AiKKKdkFsFr0UWwYMLSBEcJDE/JHkVP0BqnajLFEaygqKyq+QPUE6BAlLNOmRJUQkBsidspym5RZBQD4RB5hLFUNyJ4UQG5qFJODhEuRAEUgrgFmtMYFF8kFAkmAxEZ6VBB4jfKYJ1IVr2RkfFEEqF4eafI4dcuGSFG5P1uGcSLNFTcqyc4kaZUxBCi0GNIpCs4eEOREI2Bc1moIOEo0ygZYcy5vWmzqkI4ZQhcJTj8CTklyyLFVFBeHDnAysE0nZqicqxQQlAqpCO5kYwA3ozhU6C6uDbZUKtAyBwllyBC0pwclFGC1xC9C8l+c0KgAqWUkSqDB6hDoEgsA1UKVoyGBgG8BcOn8RIrIwJXBxHJGssxgOP3I/R0SvF4FSiGhOQ+RxIliDLFg7ScRRXKr5BjMHJPqhhsFsWLmt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"id": "992c4695-ec4f-428d-bd05-fb3b5fbd70f4",
"metadata": {},
"source": [
"# How to manage conversation history in a ReAct Agent\n",
"\n",
"!!! info \"Prerequisites\"\n",
" This guide assumes familiarity with the following:\n",
"\n",
" - [Prebuilt create_react_agent](../create-react-agent)\n",
" - [Persistence](../../concepts/persistence)\n",
" - [Short-term Memory](../../concepts/memory/#short-term-memory)\n",
" - [Trimming Messages](https://python.langchain.com/docs/how_to/trim_messages/)\n",
"\n",
"Message history can grow quickly and exceed LLM context window size, whether you're building chatbots with many conversation turns or agentic systems with numerous tool calls. There are several strategies for managing the message history:\n",
"\n",
"* [message trimming](#keep-the-original-message-history-unmodified) - remove first or last N messages in the history\n",
"* [summarization](#summarizing-message-history) - summarize earlier messages in the history and replace them with a summary\n",
"* custom strategies (e.g., message filtering, etc.)\n",
"\n",
"To manage message history in `create_react_agent`, you need to define a `pre_model_hook` function or [runnable](https://python.langchain.com/docs/concepts/runnables/) that takes graph state an returns a state update:\n",
"\n",
"\n",
"* Trimming example:\n",
" ```python\n",
" # highlight-next-line\n",
" from langchain_core.messages.utils import (\n",
" # highlight-next-line\n",
" trim_messages, \n",
" # highlight-next-line\n",
" count_tokens_approximately\n",
" # highlight-next-line\n",
" )\n",
" from langgraph.prebuilt import create_react_agent\n",
" \n",
" # This function will be called every time before the node that calls LLM\n",
" def pre_model_hook(state):\n",
" trimmed_messages = trim_messages(\n",
" state[\"messages\"],\n",
" strategy=\"last\",\n",
" token_counter=count_tokens_approximately,\n",
" max_tokens=384,\n",
" start_on=\"human\",\n",
" end_on=(\"human\", \"tool\"),\n",
" )\n",
" # You can return updated messages either under `llm_input_messages` or \n",
" # `messages` key (see the note below)\n",
" # highlight-next-line\n",
" return {\"llm_input_messages\": trimmed_messages}\n",
"\n",
" checkpointer = InMemorySaver()\n",
" agent = create_react_agent(\n",
" model,\n",
" tools,\n",
" # highlight-next-line\n",
" pre_model_hook=pre_model_hook,\n",
" checkpointer=checkpointer,\n",
" )\n",
" ```\n",
"\n",
"* Summarization example:\n",
" ```python\n",
" # highlight-next-line\n",
" from langmem.short_term import SummarizationNode\n",
" from langchain_core.messages.utils import count_tokens_approximately\n",
" from langgraph.prebuilt.chat_agent_executor import AgentState\n",
" from langgraph.checkpoint.memory import InMemorySaver\n",
" from typing import Any\n",
" \n",
" model = ChatOpenAI(model=\"gpt-4o\")\n",
" \n",
" summarization_node = SummarizationNode(\n",
" token_counter=count_tokens_approximately,\n",
" model=model,\n",
" max_tokens=384,\n",
" max_summary_tokens=128,\n",
" output_messages_key=\"llm_input_messages\",\n",
" )\n",
"\n",
" class State(AgentState):\n",
" # NOTE: we're adding this key to keep track of previous summary information\n",
" # to make sure we're not summarizing on every LLM call\n",
" # highlight-next-line\n",
" context: dict[str, Any]\n",
" \n",
" \n",
" checkpointer = InMemorySaver()\n",
" graph = create_react_agent(\n",
" model,\n",
" tools,\n",
" # highlight-next-line\n",
" pre_model_hook=summarization_node,\n",
" # highlight-next-line\n",
" state_schema=State,\n",
" checkpointer=checkpointer,\n",
" )\n",
" ```\n",
"\n",
"!!! Important\n",
" \n",
" * To **keep the original message history unmodified** in the graph state and pass the updated history **only as the input to the LLM**, return updated messages under `llm_input_messages` key\n",
" * To **overwrite the original message history** in the graph state with the updated history, return updated messages under `messages` key\n",
" \n",
" To overwrite the `messages` key, you need to do the following:\n",
"\n",
" ```python\n",
" from langchain_core.messages import RemoveMessage\n",
" from langgraph.graph.message import REMOVE_ALL_MESSAGES\n",
"\n",
" def pre_model_hook(state):\n",
" updated_messages = ...\n",
" return {\n",
" \"messages\": [RemoveMessage(id=REMOVE_ALL_MESSAGES), *updated_messages]\n",
" ...\n",
" }\n",
" ```"
]
},
{
"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 langmem"
]
},
{
"cell_type": "code",
"execution_count": null,
"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": [
"<div class=\"admonition tip\">\n",
" <p class=\"admonition-title\">Set up <a href=\"https://smith.langchain.com\">LangSmith</a> for LangGraph development</p>\n",
" <p style=\"padding-top: 5px;\">\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 <a href=\"https://docs.smith.langchain.com\">here</a>. \n",
" </p>\n",
"</div>"
]
},
{
"cell_type": "markdown",
"id": "03c0f089-070c-4cd4-87e0-6c51f2477b82",
"metadata": {},
"source": [
"## Keep the original message history unmodified"
]
},
{
"cell_type": "markdown",
"id": "cd6cbd3a-8632-47ae-9ec5-eec8d7b05cae",
"metadata": {},
"source": [
"Let's build a ReAct agent with a step that manages the conversation history: when the length of the history exceeds a specified number of tokens, we will call [`trim_messages`](https://python.langchain.com/api_reference/core/messages/langchain_core.messages.utils.trim_messages.html) utility that that will reduce the history while satisfying LLM provider constraints.\n",
"\n",
"There are two ways that the updated message history can be applied inside ReAct agent:\n",
"\n",
" * [**Keep the original message history unmodified**](#keep-the-original-message-history-unmodified) in the graph state and pass the updated history **only as the input to the LLM**\n",
" * [**Overwrite the original message history**](#overwrite-the-original-message-history) in the graph state with the updated history\n",
"\n",
"Let's start by implementing the first one. We'll need to first define model and tools for our agent:"
]
},
{
"cell_type": "code",
"execution_count": 3,
"id": "eaad19ee-e174-4c6c-b2b8-3530d7acea40",
"metadata": {},
"outputs": [],
"source": [
"from langchain_openai import ChatOpenAI\n",
"\n",
"model = ChatOpenAI(model=\"gpt-4o\", temperature=0)\n",
"\n",
"\n",
"def get_weather(location: str) -> str:\n",
" \"\"\"Use this to get weather information.\"\"\"\n",
" if any([city in location.lower() for city in [\"nyc\", \"new york city\"]]):\n",
" return \"It might be cloudy in nyc, with a chance of rain and temperatures up to 80 degrees.\"\n",
" elif any([city in location.lower() for city in [\"sf\", \"san francisco\"]]):\n",
" return \"It's always sunny in sf\"\n",
" else:\n",
" return f\"I am not sure what the weather is in {location}\"\n",
"\n",
"\n",
"tools = [get_weather]"
]
},
{
"cell_type": "markdown",
"id": "52402333-61ab-47d3-8549-6a70f6f1cf36",
"metadata": {},
"source": [
"Now let's implement `pre_model_hook` — a function that will be added as a new node and called every time **before** the node that calls the LLM (the `agent` node).\n",
"\n",
"Our implementation will wrap the `trim_messages` call and return the trimmed messages under `llm_input_messages`. This will **keep the original message history unmodified** in the graph state and pass the updated history **only as the input to the LLM**"
]
},
{
"cell_type": "code",
"execution_count": 4,
"id": "b507eb58-6e02-4ac6-b48b-ea4defdc11f0",
"metadata": {},
"outputs": [],
"source": [
"from langgraph.prebuilt import create_react_agent\n",
"from langgraph.checkpoint.memory import InMemorySaver\n",
"\n",
"# highlight-next-line\n",
"from langchain_core.messages.utils import (\n",
" # highlight-next-line\n",
" trim_messages,\n",
" # highlight-next-line\n",
" count_tokens_approximately,\n",
" # highlight-next-line\n",
")\n",
"\n",
"\n",
"# This function will be added as a new node in ReAct agent graph\n",
"# that will run every time before the node that calls the LLM.\n",
"# The messages returned by this function will be the input to the LLM.\n",
"def pre_model_hook(state):\n",
" trimmed_messages = trim_messages(\n",
" state[\"messages\"],\n",
" strategy=\"last\",\n",
" token_counter=count_tokens_approximately,\n",
" max_tokens=384,\n",
" start_on=\"human\",\n",
" end_on=(\"human\", \"tool\"),\n",
" )\n",
" # highlight-next-line\n",
" return {\"llm_input_messages\": trimmed_messages}\n",
"\n",
"\n",
"checkpointer = InMemorySaver()\n",
"graph = create_react_agent(\n",
" model,\n",
" tools,\n",
" # highlight-next-line\n",
" pre_model_hook=pre_model_hook,\n",
" checkpointer=checkpointer,\n",
")"
]
},
{
"cell_type": "code",
"execution_count": 5,
"id": "8182ab45-86b3-4d6f-b75e-58862a14fa4e",
"metadata": {},
"outputs": [
{
"data": {
"image/png": "iVBORw0KGgoAAAANSUhEUgAAANgAAAFcCAIAAAAlFOfAAAAAAXNSR0IArs4c6QAAIABJREFUeJztnXdcU9ffx8/NXhBGWAEiU7YLJ7YuFNw4cVd/aod7z1arVVtrtVqsVqtVa91WxWptxVVRXFXrQBEQGbJ3IHs+f8QnUgsIkpNzE8775R/JvTfnfBI+nn2+h9Dr9QCDQQ0FtQAMBmAjYsgCNiKGFGAjYkgBNiKGFGAjYkgBDbUA06OUa8vyVbJqraxao9HoNSoLGJ9isik0BsGxoXFsqS6eLNRyEGA9RpRWqdPvS18kS6rK1DYOdI4NlWNDs3WgA0sYKNVpQVGWUlYtpTMpOc9k3qFcnzCuTxgPtS7zQVjBgLZOq79xpqw0X+koZPiE8tz92KgVNQmFTJuZLM1Nl+W/UEQMdPRva4NakTmweCM+uSX+63hJxCDHtj3sUWsxMVVl6htny5QybdQEVzaPiloOXCzbiH8dL2ZxKJ0HCFALgUhpgTJ+W17fia4e/hzUWiBiwUa8cKDI1ZsV1pWPWog5OLUt7/2hAoGQiVoILCzViPHb8/za8EIjmoULDZzalhvW1c6vjXX2YCxyHPFafIlXMLdZuRAAMHSGx60/yiqKVKiFQMHyjJh6v5pGp7TpYYdaCALGLRVdOV5soZVY/VieEa8eL2nXqzm6EABAEIRXMPfGmTLUQkyPhRnx3sWK0K62TLaVj2XUQ7te9k9vVymkWtRCTIwlGVGv1+ekyiIGWvNgTUPoNszpwdVK1CpMjCUZ8cVjKZNtSYIhIQrgJN8Qo1ZhYizp75qZLPUO5Zo50yVLlpw5c+YdPti7d+/8/HwIigCbR7UTMAqy5DASR4UlGbGyRO0TZm4jpqSkvMO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deuX/lx19bCwnxPzxaLF30eGBBcv556btXkwYN7i5bMWLvm204dIxolyfygNyKNSgMA7NwVt2zpF4EBwbduXV+5apFI5DWg/xA6na5QyE+eOrJk8SqRyAsAsGPnd7+fOzV39tKQ0Nb37t3+fttGGo02oP+QetKn0mgAgD17f1i2ZLW7u+f6rz/fvOXLkOBWa77YZGvLX7ps9tbvv9n+/T4AwJbv1l9P+mvunKUBAcFPnz7e8t1XSqVyxvT5AICv1q/Mzcv56svvHB0E8aePJV67bGvLN4RLXLJ0lkQqWbJ4laOD4PRvx5cum/3Dtv0+Pn4N/wWKiwrPnDmxeOFKAMCWuPVfrV/5895f69dTzy0jubk5K1ctGj3qA/K7kERVc5/e/YODQikUSkREt7Zt2p9POGuI7KFQKEYMH9u5U1ehm7tEIjn92/FRsROiowd6uHvGDB4RHTXw0OF9DUm/Z48+IpEXlUrt0b2PTCbr33+IQODEYDC6dYvMyEgDAIjFlQkXfv9gwtRePaPchR59evcbNnT02d9PqtXqkpLi+//8PWb0pHZtO7Ro4T171mIOh2tI9u6922npzxYu+Mxwa+aMhS4ubidPHWnUdy+vKPt0+dqwsDZhYW2GDR2dk5MlkUjq0VPPLWOaYnHl0uVzunR5f8rk6Y38U6CBLEZs6R9ofN2ihU9+/utDdYKDwwwvMjLSNBpN+/DOxlutW4fn5+fKZLK3pi/yfBVvmMPl1nzL5XBVKpVKpcp4ka7VaoODwowfCQgIVigUubk52TmZAIDAwBDDdYIgjK9TUpLpdHqb1uGGtxQKpVVY2+fPUxv13T0Line truncated
"text/plain": [
"<IPython.core.display.Image object>"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"from IPython.display import display, Image\n",
"\n",
"display(Image(graph.get_graph().draw_mermaid_png()))"
]
},
{
"cell_type": "markdown",
"id": "d41e8e76-5d43-44cd-bf01-a39212cedd8d",
"metadata": {},
"source": [
"We'll also define a utility to render the agent outputs nicely:"
]
},
{
"cell_type": "code",
"execution_count": 6,
"id": "16636975-5f2d-4dc7-ab8e-d0bea0830a28",
"metadata": {},
"outputs": [],
"source": [
"def print_stream(stream, output_messages_key=\"llm_input_messages\"):\n",
" for chunk in stream:\n",
" for node, update in chunk.items():\n",
" print(f\"Update from node: {node}\")\n",
" messages_key = (\n",
" output_messages_key if node == \"pre_model_hook\" else \"messages\"\n",
" )\n",
" for message in update[messages_key]:\n",
" if isinstance(message, tuple):\n",
" print(message)\n",
" else:\n",
" message.pretty_print()\n",
"\n",
" print(\"\\n\\n\")"
]
},
{
"cell_type": "markdown",
"id": "84448d29-b323-4833-80fc-4fff2f5a0950",
"metadata": {},
"source": [
"Now let's run the agent with a few different queries to reach the specified max tokens limit:"
]
},
{
"cell_type": "code",
"execution_count": 7,
"id": "9ffff6c3-a4f5-47c9-b51d-97caaee85cd6",
"metadata": {},
"outputs": [],
"source": [
"config = {\"configurable\": {\"thread_id\": \"1\"}}\n",
"\n",
"inputs = {\"messages\": [(\"user\", \"What's the weather in NYC?\")]}\n",
"result = graph.invoke(inputs, config=config)\n",
"\n",
"inputs = {\"messages\": [(\"user\", \"What's it known for?\")]}\n",
"result = graph.invoke(inputs, config=config)"
]
},
{
"cell_type": "markdown",
"id": "fdb186da-b55d-4cb8-a237-e9e157ab0458",
"metadata": {},
"source": [
"Let's see how many tokens we have in the message history so far:"
]
},
{
"cell_type": "code",
"execution_count": 8,
"id": "41ba0253-5199-4d29-82ae-258cbbebddb4",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"415"
]
},
"execution_count": 8,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"messages = result[\"messages\"]\n",
"count_tokens_approximately(messages)"
]
},
{
"attachments": {},
"cell_type": "markdown",
"id": "812987ac-66ba-4122-8281-469cbdced7c7",
"metadata": {},
"source": [
"You can see that we are close to the `max_tokens` threshold, so on the next invocation we should see `pre_model_hook` kick-in and trim the message history. Let's run it again:"
]
},
{
"cell_type": "code",
"execution_count": 9,
"id": "26c53429-90ba-4d0b-abb9-423d9120ad26",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Update from node: pre_model_hook\n",
"================================\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 is known for a variety of iconic landmarks, cultural institutions, and vibrant neighborhoods. Some of the most notable features include:\n",
"\n",
"1. **Statue of Liberty**: A symbol of freedom and democracy, located on Liberty Island.\n",
"2. **Times Square**: Known for its bright lights, Broadway theaters, and bustling atmosphere.\n",
"3. **Central Park**: A large public park offering a natural retreat in the middle of the city.\n",
"4. **Empire State Building**: An iconic skyscraper 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, Museum of Modern Art (MoMA), and the American Museum of Natural History.\n",
"8. **Diverse Cuisine**: A melting pot of cultures offering a wide range of culinary experiences.\n",
"9. **Cultural Diversity**: A rich tapestry of cultures and communities from around the world.\n",
"10. **Fashion**: A global fashion capital, hosting events like New York Fashion Week.\n",
"\n",
"These are just a few highlights of what makes New York City a unique and vibrant place.\n",
"================================\u001b[1m Human Message \u001b[0m=================================\n",
"\n",
"where can i find the best bagel?\n",
"\n",
"\n",
"\n",
"Update from node: agent\n",
"==================================\u001b[1m Ai Message \u001b[0m==================================\n",
"\n",
"New York City is famous for its bagels, and there are several places renowned for serving some of the best. Here are a few top spots where you can find excellent bagels in NYC:\n",
"\n",
"1. **Ess-a-Bagel**: Known for their large, chewy bagels with a variety of spreads and toppings.\n",
"2. **Russ & Daughters**: A classic spot offering traditional bagels with high-quality smoked fish and cream cheese.\n",
"3. **H&H Bagels**: Famous for their fresh, hand-rolled bagels.\n",
"4. **Murray’s Bagels**: Offers a wide selection of bagels and spreads, with a no-toasting policy to preserve freshness.\n",
"5. **Absolute Bagels**: Known for their authentic, fluffy bagels and a variety of cream cheese options.\n",
"6. **Tompkins Square Bagels**: Offers creative bagel sandwiches and a wide range of spreads.\n",
"7. **Bagel Hole**: Known for their smaller, denser bagels with a crispy crust.\n",
"\n",
"Each of these places has its own unique style and flavor, so it might be worth trying a few to find your personal favorite!\n",
"\n",
"\n",
"\n"
]
}
],
"source": [
"inputs = {\"messages\": [(\"user\", \"where can i find the best bagel?\")]}\n",
"print_stream(graph.stream(inputs, config=config, stream_mode=\"updates\"))"
]
},
{
"cell_type": "markdown",
"id": "58fe0399-4e7d-4482-a4cb-5301311932d0",
"metadata": {},
"source": [
"You can see that the `pre_model_hook` node now only returned the last 3 messages, as expected. However, the existing message history is untouched:"
]
},
{
"cell_type": "code",
"execution_count": 10,
"id": "7ecfc310-8f9e-4aa0-9e58-17e71551639a",
"metadata": {},
"outputs": [],
"source": [
"updated_messages = graph.get_state(config).values[\"messages\"]\n",
"assert [(m.type, m.content) for m in updated_messages[: len(messages)]] == [\n",
" (m.type, m.content) for m in messages\n",
"]"
]
},
{
"cell_type": "markdown",
"id": "035864e3-0083-4dea-bf85-3a702fa5303f",
"metadata": {},
"source": [
"## Overwrite the original message history"
]
},
{
"cell_type": "markdown",
"id": "0b0a4fd5-a2ba-4eca-91a9-d294f4f2d884",
"metadata": {},
"source": [
"Let's now change the `pre_model_hook` to **overwrite** the message history in the graph state. To do this, we’ll return the updated messages under `messages` key. We’ll also include a special `RemoveMessage(REMOVE_ALL_MESSAGES)` object, which tells `create_react_agent` to remove previous messages from the graph state:"
]
},
{
"cell_type": "code",
"execution_count": 11,
"id": "48c2a65b-685a-4750-baa6-2d61efe76b5f",
"metadata": {},
"outputs": [],
"source": [
"from langchain_core.messages import RemoveMessage\n",
"from langgraph.graph.message import REMOVE_ALL_MESSAGES\n",
"\n",
"\n",
"def pre_model_hook(state):\n",
" trimmed_messages = trim_messages(\n",
" state[\"messages\"],\n",
" strategy=\"last\",\n",
" token_counter=count_tokens_approximately,\n",
" max_tokens=384,\n",
" start_on=\"human\",\n",
" end_on=(\"human\", \"tool\"),\n",
" )\n",
" # NOTE that we're now returning the messages under the `messages` key\n",
" # We also remove the existing messages in the history to ensure we're overwriting the history\n",
" # highlight-next-line\n",
" return {\"messages\": [RemoveMessage(REMOVE_ALL_MESSAGES)] + trimmed_messages}\n",
"\n",
"\n",
"checkpointer = InMemorySaver()\n",
"graph = create_react_agent(\n",
" model,\n",
" tools,\n",
" # highlight-next-line\n",
" pre_model_hook=pre_model_hook,\n",
" checkpointer=checkpointer,\n",
")"
]
},
{
"cell_type": "markdown",
"id": "cd061682-231c-4487-9c2f-a6820dfbcab7",
"metadata": {},
"source": [
"Now let's run the agent with the same queries as before:"
]
},
{
"cell_type": "code",
"execution_count": 12,
"id": "831be36a-78a1-4885-9a03-8d085dfd7e37",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Update from node: pre_model_hook\n",
"================================\u001b[1m Remove Message \u001b[0m================================\n",
"\n",
"\n",
"================================\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 is known for a variety of iconic landmarks, cultural institutions, and vibrant neighborhoods. Some of the most notable features include:\n",
"\n",
"1. **Statue of Liberty**: A symbol of freedom and democracy, located on Liberty Island.\n",
"2. **Times Square**: Known for its bright lights, Broadway theaters, and bustling atmosphere.\n",
"3. **Central Park**: A large public park offering a natural oasis amidst the urban environment.\n",
"4. **Empire State Building**: An iconic skyscraper offering panoramic views of the city.\n",
"5. **Broadway**: Famous for its world-class theater productions and musicals.\n",
"6. **Wall Street**: The financial hub of the United States, located in the Financial District.\n",
"7. **Museums**: Including the Metropolitan Museum of Art, Museum of Modern Art (MoMA), and the American Museum of Natural History.\n",
"8. **Diverse Cuisine**: A melting pot of cultures, offering a wide range of international foods.\n",
"9. **Cultural Diversity**: Known for its diverse population and vibrant cultural scene.\n",
"10. **Brooklyn Bridge**: An iconic suspension bridge connecting Manhattan and Brooklyn.\n",
"\n",
"These are just a few highlights, as NYC is a city with endless attractions and activities.\n",
"================================\u001b[1m Human Message \u001b[0m=================================\n",
"\n",
"where can i find the best bagel?\n",
"\n",
"\n",
"\n",
"Update from node: agent\n",
"==================================\u001b[1m Ai Message \u001b[0m==================================\n",
"\n",
"New York City is famous for its bagels, and there are several places renowned for serving some of the best. Here are a few top spots where you can find delicious bagels in NYC:\n",
"\n",
"1. **Ess-a-Bagel**: Known for its large, chewy bagels and a wide variety of spreads and toppings. Locations in Midtown and the East Village.\n",
"\n",
"2. **Russ & Daughters**: A historic appetizing store on the Lower East Side, famous for its bagels with lox and cream cheese.\n",
"\n",
"3. **Absolute Bagels**: Located on the Upper West Side, this spot is popular for its fresh, fluffy bagels.\n",
"\n",
"4. **Murray’s Bagels**: Known for its traditional, hand-rolled bagels. Located in Greenwich Village.\n",
"\n",
"5. **Tompkins Square Bagels**: Offers a wide selection of bagels and creative cream cheese flavors. Located in the East Village.\n",
"\n",
"6. **Bagel Hole**: A small shop in Park Slope, Brooklyn, known for its classic, no-frills bagels.\n",
"\n",
"7. **Leo’s Bagels**: Located in the Financial District, known for its authentic New York-style bagels.\n",
"\n",
"Each of these places has its own unique style and flavor, so it might be worth trying a few to find your personal favorite!\n",
"\n",
"\n",
"\n"
]
}
],
"source": [
"config = {\"configurable\": {\"thread_id\": \"1\"}}\n",
"\n",
"inputs = {\"messages\": [(\"user\", \"What's the weather in NYC?\")]}\n",
"result = graph.invoke(inputs, config=config)\n",
"\n",
"inputs = {\"messages\": [(\"user\", \"What's it known for?\")]}\n",
"result = graph.invoke(inputs, config=config)\n",
"messages = result[\"messages\"]\n",
"\n",
"inputs = {\"messages\": [(\"user\", \"where can i find the best bagel?\")]}\n",
"print_stream(\n",
" graph.stream(inputs, config=config, stream_mode=\"updates\"),\n",
" output_messages_key=\"messages\",\n",
")"
]
},
{
"cell_type": "markdown",
"id": "cc9a0604-3d2b-48ff-9eaf-d16ea351fb30",
"metadata": {},
"source": [
"You can see that the `pre_model_hook` node returned the last 3 messages again. However, this time, the message history is modified in the graph state as well:"
]
},
{
"cell_type": "code",
"execution_count": 13,
"id": "394f72f8-f817-472d-a193-e01509a86132",
"metadata": {},
"outputs": [],
"source": [
"updated_messages = graph.get_state(config).values[\"messages\"]\n",
"assert (\n",
" # First 2 messages in the new history are the same as last 2 messages in the old\n",
" [(m.type, m.content) for m in updated_messages[:2]]\n",
" == [(m.type, m.content) for m in messages[-2:]]\n",
")"
]
},
{
"cell_type": "markdown",
"id": "ee186d6d-4d07-404f-b236-f662db62339d",
"metadata": {},
"source": [
"## Summarizing message history"
]
},
{
"cell_type": "markdown",
"id": "a6e53e0f-9a1e-4188-8435-c23ad8148b4f",
"metadata": {},
"source": [
"Finally, let's apply a different strategy for managing message history — summarization. Just as with trimming, you can choose to keep original message history unmodified or overwrite it. The example below will only show the former.\n",
"\n",
"We will use the [`SummarizationNode`](https://langchain-ai.github.io/langmem/guides/summarization/#using-summarizationnode) from the prebuilt `langmem` library. Once the message history reaches the token limit, the summarization node will summarize earlier messages to make sure they fit into `max_tokens`."
]
},
{
"cell_type": "code",
"execution_count": 14,
"id": "b9540c1c-2eba-42da-ba4e-478521161a1f",
"metadata": {},
"outputs": [],
"source": [
"# highlight-next-line\n",
"from langmem.short_term import SummarizationNode\n",
"from langgraph.prebuilt.chat_agent_executor import AgentState\n",
"from typing import Any\n",
"\n",
"model = ChatOpenAI(model=\"gpt-4o\")\n",
"summarization_model = model.bind(max_tokens=128)\n",
"\n",
"summarization_node = SummarizationNode(\n",
" token_counter=count_tokens_approximately,\n",
" model=summarization_model,\n",
" max_tokens=384,\n",
" max_summary_tokens=128,\n",
" output_messages_key=\"llm_input_messages\",\n",
")\n",
"\n",
"\n",
"class State(AgentState):\n",
" # NOTE: we're adding this key to keep track of previous summary information\n",
" # to make sure we're not summarizing on every LLM call\n",
" # highlight-next-line\n",
" context: dict[str, Any]\n",
"\n",
"\n",
"checkpointer = InMemorySaver()\n",
"graph = create_react_agent(\n",
" model,\n",
" tools,\n",
" # highlight-next-line\n",
" pre_model_hook=summarization_node,\n",
" # highlight-next-line\n",
" state_schema=State,\n",
" checkpointer=checkpointer,\n",
")"
]
},
{
"cell_type": "code",
"execution_count": 15,
"id": "8eccaaca-5d9c-4faf-b997-d4b8e84b59ac",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Update from node: pre_model_hook\n",
"================================\u001b[1m System Message \u001b[0m================================\n",
"\n",
"Summary of the conversation so far: The user asked about the current weather in New York City. In response, the assistant provided information that it might be cloudy, with a chance of rain, and temperatures reaching up to 80 degrees.\n",
"================================\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, often referred to as NYC, is known for its:\n",
"\n",
"1. **Landmarks and Iconic Sites**:\n",
" - **Statue of Liberty**: A symbol of freedom and democracy.\n",
" - **Central Park**: A vast green oasis in the middle of the city.\n",
" - **Empire State Building**: Once the tallest building in the world, offering stunning views of the city.\n",
" - **Times Square**: Known for its bright lights and bustling atmosphere.\n",
"\n",
"2. **Cultural Institutions**:\n",
" - **Broadway**: Renowned for theatrical performances and musicals.\n",
" - **Metropolitan Museum of Art** and **Museum of Modern Art (MoMA)**: World-class art collections.\n",
" - **American Museum of Natural History**: Known for its extensive exhibits ranging from dinosaurs to space exploration.\n",
" \n",
"3. **Diverse Neighborhoods and Cuisine**:\n",
" - NYC is famous for having a melting pot of cultures, reflected in neighborhoods like Chinatown, Little Italy, and Harlem.\n",
" - The city offers a wide range of international cuisines, from street food to high-end dining.\n",
"\n",
"4. **Financial District**:\n",
" - Home to Wall Street, the New York Stock Exchange (NYSE), and other major financial institutions.\n",
"\n",
"5. **Media and Entertainment**:\n",
" - Major hub for television, film, and media, with numerous studios and networks based there.\n",
"\n",
"6. **Fashion**:\n",
" - Often referred to as one of the \"Big Four\" fashion capitals, hosting events like New York Fashion Week.\n",
"\n",
"7. **Sports**:\n",
" - Known for its passionate sports culture with teams like the Yankees (MLB), Mets (MLB), Knicks (NBA), and Rangers (NHL).\n",
"\n",
"These elements, among others, contribute to NYC's reputation as a vibrant and dynamic city.\n",
"================================\u001b[1m Human Message \u001b[0m=================================\n",
"\n",
"where can i find the best bagel?\n",
"\n",
"\n",
"\n",
"Update from node: agent\n",
"==================================\u001b[1m Ai Message \u001b[0m==================================\n",
"\n",
"Finding the best bagel in New York City can be subjective, as there are many beloved spots across the city. However, here are some renowned bagel shops you might want to try:\n",
"\n",
"1. **Ess-a-Bagel**: Known for its chewy and flavorful bagels, located in Midtown and Stuyvesant Town.\n",
"\n",
"2. **Bagel Hole**: A favorite for traditionalists, offering classic and dense bagels, located in Park Slope, Brooklyn.\n",
"\n",
"3. **Russ & Daughters**: A legendary appetizing store on the Lower East Side, famous for their bagels with lox.\n",
"\n",
"4. **Murray’s Bagels**: Located in Greenwich Village, known for their fresh and authentic New York bagels.\n",
"\n",
"5. **Absolute Bagels**: Located on the Upper West Side, they’re known for their fresh, fluffy bagels with a variety of spreads.\n",
"\n",
"6. **Tompkins Square Bagels**: In the East Village, famous for their creative cream cheese options and fresh bagels.\n",
"\n",
"7. **Zabar’s**: A landmark on the Upper West Side known for their classic bagels and smoked fish.\n",
"\n",
"Each of these spots offers a unique take on the classic New York bagel experience, and trying several might be the best way to discover your personal favorite!\n",
"\n",
"\n",
"\n"
]
}
],
"source": [
"config = {\"configurable\": {\"thread_id\": \"1\"}}\n",
"inputs = {\"messages\": [(\"user\", \"What's the weather in NYC?\")]}\n",
"\n",
"result = graph.invoke(inputs, config=config)\n",
"\n",
"inputs = {\"messages\": [(\"user\", \"What's it known for?\")]}\n",
"result = graph.invoke(inputs, config=config)\n",
"\n",
"inputs = {\"messages\": [(\"user\", \"where can i find the best bagel?\")]}\n",
"print_stream(graph.stream(inputs, config=config, stream_mode=\"updates\"))"
]
},
{
"cell_type": "markdown",
"id": "7caaf2f7-281a-4421-bf98-c745d950c56f",
"metadata": {},
"source": [
"You can see that the earlier messages have now been replaced with the summary of the earlier conversation!"
]
}
],
"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.12.3"
}
},
"nbformat": 4,
"nbformat_minor": 5
}
+1
View File
@@ -163,6 +163,7 @@ These guides show how to use the prebuilt ReAct agent:
- [How to add human-in-the-loop processes to a ReAct agent](create-react-agent-hitl.ipynb)
- [How to return structured output from a ReAct agent](create-react-agent-structured-output.ipynb)
- [How to add semantic search for long-term memory to a ReAct agent](memory/semantic-search.ipynb#using-in-create-react-agent)
- [How to manage message history in a ReAct agent](create-react-agent-manage-message-history.ipynb)
Interested in further customizing the ReAct agent? This guide provides an
overview of its underlying implementation to help you customize for your own needs:
+241 -196
View File
@@ -44,7 +44,7 @@
"...\n",
"```\n",
"\n",
"!!! info \"Setup\"",
"!!! info \"Setup\"\n",
"\n",
" You need to run `.setup()` once on your checkpointer to initialize the database before you can use it."
]
@@ -146,20 +146,20 @@
},
{
"cell_type": "markdown",
"id": "e9342c62-dbb4-40f6-9271-7393f1ca48c4",
"id": "f54f9371",
"metadata": {},
"source": [
"## Use sync connection\n",
"## Use async connection\n",
"\n",
"This sets up a synchronous connection to the database. \n",
"For most production server use cases, we recommend using the async connection to the database.\n",
"\n",
"Synchronous connections execute operations in a blocking manner, meaning each operation waits for completion before moving to the next one. The `DB_URI` is the database connection URI, with the protocol used for connecting to a PostgreSQL database, authentication, and host where database is running. The connection_kwargs dictionary defines additional parameters for the database connection."
"Async connections allow non-blocking database operations. This means other parts of your application can continue running while waiting for database operations to complete. It's particularly useful in high-concurrency scenarios or when dealing with I/O-bound operations."
]
},
{
"cell_type": "code",
"execution_count": 2,
"id": "2b9d13b1-9d72-48a0-b63a-adc062c06c29",
"execution_count": null,
"id": "2d8d6c9a",
"metadata": {},
"outputs": [],
"source": [
@@ -168,8 +168,8 @@
},
{
"cell_type": "code",
"execution_count": 3,
"id": "3fe36f67-073a-4fd7-a8f8-da196dd46a0d",
"execution_count": null,
"id": "351b4251",
"metadata": {},
"outputs": [],
"source": [
@@ -179,6 +179,238 @@
"}"
]
},
{
"cell_type": "markdown",
"id": "8e1dd27d",
"metadata": {},
"source": [
"### With a connection pool"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "a89a237a",
"metadata": {},
"outputs": [],
"source": [
"from psycopg_pool import AsyncConnectionPool\n",
"\n",
"async with AsyncConnectionPool(\n",
" # Example configuration\n",
" conninfo=DB_URI,\n",
" max_size=20,\n",
" kwargs=connection_kwargs,\n",
") as pool:\n",
" checkpointer = AsyncPostgresSaver(pool)\n",
"\n",
" # NOTE: you need to call .setup() the first time you're using your checkpointer\n",
" await checkpointer.setup()\n",
"\n",
" graph = create_react_agent(model, tools=tools, checkpointer=checkpointer)\n",
" config = {\"configurable\": {\"thread_id\": \"4\"}}\n",
" res = await graph.ainvoke(\n",
" {\"messages\": [(\"human\", \"what's the weather in nyc\")]}, config\n",
" )\n",
"\n",
" checkpoint = await checkpointer.aget(config)"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "2bb1b8fd",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"{'v': 1,\n",
" 'id': '1ef559b7-5cc9-6460-8003-8655824c0944',\n",
" 'ts': '2024-08-08T15:32:45.640793+00:00',\n",
" 'current_tasks': {},\n",
" 'pending_sends': [],\n",
" 'versions_seen': {'agent': {'tools': '00000000000000000000000000000004.022986cd20ae85c77ea298a383f69ba8',\n",
" 'start:agent': '00000000000000000000000000000002.d6f25946c3108fc12f27abbcf9b4cedc'},\n",
" 'tools': {'branch:agent:should_continue:tools': '00000000000000000000000000000003.065d90dd7f7cd091f0233855210bb2af'},\n",
" '__input__': {},\n",
" '__start__': {'__start__': '00000000000000000000000000000001.0e148ae3debe753278387e84f786e863'}},\n",
" 'channel_versions': {'agent': '00000000000000000000000000000005.065d90dd7f7cd091f0233855210bb2af',\n",
" 'tools': '00000000000000000000000000000005.',\n",
" 'messages': '00000000000000000000000000000005.d869fc7231619df0db74feed624efe41',\n",
" '__start__': '00000000000000000000000000000002.',\n",
" 'start:agent': '00000000000000000000000000000003.',\n",
" 'branch:agent:should_continue:tools': '00000000000000000000000000000004.'},\n",
" 'channel_values': {'agent': 'agent',\n",
" 'messages': [HumanMessage(content=\"what's the weather in nyc\", id='d883b8a0-99de-486d-91a2-bcfa7f25dc05'),\n",
" AIMessage(content='', additional_kwargs={'tool_calls': [{'id': 'call_H6TAYfyd6AnaCrkQGs6Q2fVp', 'function': {'arguments': '{\"city\":\"nyc\"}', 'name': 'get_weather'}, 'type': 'function'}]}, response_metadata={'token_usage': {'completion_tokens': 15, 'prompt_tokens': 58, 'total_tokens': 73}, 'model_name': 'gpt-4o-mini-2024-07-18', 'system_fingerprint': 'fp_48196bc67a', 'finish_reason': 'tool_calls', 'logprobs': None}, id='run-6f542f84-ad73-444c-8ef7-b5ea75a2e09b-0', tool_calls=[{'name': 'get_weather', 'args': {'city': 'nyc'}, 'id': 'call_H6TAYfyd6AnaCrkQGs6Q2fVp', 'type': 'tool_call'}], usage_metadata={'input_tokens': 58, 'output_tokens': 15, 'total_tokens': 73}),\n",
" ToolMessage(content='It might be cloudy in nyc', name='get_weather', id='c0e52254-77a4-4ea9-a2b7-61dd2d65ec68', tool_call_id='call_H6TAYfyd6AnaCrkQGs6Q2fVp'),\n",
" AIMessage(content='The weather in NYC might be cloudy.', response_metadata={'token_usage': {'completion_tokens': 9, 'prompt_tokens': 88, 'total_tokens': 97}, 'model_name': 'gpt-4o-mini-2024-07-18', 'system_fingerprint': 'fp_48196bc67a', 'finish_reason': 'stop', 'logprobs': None}, id='run-977140d4-7582-40c3-b2b6-31b542c430a3-0', usage_metadata={'input_tokens': 88, 'output_tokens': 9, 'total_tokens': 97})]}}"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"checkpoint"
]
},
{
"cell_type": "markdown",
"id": "a68094dc",
"metadata": {},
"source": [
"Note: If you are using this in an ASGI web framework or Starlette (or FastAPI), we'd recommend creating the connection pool within a [**lifespan event.**](https://www.starlette.io/lifespan/), similar to the pseudocode below:\n",
"\n",
"```python\n",
"import contextlib\n",
"\n",
"from starlette.applications import Starlette\n",
"from starlette.requests import Request\n",
"from starlette.responses import Response\n",
"from starlette.routing import Route\n",
"from psycopg_pool import AsyncConnectionPool\n",
"from langgraph.checkpoint.postgres.aio import AsyncPostgresSaver\n",
"\n",
"@contextlib.asynccontextmanager\n",
"async def lifespan(app):\n",
" async with AsyncConnectionPool(\n",
" # Example configuration\n",
" conninfo=DB_URI,\n",
" max_size=20,\n",
" kwargs=connection_kwargs,\n",
" ) as pool:\n",
" checkpointer = AsyncPostgresSaver(pool)\n",
"\n",
" # NOTE: you need to call .setup() the first time you're using your checkpointer\n",
" await checkpointer.setup()\n",
" yield {\"checkpointer\": checkpointer}\n",
"\n",
"\n",
"graph = create_react_agent(model, tools=tools, checkpointer=checkpointer)\n",
"\n",
"async def my_route(request: Request):\n",
" checkpointer = request.state.checkpointer\n",
" agent = graph.copy({\"checkpointer\": checkpointer})\n",
" await agent.ainvoke(request)\n",
" return Response(...)\n",
"\n",
"routes = [\n",
" Route(\"/\", my_route),\n",
"]\n",
"\n",
"app = Starlette(routes=routes, lifespan=lifespan)\n",
"```"
]
},
{
"cell_type": "markdown",
"id": "6e53287e",
"metadata": {},
"source": [
"### With a connection"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "7f0b0f76",
"metadata": {},
"outputs": [],
"source": [
"from psycopg import AsyncConnection\n",
"\n",
"async with await AsyncConnection.connect(DB_URI, **connection_kwargs) as conn:\n",
" checkpointer = AsyncPostgresSaver(conn)\n",
" graph = create_react_agent(model, tools=tools, checkpointer=checkpointer)\n",
" config = {\"configurable\": {\"thread_id\": \"5\"}}\n",
" res = await graph.ainvoke(\n",
" {\"messages\": [(\"human\", \"what's the weather in nyc\")]}, config\n",
" )\n",
" checkpoint_tuple = await checkpointer.aget_tuple(config)"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "6a81c382",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"CheckpointTuple(config={'configurable': {'thread_id': '5', 'checkpoint_ns': '', 'checkpoint_id': '1ef559b7-65b4-60ca-8003-1ef4b620559a'}}, checkpoint={'v': 1, 'id': '1ef559b7-65b4-60ca-8003-1ef4b620559a', 'ts': '2024-08-08T15:32:46.575814+00:00', 'current_tasks': {}, 'pending_sends': [], 'versions_seen': {'agent': {'tools': '00000000000000000000000000000004.022986cd20ae85c77ea298a383f69ba8', 'start:agent': '00000000000000000000000000000002.d6f25946c3108fc12f27abbcf9b4cedc'}, 'tools': {'branch:agent:should_continue:tools': '00000000000000000000000000000003.065d90dd7f7cd091f0233855210bb2af'}, '__input__': {}, '__start__': {'__start__': '00000000000000000000000000000001.0e148ae3debe753278387e84f786e863'}}, 'channel_versions': {'agent': '00000000000000000000000000000005.065d90dd7f7cd091f0233855210bb2af', 'tools': '00000000000000000000000000000005.', 'messages': '00000000000000000000000000000005.1557a6006d58f736d5cb2dd5c5f10111', '__start__': '00000000000000000000000000000002.', 'start:agent': '00000000000000000000000000000003.', 'branch:agent:should_continue:tools': '00000000000000000000000000000004.'}, 'channel_values': {'agent': 'agent', 'messages': [HumanMessage(content=\"what's the weather in nyc\", id='935e7732-b288-49bd-9ec2-1f7610cc38cb'), AIMessage(content='', additional_kwargs={'tool_calls': [{'id': 'call_94KtjtPmsiaj7T8yXvL7Ef31', 'function': {'arguments': '{\"city\":\"nyc\"}', 'name': 'get_weather'}, 'type': 'function'}]}, response_metadata={'token_usage': {'completion_tokens': 15, 'prompt_tokens': 58, 'total_tokens': 73}, 'model_name': 'gpt-4o-mini-2024-07-18', 'system_fingerprint': 'fp_48196bc67a', 'finish_reason': 'tool_calls', 'logprobs': None}, id='run-790c929a-7982-49e7-af67-2cbe4a86373b-0', tool_calls=[{'name': 'get_weather', 'args': {'city': 'nyc'}, 'id': 'call_94KtjtPmsiaj7T8yXvL7Ef31', 'type': 'tool_call'}], usage_metadata={'input_tokens': 58, 'output_tokens': 15, 'total_tokens': 73}), ToolMessage(content='It might be cloudy in nyc', name='get_weather', id='b2dc1073-abc4-4492-8982-434a7e32e445', tool_call_id='call_94KtjtPmsiaj7T8yXvL7Ef31'), AIMessage(content='The weather in NYC might be cloudy.', response_metadata={'token_usage': {'completion_tokens': 9, 'prompt_tokens': 88, 'total_tokens': 97}, 'model_name': 'gpt-4o-mini-2024-07-18', 'system_fingerprint': 'fp_48196bc67a', 'finish_reason': 'stop', 'logprobs': None}, id='run-7e8a7f16-d8e1-457a-89f3-192102396449-0', usage_metadata={'input_tokens': 88, 'output_tokens': 9, 'total_tokens': 97})]}}, metadata={'step': 3, 'source': 'loop', 'writes': {'agent': {'messages': [AIMessage(content='The weather in NYC might be cloudy.', response_metadata={'logprobs': None, 'model_name': 'gpt-4o-mini-2024-07-18', 'token_usage': {'total_tokens': 97, 'prompt_tokens': 88, 'completion_tokens': 9}, 'finish_reason': 'stop', 'system_fingerprint': 'fp_48196bc67a'}, id='run-7e8a7f16-d8e1-457a-89f3-192102396449-0', usage_metadata={'input_tokens': 88, 'output_tokens': 9, 'total_tokens': 97})]}}}, parent_config={'configurable': {'thread_id': '5', 'checkpoint_ns': '', 'checkpoint_id': '1ef559b7-62ae-6128-8002-c04af82bcd41'}}, pending_writes=[])"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"checkpoint_tuple"
]
},
{
"cell_type": "markdown",
"id": "26bd7fbb",
"metadata": {},
"source": [
"### With a connection string"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "d93f68f7",
"metadata": {},
"outputs": [],
"source": [
"async with AsyncPostgresSaver.from_conn_string(DB_URI) as checkpointer:\n",
" graph = create_react_agent(model, tools=tools, checkpointer=checkpointer)\n",
" config = {\"configurable\": {\"thread_id\": \"6\"}}\n",
" res = await graph.ainvoke(\n",
" {\"messages\": [(\"human\", \"what's the weather in nyc\")]}, config\n",
" )\n",
" checkpoint_tuples = [c async for c in checkpointer.alist(config)]"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "717a28ea",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[CheckpointTuple(config={'configurable': {'thread_id': '6', 'checkpoint_ns': '', 'checkpoint_id': '1ef559b7-723c-67de-8003-63bd4eab35af'}}, checkpoint={'v': 1, 'id': '1ef559b7-723c-67de-8003-63bd4eab35af', 'ts': '2024-08-08T15:32:47.890003+00:00', 'current_tasks': {}, 'pending_sends': [], 'versions_seen': {'agent': {'tools': '00000000000000000000000000000004.022986cd20ae85c77ea298a383f69ba8', 'start:agent': '00000000000000000000000000000002.d6f25946c3108fc12f27abbcf9b4cedc'}, 'tools': {'branch:agent:should_continue:tools': '00000000000000000000000000000003.065d90dd7f7cd091f0233855210bb2af'}, '__input__': {}, '__start__': {'__start__': '00000000000000000000000000000001.0e148ae3debe753278387e84f786e863'}}, 'channel_versions': {'agent': '00000000000000000000000000000005.065d90dd7f7cd091f0233855210bb2af', 'tools': '00000000000000000000000000000005.', 'messages': '00000000000000000000000000000005.b6fe2a26011590cfe8fd6a39151a9e92', '__start__': '00000000000000000000000000000002.', 'start:agent': '00000000000000000000000000000003.', 'branch:agent:should_continue:tools': '00000000000000000000000000000004.'}, 'channel_values': {'agent': 'agent', 'messages': [HumanMessage(content=\"what's the weather in nyc\", id='977ddb90-9991-44cb-9f73-361c6dd21396'), AIMessage(content='', additional_kwargs={'tool_calls': [{'id': 'call_QIFCuh4zfP9owpjToycJiZf7', 'function': {'arguments': '{\"city\":\"nyc\"}', 'name': 'get_weather'}, 'type': 'function'}]}, response_metadata={'token_usage': {'completion_tokens': 15, 'prompt_tokens': 58, 'total_tokens': 73}, 'model_name': 'gpt-4o-mini-2024-07-18', 'system_fingerprint': 'fp_48196bc67a', 'finish_reason': 'tool_calls', 'logprobs': None}, id='run-47b10c48-4db3-46d8-b4fa-e021818e01c5-0', tool_calls=[{'name': 'get_weather', 'args': {'city': 'nyc'}, 'id': 'call_QIFCuh4zfP9owpjToycJiZf7', 'type': 'tool_call'}], usage_metadata={'input_tokens': 58, 'output_tokens': 15, 'total_tokens': 73}), ToolMessage(content='It might be cloudy in nyc', name='get_weather', id='798c520f-4f9a-4f6d-a389-da721eb4d4ce', tool_call_id='call_QIFCuh4zfP9owpjToycJiZf7'), AIMessage(content='The weather in NYC might be cloudy.', response_metadata={'token_usage': {'completion_tokens': 9, 'prompt_tokens': 88, 'total_tokens': 97}, 'model_name': 'gpt-4o-mini-2024-07-18', 'system_fingerprint': 'fp_48196bc67a', 'finish_reason': 'stop', 'logprobs': None}, id='run-4a34e05d-8bcf-41ad-adc3-715919fde64c-0', usage_metadata={'input_tokens': 88, 'output_tokens': 9, 'total_tokens': 97})]}}, metadata={'step': 3, 'source': 'loop', 'writes': {'agent': {'messages': [AIMessage(content='The weather in NYC might be cloudy.', response_metadata={'logprobs': None, 'model_name': 'gpt-4o-mini-2024-07-18', 'token_usage': {'total_tokens': 97, 'prompt_tokens': 88, 'completion_tokens': 9}, 'finish_reason': 'stop', 'system_fingerprint': 'fp_48196bc67a'}, id='run-4a34e05d-8bcf-41ad-adc3-715919fde64c-0', usage_metadata={'input_tokens': 88, 'output_tokens': 9, 'total_tokens': 97})]}}}, parent_config={'configurable': {'thread_id': '6', 'checkpoint_ns': '', 'checkpoint_id': '1ef559b7-6bf5-63c6-8002-ed990dbbc96e'}}, pending_writes=None),\n",
" CheckpointTuple(config={'configurable': {'thread_id': '6', 'checkpoint_ns': '', 'checkpoint_id': '1ef559b7-6bf5-63c6-8002-ed990dbbc96e'}}, checkpoint={'v': 1, 'id': '1ef559b7-6bf5-63c6-8002-ed990dbbc96e', 'ts': '2024-08-08T15:32:47.231667+00:00', 'current_tasks': {}, 'pending_sends': [], 'versions_seen': {'agent': {'start:agent': '00000000000000000000000000000002.d6f25946c3108fc12f27abbcf9b4cedc'}, 'tools': {'branch:agent:should_continue:tools': '00000000000000000000000000000003.065d90dd7f7cd091f0233855210bb2af'}, '__input__': {}, '__start__': {'__start__': '00000000000000000000000000000001.0e148ae3debe753278387e84f786e863'}}, 'channel_versions': {'agent': '00000000000000000000000000000004.', 'tools': '00000000000000000000000000000004.022986cd20ae85c77ea298a383f69ba8', 'messages': '00000000000000000000000000000004.c9074f2a41f05486b5efb86353dc75c0', '__start__': '00000000000000000000000000000002.', 'start:agent': '00000000000000000000000000000003.', 'branch:agent:should_continue:tools': '00000000000000000000000000000004.'}, 'channel_values': {'tools': 'tools', 'messages': [HumanMessage(content=\"what's the weather in nyc\", id='977ddb90-9991-44cb-9f73-361c6dd21396'), AIMessage(content='', additional_kwargs={'tool_calls': [{'id': 'call_QIFCuh4zfP9owpjToycJiZf7', 'function': {'arguments': '{\"city\":\"nyc\"}', 'name': 'get_weather'}, 'type': 'function'}]}, response_metadata={'token_usage': {'completion_tokens': 15, 'prompt_tokens': 58, 'total_tokens': 73}, 'model_name': 'gpt-4o-mini-2024-07-18', 'system_fingerprint': 'fp_48196bc67a', 'finish_reason': 'tool_calls', 'logprobs': None}, id='run-47b10c48-4db3-46d8-b4fa-e021818e01c5-0', tool_calls=[{'name': 'get_weather', 'args': {'city': 'nyc'}, 'id': 'call_QIFCuh4zfP9owpjToycJiZf7', 'type': 'tool_call'}], usage_metadata={'input_tokens': 58, 'output_tokens': 15, 'total_tokens': 73}), ToolMessage(content='It might be cloudy in nyc', name='get_weather', id='798c520f-4f9a-4f6d-a389-da721eb4d4ce', tool_call_id='call_QIFCuh4zfP9owpjToycJiZf7')]}}, metadata={'step': 2, 'source': 'loop', 'writes': {'tools': {'messages': [ToolMessage(content='It might be cloudy in nyc', name='get_weather', id='798c520f-4f9a-4f6d-a389-da721eb4d4ce', tool_call_id='call_QIFCuh4zfP9owpjToycJiZf7')]}}}, parent_config={'configurable': {'thread_id': '6', 'checkpoint_ns': '', 'checkpoint_id': '1ef559b7-6be0-6926-8001-1a8ce73baf9e'}}, pending_writes=None),\n",
" CheckpointTuple(config={'configurable': {'thread_id': '6', 'checkpoint_ns': '', 'checkpoint_id': '1ef559b7-6be0-6926-8001-1a8ce73baf9e'}}, checkpoint={'v': 1, 'id': '1ef559b7-6be0-6926-8001-1a8ce73baf9e', 'ts': '2024-08-08T15:32:47.223198+00:00', 'current_tasks': {}, 'pending_sends': [], 'versions_seen': {'agent': {'start:agent': '00000000000000000000000000000002.d6f25946c3108fc12f27abbcf9b4cedc'}, '__input__': {}, '__start__': {'__start__': '00000000000000000000000000000001.0e148ae3debe753278387e84f786e863'}}, 'channel_versions': {'agent': '00000000000000000000000000000003.065d90dd7f7cd091f0233855210bb2af', 'messages': '00000000000000000000000000000003.097b5407d709b297591f1ef5d50c8368', '__start__': '00000000000000000000000000000002.', 'start:agent': '00000000000000000000000000000003.', 'branch:agent:should_continue:tools': '00000000000000000000000000000003.065d90dd7f7cd091f0233855210bb2af'}, 'channel_values': {'agent': 'agent', 'messages': [HumanMessage(content=\"what's the weather in nyc\", id='977ddb90-9991-44cb-9f73-361c6dd21396'), AIMessage(content='', additional_kwargs={'tool_calls': [{'id': 'call_QIFCuh4zfP9owpjToycJiZf7', 'function': {'arguments': '{\"city\":\"nyc\"}', 'name': 'get_weather'}, 'type': 'function'}]}, response_metadata={'token_usage': {'completion_tokens': 15, 'prompt_tokens': 58, 'total_tokens': 73}, 'model_name': 'gpt-4o-mini-2024-07-18', 'system_fingerprint': 'fp_48196bc67a', 'finish_reason': 'tool_calls', 'logprobs': None}, id='run-47b10c48-4db3-46d8-b4fa-e021818e01c5-0', tool_calls=[{'name': 'get_weather', 'args': {'city': 'nyc'}, 'id': 'call_QIFCuh4zfP9owpjToycJiZf7', 'type': 'tool_call'}], usage_metadata={'input_tokens': 58, 'output_tokens': 15, 'total_tokens': 73})], 'branch:agent:should_continue:tools': 'agent'}}, metadata={'step': 1, 'source': 'loop', 'writes': {'agent': {'messages': [AIMessage(content='', additional_kwargs={'tool_calls': [{'id': 'call_QIFCuh4zfP9owpjToycJiZf7', 'type': 'function', 'function': {'name': 'get_weather', 'arguments': '{\"city\":\"nyc\"}'}}]}, response_metadata={'logprobs': None, 'model_name': 'gpt-4o-mini-2024-07-18', 'token_usage': {'total_tokens': 73, 'prompt_tokens': 58, 'completion_tokens': 15}, 'finish_reason': 'tool_calls', 'system_fingerprint': 'fp_48196bc67a'}, id='run-47b10c48-4db3-46d8-b4fa-e021818e01c5-0', tool_calls=[{'name': 'get_weather', 'args': {'city': 'nyc'}, 'id': 'call_QIFCuh4zfP9owpjToycJiZf7', 'type': 'tool_call'}], usage_metadata={'input_tokens': 58, 'output_tokens': 15, 'total_tokens': 73})]}}}, parent_config={'configurable': {'thread_id': '6', 'checkpoint_ns': '', 'checkpoint_id': '1ef559b7-663d-60b4-8000-10a8922bffbf'}}, pending_writes=None),\n",
" CheckpointTuple(config={'configurable': {'thread_id': '6', 'checkpoint_ns': '', 'checkpoint_id': '1ef559b7-663d-60b4-8000-10a8922bffbf'}}, checkpoint={'v': 1, 'id': '1ef559b7-663d-60b4-8000-10a8922bffbf', 'ts': '2024-08-08T15:32:46.631935+00:00', 'current_tasks': {}, 'pending_sends': [], 'versions_seen': {'__input__': {}, '__start__': {'__start__': '00000000000000000000000000000001.0e148ae3debe753278387e84f786e863'}}, 'channel_versions': {'messages': '00000000000000000000000000000002.2a79db8da664e437bdb25ea804457ca7', '__start__': '00000000000000000000000000000002.', 'start:agent': '00000000000000000000000000000002.d6f25946c3108fc12f27abbcf9b4cedc'}, 'channel_values': {'messages': [HumanMessage(content=\"what's the weather in nyc\", id='977ddb90-9991-44cb-9f73-361c6dd21396')], 'start:agent': '__start__'}}, metadata={'step': 0, 'source': 'loop', 'writes': None}, parent_config={'configurable': {'thread_id': '6', 'checkpoint_ns': '', 'checkpoint_id': '1ef559b7-6637-6d4e-bfff-6cecf690c3cb'}}, pending_writes=None),\n",
" CheckpointTuple(config={'configurable': {'thread_id': '6', 'checkpoint_ns': '', 'checkpoint_id': '1ef559b7-6637-6d4e-bfff-6cecf690c3cb'}}, checkpoint={'v': 1, 'id': '1ef559b7-6637-6d4e-bfff-6cecf690c3cb', 'ts': '2024-08-08T15:32:46.629806+00:00', 'current_tasks': {}, 'pending_sends': [], 'versions_seen': {'__input__': {}}, 'channel_versions': {'__start__': '00000000000000000000000000000001.0e148ae3debe753278387e84f786e863'}, 'channel_values': {'__start__': {'messages': [['human', \"what's the weather in nyc\"]]}}}, metadata={'step': -1, 'source': 'input', 'writes': {'messages': [['human', \"what's the weather in nyc\"]]}}, parent_config=None, pending_writes=None)]"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"checkpoint_tuples"
]
},
{
"cell_type": "markdown",
"id": "e9342c62-dbb4-40f6-9271-7393f1ca48c4",
"metadata": {},
"source": [
"## Use sync connection\n",
"\n",
"This sets up a synchronous connection to the database. \n",
"\n",
"Synchronous connections execute operations in a blocking manner, meaning each operation waits for completion before moving to the next one. The `DB_URI` is the database connection URI, with the protocol used for connecting to a PostgreSQL database, authentication, and host where database is running. The connection_kwargs dictionary defines additional parameters for the database connection."
]
},
{
"cell_type": "markdown",
"id": "e39fc712-9e1c-4831-9077-dd07b0c13594",
@@ -387,193 +619,6 @@
"source": [
"checkpoint_tuples"
]
},
{
"cell_type": "markdown",
"id": "c0a47d3e-e588-48fc-a5d4-2145dff17e77",
"metadata": {},
"source": [
"## Use async connection\n",
"\n",
"This sets up an asynchronous connection to the database. \n",
"\n",
"Async connections allow non-blocking database operations. This means other parts of your application can continue running while waiting for database operations to complete. It's particularly useful in high-concurrency scenarios or when dealing with I/O-bound operations."
]
},
{
"cell_type": "markdown",
"id": "ee6b6cf7-d8f7-4777-a48d-93b5855fe681",
"metadata": {},
"source": [
"### With a connection pool"
]
},
{
"cell_type": "code",
"execution_count": 5,
"id": "4faf6087-73cc-4957-9a4f-f3509a32a740",
"metadata": {},
"outputs": [],
"source": [
"from psycopg_pool import AsyncConnectionPool\n",
"\n",
"async with AsyncConnectionPool(\n",
" # Example configuration\n",
" conninfo=DB_URI,\n",
" max_size=20,\n",
" kwargs=connection_kwargs,\n",
") as pool:\n",
" checkpointer = AsyncPostgresSaver(pool)\n",
"\n",
" # NOTE: you need to call .setup() the first time you're using your checkpointer\n",
" await checkpointer.setup()\n",
"\n",
" graph = create_react_agent(model, tools=tools, checkpointer=checkpointer)\n",
" config = {\"configurable\": {\"thread_id\": \"4\"}}\n",
" res = await graph.ainvoke(\n",
" {\"messages\": [(\"human\", \"what's the weather in nyc\")]}, config\n",
" )\n",
"\n",
" checkpoint = await checkpointer.aget(config)"
]
},
{
"cell_type": "code",
"execution_count": 14,
"id": "e0c42044-4de6-4742-8e00-fe295d50c95a",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"{'v': 1,\n",
" 'id': '1ef559b7-5cc9-6460-8003-8655824c0944',\n",
" 'ts': '2024-08-08T15:32:45.640793+00:00',\n",
" 'current_tasks': {},\n",
" 'pending_sends': [],\n",
" 'versions_seen': {'agent': {'tools': '00000000000000000000000000000004.022986cd20ae85c77ea298a383f69ba8',\n",
" 'start:agent': '00000000000000000000000000000002.d6f25946c3108fc12f27abbcf9b4cedc'},\n",
" 'tools': {'branch:agent:should_continue:tools': '00000000000000000000000000000003.065d90dd7f7cd091f0233855210bb2af'},\n",
" '__input__': {},\n",
" '__start__': {'__start__': '00000000000000000000000000000001.0e148ae3debe753278387e84f786e863'}},\n",
" 'channel_versions': {'agent': '00000000000000000000000000000005.065d90dd7f7cd091f0233855210bb2af',\n",
" 'tools': '00000000000000000000000000000005.',\n",
" 'messages': '00000000000000000000000000000005.d869fc7231619df0db74feed624efe41',\n",
" '__start__': '00000000000000000000000000000002.',\n",
" 'start:agent': '00000000000000000000000000000003.',\n",
" 'branch:agent:should_continue:tools': '00000000000000000000000000000004.'},\n",
" 'channel_values': {'agent': 'agent',\n",
" 'messages': [HumanMessage(content=\"what's the weather in nyc\", id='d883b8a0-99de-486d-91a2-bcfa7f25dc05'),\n",
" AIMessage(content='', additional_kwargs={'tool_calls': [{'id': 'call_H6TAYfyd6AnaCrkQGs6Q2fVp', 'function': {'arguments': '{\"city\":\"nyc\"}', 'name': 'get_weather'}, 'type': 'function'}]}, response_metadata={'token_usage': {'completion_tokens': 15, 'prompt_tokens': 58, 'total_tokens': 73}, 'model_name': 'gpt-4o-mini-2024-07-18', 'system_fingerprint': 'fp_48196bc67a', 'finish_reason': 'tool_calls', 'logprobs': None}, id='run-6f542f84-ad73-444c-8ef7-b5ea75a2e09b-0', tool_calls=[{'name': 'get_weather', 'args': {'city': 'nyc'}, 'id': 'call_H6TAYfyd6AnaCrkQGs6Q2fVp', 'type': 'tool_call'}], usage_metadata={'input_tokens': 58, 'output_tokens': 15, 'total_tokens': 73}),\n",
" ToolMessage(content='It might be cloudy in nyc', name='get_weather', id='c0e52254-77a4-4ea9-a2b7-61dd2d65ec68', tool_call_id='call_H6TAYfyd6AnaCrkQGs6Q2fVp'),\n",
" AIMessage(content='The weather in NYC might be cloudy.', response_metadata={'token_usage': {'completion_tokens': 9, 'prompt_tokens': 88, 'total_tokens': 97}, 'model_name': 'gpt-4o-mini-2024-07-18', 'system_fingerprint': 'fp_48196bc67a', 'finish_reason': 'stop', 'logprobs': None}, id='run-977140d4-7582-40c3-b2b6-31b542c430a3-0', usage_metadata={'input_tokens': 88, 'output_tokens': 9, 'total_tokens': 97})]}}"
]
},
"execution_count": 14,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"checkpoint"
]
},
{
"cell_type": "markdown",
"id": "56552584-9eb8-40df-a6a0-44151018b509",
"metadata": {},
"source": [
"### With a connection"
]
},
{
"cell_type": "code",
"execution_count": 15,
"id": "386b78bc-2f73-49ba-a2a4-47bce6fc49b7",
"metadata": {},
"outputs": [],
"source": [
"from psycopg import AsyncConnection\n",
"\n",
"async with await AsyncConnection.connect(DB_URI, **connection_kwargs) as conn:\n",
" checkpointer = AsyncPostgresSaver(conn)\n",
" graph = create_react_agent(model, tools=tools, checkpointer=checkpointer)\n",
" config = {\"configurable\": {\"thread_id\": \"5\"}}\n",
" res = await graph.ainvoke(\n",
" {\"messages\": [(\"human\", \"what's the weather in nyc\")]}, config\n",
" )\n",
" checkpoint_tuple = await checkpointer.aget_tuple(config)"
]
},
{
"cell_type": "code",
"execution_count": 16,
"id": "d1ed1344-c923-4a46-b04e-cc3646737d48",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"CheckpointTuple(config={'configurable': {'thread_id': '5', 'checkpoint_ns': '', 'checkpoint_id': '1ef559b7-65b4-60ca-8003-1ef4b620559a'}}, checkpoint={'v': 1, 'id': '1ef559b7-65b4-60ca-8003-1ef4b620559a', 'ts': '2024-08-08T15:32:46.575814+00:00', 'current_tasks': {}, 'pending_sends': [], 'versions_seen': {'agent': {'tools': '00000000000000000000000000000004.022986cd20ae85c77ea298a383f69ba8', 'start:agent': '00000000000000000000000000000002.d6f25946c3108fc12f27abbcf9b4cedc'}, 'tools': {'branch:agent:should_continue:tools': '00000000000000000000000000000003.065d90dd7f7cd091f0233855210bb2af'}, '__input__': {}, '__start__': {'__start__': '00000000000000000000000000000001.0e148ae3debe753278387e84f786e863'}}, 'channel_versions': {'agent': '00000000000000000000000000000005.065d90dd7f7cd091f0233855210bb2af', 'tools': '00000000000000000000000000000005.', 'messages': '00000000000000000000000000000005.1557a6006d58f736d5cb2dd5c5f10111', '__start__': '00000000000000000000000000000002.', 'start:agent': '00000000000000000000000000000003.', 'branch:agent:should_continue:tools': '00000000000000000000000000000004.'}, 'channel_values': {'agent': 'agent', 'messages': [HumanMessage(content=\"what's the weather in nyc\", id='935e7732-b288-49bd-9ec2-1f7610cc38cb'), AIMessage(content='', additional_kwargs={'tool_calls': [{'id': 'call_94KtjtPmsiaj7T8yXvL7Ef31', 'function': {'arguments': '{\"city\":\"nyc\"}', 'name': 'get_weather'}, 'type': 'function'}]}, response_metadata={'token_usage': {'completion_tokens': 15, 'prompt_tokens': 58, 'total_tokens': 73}, 'model_name': 'gpt-4o-mini-2024-07-18', 'system_fingerprint': 'fp_48196bc67a', 'finish_reason': 'tool_calls', 'logprobs': None}, id='run-790c929a-7982-49e7-af67-2cbe4a86373b-0', tool_calls=[{'name': 'get_weather', 'args': {'city': 'nyc'}, 'id': 'call_94KtjtPmsiaj7T8yXvL7Ef31', 'type': 'tool_call'}], usage_metadata={'input_tokens': 58, 'output_tokens': 15, 'total_tokens': 73}), ToolMessage(content='It might be cloudy in nyc', name='get_weather', id='b2dc1073-abc4-4492-8982-434a7e32e445', tool_call_id='call_94KtjtPmsiaj7T8yXvL7Ef31'), AIMessage(content='The weather in NYC might be cloudy.', response_metadata={'token_usage': {'completion_tokens': 9, 'prompt_tokens': 88, 'total_tokens': 97}, 'model_name': 'gpt-4o-mini-2024-07-18', 'system_fingerprint': 'fp_48196bc67a', 'finish_reason': 'stop', 'logprobs': None}, id='run-7e8a7f16-d8e1-457a-89f3-192102396449-0', usage_metadata={'input_tokens': 88, 'output_tokens': 9, 'total_tokens': 97})]}}, metadata={'step': 3, 'source': 'loop', 'writes': {'agent': {'messages': [AIMessage(content='The weather in NYC might be cloudy.', response_metadata={'logprobs': None, 'model_name': 'gpt-4o-mini-2024-07-18', 'token_usage': {'total_tokens': 97, 'prompt_tokens': 88, 'completion_tokens': 9}, 'finish_reason': 'stop', 'system_fingerprint': 'fp_48196bc67a'}, id='run-7e8a7f16-d8e1-457a-89f3-192102396449-0', usage_metadata={'input_tokens': 88, 'output_tokens': 9, 'total_tokens': 97})]}}}, parent_config={'configurable': {'thread_id': '5', 'checkpoint_ns': '', 'checkpoint_id': '1ef559b7-62ae-6128-8002-c04af82bcd41'}}, pending_writes=[])"
]
},
"execution_count": 16,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"checkpoint_tuple"
]
},
{
"cell_type": "markdown",
"id": "2f7e486a-3e63-41d7-b84b-6743f0a5764c",
"metadata": {},
"source": [
"### With a connection string"
]
},
{
"cell_type": "code",
"execution_count": 17,
"id": "6a39d1ff-ca37-4457-8b52-07d33b59c36e",
"metadata": {},
"outputs": [],
"source": [
"async with AsyncPostgresSaver.from_conn_string(DB_URI) as checkpointer:\n",
" graph = create_react_agent(model, tools=tools, checkpointer=checkpointer)\n",
" config = {\"configurable\": {\"thread_id\": \"6\"}}\n",
" res = await graph.ainvoke(\n",
" {\"messages\": [(\"human\", \"what's the weather in nyc\")]}, config\n",
" )\n",
" checkpoint_tuples = [c async for c in checkpointer.alist(config)]"
]
},
{
"cell_type": "code",
"execution_count": 18,
"id": "2b6d73ca-519e-45f7-90c2-1b8596624505",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[CheckpointTuple(config={'configurable': {'thread_id': '6', 'checkpoint_ns': '', 'checkpoint_id': '1ef559b7-723c-67de-8003-63bd4eab35af'}}, checkpoint={'v': 1, 'id': '1ef559b7-723c-67de-8003-63bd4eab35af', 'ts': '2024-08-08T15:32:47.890003+00:00', 'current_tasks': {}, 'pending_sends': [], 'versions_seen': {'agent': {'tools': '00000000000000000000000000000004.022986cd20ae85c77ea298a383f69ba8', 'start:agent': '00000000000000000000000000000002.d6f25946c3108fc12f27abbcf9b4cedc'}, 'tools': {'branch:agent:should_continue:tools': '00000000000000000000000000000003.065d90dd7f7cd091f0233855210bb2af'}, '__input__': {}, '__start__': {'__start__': '00000000000000000000000000000001.0e148ae3debe753278387e84f786e863'}}, 'channel_versions': {'agent': '00000000000000000000000000000005.065d90dd7f7cd091f0233855210bb2af', 'tools': '00000000000000000000000000000005.', 'messages': '00000000000000000000000000000005.b6fe2a26011590cfe8fd6a39151a9e92', '__start__': '00000000000000000000000000000002.', 'start:agent': '00000000000000000000000000000003.', 'branch:agent:should_continue:tools': '00000000000000000000000000000004.'}, 'channel_values': {'agent': 'agent', 'messages': [HumanMessage(content=\"what's the weather in nyc\", id='977ddb90-9991-44cb-9f73-361c6dd21396'), AIMessage(content='', additional_kwargs={'tool_calls': [{'id': 'call_QIFCuh4zfP9owpjToycJiZf7', 'function': {'arguments': '{\"city\":\"nyc\"}', 'name': 'get_weather'}, 'type': 'function'}]}, response_metadata={'token_usage': {'completion_tokens': 15, 'prompt_tokens': 58, 'total_tokens': 73}, 'model_name': 'gpt-4o-mini-2024-07-18', 'system_fingerprint': 'fp_48196bc67a', 'finish_reason': 'tool_calls', 'logprobs': None}, id='run-47b10c48-4db3-46d8-b4fa-e021818e01c5-0', tool_calls=[{'name': 'get_weather', 'args': {'city': 'nyc'}, 'id': 'call_QIFCuh4zfP9owpjToycJiZf7', 'type': 'tool_call'}], usage_metadata={'input_tokens': 58, 'output_tokens': 15, 'total_tokens': 73}), ToolMessage(content='It might be cloudy in nyc', name='get_weather', id='798c520f-4f9a-4f6d-a389-da721eb4d4ce', tool_call_id='call_QIFCuh4zfP9owpjToycJiZf7'), AIMessage(content='The weather in NYC might be cloudy.', response_metadata={'token_usage': {'completion_tokens': 9, 'prompt_tokens': 88, 'total_tokens': 97}, 'model_name': 'gpt-4o-mini-2024-07-18', 'system_fingerprint': 'fp_48196bc67a', 'finish_reason': 'stop', 'logprobs': None}, id='run-4a34e05d-8bcf-41ad-adc3-715919fde64c-0', usage_metadata={'input_tokens': 88, 'output_tokens': 9, 'total_tokens': 97})]}}, metadata={'step': 3, 'source': 'loop', 'writes': {'agent': {'messages': [AIMessage(content='The weather in NYC might be cloudy.', response_metadata={'logprobs': None, 'model_name': 'gpt-4o-mini-2024-07-18', 'token_usage': {'total_tokens': 97, 'prompt_tokens': 88, 'completion_tokens': 9}, 'finish_reason': 'stop', 'system_fingerprint': 'fp_48196bc67a'}, id='run-4a34e05d-8bcf-41ad-adc3-715919fde64c-0', usage_metadata={'input_tokens': 88, 'output_tokens': 9, 'total_tokens': 97})]}}}, parent_config={'configurable': {'thread_id': '6', 'checkpoint_ns': '', 'checkpoint_id': '1ef559b7-6bf5-63c6-8002-ed990dbbc96e'}}, pending_writes=None),\n",
" CheckpointTuple(config={'configurable': {'thread_id': '6', 'checkpoint_ns': '', 'checkpoint_id': '1ef559b7-6bf5-63c6-8002-ed990dbbc96e'}}, checkpoint={'v': 1, 'id': '1ef559b7-6bf5-63c6-8002-ed990dbbc96e', 'ts': '2024-08-08T15:32:47.231667+00:00', 'current_tasks': {}, 'pending_sends': [], 'versions_seen': {'agent': {'start:agent': '00000000000000000000000000000002.d6f25946c3108fc12f27abbcf9b4cedc'}, 'tools': {'branch:agent:should_continue:tools': '00000000000000000000000000000003.065d90dd7f7cd091f0233855210bb2af'}, '__input__': {}, '__start__': {'__start__': '00000000000000000000000000000001.0e148ae3debe753278387e84f786e863'}}, 'channel_versions': {'agent': '00000000000000000000000000000004.', 'tools': '00000000000000000000000000000004.022986cd20ae85c77ea298a383f69ba8', 'messages': '00000000000000000000000000000004.c9074f2a41f05486b5efb86353dc75c0', '__start__': '00000000000000000000000000000002.', 'start:agent': '00000000000000000000000000000003.', 'branch:agent:should_continue:tools': '00000000000000000000000000000004.'}, 'channel_values': {'tools': 'tools', 'messages': [HumanMessage(content=\"what's the weather in nyc\", id='977ddb90-9991-44cb-9f73-361c6dd21396'), AIMessage(content='', additional_kwargs={'tool_calls': [{'id': 'call_QIFCuh4zfP9owpjToycJiZf7', 'function': {'arguments': '{\"city\":\"nyc\"}', 'name': 'get_weather'}, 'type': 'function'}]}, response_metadata={'token_usage': {'completion_tokens': 15, 'prompt_tokens': 58, 'total_tokens': 73}, 'model_name': 'gpt-4o-mini-2024-07-18', 'system_fingerprint': 'fp_48196bc67a', 'finish_reason': 'tool_calls', 'logprobs': None}, id='run-47b10c48-4db3-46d8-b4fa-e021818e01c5-0', tool_calls=[{'name': 'get_weather', 'args': {'city': 'nyc'}, 'id': 'call_QIFCuh4zfP9owpjToycJiZf7', 'type': 'tool_call'}], usage_metadata={'input_tokens': 58, 'output_tokens': 15, 'total_tokens': 73}), ToolMessage(content='It might be cloudy in nyc', name='get_weather', id='798c520f-4f9a-4f6d-a389-da721eb4d4ce', tool_call_id='call_QIFCuh4zfP9owpjToycJiZf7')]}}, metadata={'step': 2, 'source': 'loop', 'writes': {'tools': {'messages': [ToolMessage(content='It might be cloudy in nyc', name='get_weather', id='798c520f-4f9a-4f6d-a389-da721eb4d4ce', tool_call_id='call_QIFCuh4zfP9owpjToycJiZf7')]}}}, parent_config={'configurable': {'thread_id': '6', 'checkpoint_ns': '', 'checkpoint_id': '1ef559b7-6be0-6926-8001-1a8ce73baf9e'}}, pending_writes=None),\n",
" CheckpointTuple(config={'configurable': {'thread_id': '6', 'checkpoint_ns': '', 'checkpoint_id': '1ef559b7-6be0-6926-8001-1a8ce73baf9e'}}, checkpoint={'v': 1, 'id': '1ef559b7-6be0-6926-8001-1a8ce73baf9e', 'ts': '2024-08-08T15:32:47.223198+00:00', 'current_tasks': {}, 'pending_sends': [], 'versions_seen': {'agent': {'start:agent': '00000000000000000000000000000002.d6f25946c3108fc12f27abbcf9b4cedc'}, '__input__': {}, '__start__': {'__start__': '00000000000000000000000000000001.0e148ae3debe753278387e84f786e863'}}, 'channel_versions': {'agent': '00000000000000000000000000000003.065d90dd7f7cd091f0233855210bb2af', 'messages': '00000000000000000000000000000003.097b5407d709b297591f1ef5d50c8368', '__start__': '00000000000000000000000000000002.', 'start:agent': '00000000000000000000000000000003.', 'branch:agent:should_continue:tools': '00000000000000000000000000000003.065d90dd7f7cd091f0233855210bb2af'}, 'channel_values': {'agent': 'agent', 'messages': [HumanMessage(content=\"what's the weather in nyc\", id='977ddb90-9991-44cb-9f73-361c6dd21396'), AIMessage(content='', additional_kwargs={'tool_calls': [{'id': 'call_QIFCuh4zfP9owpjToycJiZf7', 'function': {'arguments': '{\"city\":\"nyc\"}', 'name': 'get_weather'}, 'type': 'function'}]}, response_metadata={'token_usage': {'completion_tokens': 15, 'prompt_tokens': 58, 'total_tokens': 73}, 'model_name': 'gpt-4o-mini-2024-07-18', 'system_fingerprint': 'fp_48196bc67a', 'finish_reason': 'tool_calls', 'logprobs': None}, id='run-47b10c48-4db3-46d8-b4fa-e021818e01c5-0', tool_calls=[{'name': 'get_weather', 'args': {'city': 'nyc'}, 'id': 'call_QIFCuh4zfP9owpjToycJiZf7', 'type': 'tool_call'}], usage_metadata={'input_tokens': 58, 'output_tokens': 15, 'total_tokens': 73})], 'branch:agent:should_continue:tools': 'agent'}}, metadata={'step': 1, 'source': 'loop', 'writes': {'agent': {'messages': [AIMessage(content='', additional_kwargs={'tool_calls': [{'id': 'call_QIFCuh4zfP9owpjToycJiZf7', 'type': 'function', 'function': {'name': 'get_weather', 'arguments': '{\"city\":\"nyc\"}'}}]}, response_metadata={'logprobs': None, 'model_name': 'gpt-4o-mini-2024-07-18', 'token_usage': {'total_tokens': 73, 'prompt_tokens': 58, 'completion_tokens': 15}, 'finish_reason': 'tool_calls', 'system_fingerprint': 'fp_48196bc67a'}, id='run-47b10c48-4db3-46d8-b4fa-e021818e01c5-0', tool_calls=[{'name': 'get_weather', 'args': {'city': 'nyc'}, 'id': 'call_QIFCuh4zfP9owpjToycJiZf7', 'type': 'tool_call'}], usage_metadata={'input_tokens': 58, 'output_tokens': 15, 'total_tokens': 73})]}}}, parent_config={'configurable': {'thread_id': '6', 'checkpoint_ns': '', 'checkpoint_id': '1ef559b7-663d-60b4-8000-10a8922bffbf'}}, pending_writes=None),\n",
" CheckpointTuple(config={'configurable': {'thread_id': '6', 'checkpoint_ns': '', 'checkpoint_id': '1ef559b7-663d-60b4-8000-10a8922bffbf'}}, checkpoint={'v': 1, 'id': '1ef559b7-663d-60b4-8000-10a8922bffbf', 'ts': '2024-08-08T15:32:46.631935+00:00', 'current_tasks': {}, 'pending_sends': [], 'versions_seen': {'__input__': {}, '__start__': {'__start__': '00000000000000000000000000000001.0e148ae3debe753278387e84f786e863'}}, 'channel_versions': {'messages': '00000000000000000000000000000002.2a79db8da664e437bdb25ea804457ca7', '__start__': '00000000000000000000000000000002.', 'start:agent': '00000000000000000000000000000002.d6f25946c3108fc12f27abbcf9b4cedc'}, 'channel_values': {'messages': [HumanMessage(content=\"what's the weather in nyc\", id='977ddb90-9991-44cb-9f73-361c6dd21396')], 'start:agent': '__start__'}}, metadata={'step': 0, 'source': 'loop', 'writes': None}, parent_config={'configurable': {'thread_id': '6', 'checkpoint_ns': '', 'checkpoint_id': '1ef559b7-6637-6d4e-bfff-6cecf690c3cb'}}, pending_writes=None),\n",
" CheckpointTuple(config={'configurable': {'thread_id': '6', 'checkpoint_ns': '', 'checkpoint_id': '1ef559b7-6637-6d4e-bfff-6cecf690c3cb'}}, checkpoint={'v': 1, 'id': '1ef559b7-6637-6d4e-bfff-6cecf690c3cb', 'ts': '2024-08-08T15:32:46.629806+00:00', 'current_tasks': {}, 'pending_sends': [], 'versions_seen': {'__input__': {}}, 'channel_versions': {'__start__': '00000000000000000000000000000001.0e148ae3debe753278387e84f786e863'}, 'channel_values': {'__start__': {'messages': [['human', \"what's the weather in nyc\"]]}}}, metadata={'step': -1, 'source': 'input', 'writes': {'messages': [['human', \"what's the weather in nyc\"]]}}, parent_config=None, pending_writes=None)]"
]
},
"execution_count": 18,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"checkpoint_tuples"
]
}
],
"metadata": {
+1
View File
@@ -185,6 +185,7 @@ nav:
- how-tos/create-react-agent-system-prompt.ipynb
- how-tos/create-react-agent-hitl.ipynb
- how-tos/create-react-agent-structured-output.ipynb
- how-tos/create-react-agent-manage-message-history.ipynb
- how-tos/react-agent-from-scratch.ipynb
- how-tos/react-agent-from-scratch-functional.ipynb
- LangGraph Platform:
+240 -695
View File
File diff suppressed because it is too large. Load diff
+2 -1
View File
@@ -50,7 +50,8 @@ langchain-community = "^0.3.0"
langchain-experimental = "^0.3.2"
langchain-mistralai = "^0.2.6"
langgraph-checkpoint-mongodb = "^0.1.0"
langsmith = "^0.2.0"
langmem = "^0.0.19"
langsmith = "^0.3.0"
chromadb = "^0.5.5"
gpt4all = "^2.8.2"
scikit-learn = "^1.5.2"
+1 -1
View File
@@ -1,6 +1,6 @@
[tool.poetry]
name = "langgraph-prebuilt"
version = "0.1.7"
version = "0.1.8"
description = "Library with high-level APIs for creating and executing LangGraph agents and tools."
authors = []
license = "MIT"