{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "4a1aae78-88a6-4133-b905-7e46c8e3772f",
   "metadata": {},
   "source": [
    "# Quick Start\n",
    "\n",
    "In this comprehensive quick start, we will build a support chatbot in LangGraph that can:\n",
    "\n",
    "- Answer common questions by searching the web\n",
    "- Maintain conversation state across calls\n",
    "- Route complex queries to a human for review\n",
    "- Use custom state to control its behavior\n",
    "- Rewind and explore alternative conversation paths\n",
    "\n",
    "We'll start with a basic chatbot and progressively add more sophisticated capabilities, introducing key LangGraph concepts along the way.\n",
    "\n",
    "## Setup\n",
    "\n",
    "First, install the required packages:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "6f11d631-8679-4f28-822f-cdf1f2ddc21c",
   "metadata": {},
   "outputs": [],
   "source": [
    "%%capture --no-stderr\n",
    "%pip install -U langgraph langsmith\n",
    "\n",
    "# Used for this tutorial; not a requirement for LangGraph\n",
    "%pip install -U langchain_anthropic"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a6d1e870-1bc0-4d44-86c0-96681ccf6113",
   "metadata": {},
   "source": [
    "Next, set your API keys:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "705d4020-6ee8-44cc-b1a5-8c34e7172fc7",
   "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(\"ANTHROPIC_API_KEY\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a98c72cf-33f9-4a37-9634-6c93a7c28815",
   "metadata": {},
   "source": [
    "(Encouraged) [LangSmith](https://smith.langchain.com/) makes it a lot easier to see what's going on \"under the hood.\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "13cba9af-0572-41df-92f8-d6f56d5b5322",
   "metadata": {},
   "outputs": [],
   "source": [
    "_set_env(\"LANGSMITH_API_KEY\")\n",
    "os.environ[\"LANGCHAIN_TRACING_V2\"] = \"true\"\n",
    "os.environ[\"LANGCHAIN_PROJECT\"] = \"LangGraph Tutorial\""
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "9c374e41-f9b7-439e-a520-6d8c853c5220",
   "metadata": {},
   "source": [
    "## Part 1: Build a Basic Chatbot\n",
    "\n",
    "We'll first create a simple chatbot using LangGraph. This chatbot will respond directly to user messages. Though simple, it will illustrate the core concepts of building with LangGraph. By the end of this section, you will have a built rudimentary chatbot.\n",
    "\n",
    "Start by creating a `StateGraph`. A `StateGraph` object defines the structure of our chatbot as a \"state machine\". We'll add `nodes` to represent the llm and functions our chatbot can call and `edges` to specify how the bot should transition between these functions."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "e58df974-7579-4f25-9d91-66389b94eba2",
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import Annotated\n",
    "\n",
    "from typing_extensions import TypedDict\n",
    "\n",
    "from langgraph.graph import StateGraph, START, END\n",
    "from langgraph.graph.message import add_messages\n",
    "\n",
    "\n",
    "class State(TypedDict):\n",
    "    # Messages have the type \"list\". The `add_messages` function\n",
    "    # in the annotation defines how this state key should be updated\n",
    "    # (in this case, it appends messages to the list, rather than overwriting them)\n",
    "    messages: Annotated[list, add_messages]\n",
    "\n",
    "\n",
    "graph_builder = StateGraph(State)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "31c755cd-8994-4867-bdff-96a55d7beae7",
   "metadata": {},
   "source": [
    "<div class=\"admonition tip\">\n",
    "    <p class=\"admonition-title\">Note</p>\n",
    "    <p>\n",
    "    The first thing you do when you define a graph is define the <code>State</code> of the graph. The <code>State</code> consists of the schema of the graph as well as reducer functions which specify how to apply updates to the state. In our example <code>State</code> is a <code>TypedDict</code> with a single key: <code>messages</code>. The <code>messages</code> key is annotated with the <a href=\"https://langchain-ai.github.io/langgraph/reference/graphs/?h=add+messages#add_messages\"><code>add_messages</code></a> reducer function, which tells LangGraph to append new messages to the existing list, rather than overwriting it. State keys without an annotation will be overwritten by each update, storing the most recent value. Check out <a href=\"https://langchain-ai.github.io/langgraph/reference/graphs/?h=add+messages#add_messages\">this conceptual guide</a> to learn more about state, reducers and other low-level concepts.\n",
    "    </p>\n",
    "</div>"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4137feed-746e-4c72-a34a-f7a699ad5dcf",
   "metadata": {},
   "source": [
    "So now our graph knows two things:\n",
    "\n",
    "1. Every `node` we define will receive the current `State` as input and return a value that updates that state.\n",
    "2. `messages` will be _appended_ to the current list, rather than directly overwritten. This is communicated via the prebuilt [`add_messages`](https://langchain-ai.github.io/langgraph/reference/graphs/?h=add+messages#add_messages) function in the `Annotated` syntax.\n",
    "\n",
    "Next, add a \"`chatbot`\" node. Nodes represent units of work. They are typically regular python functions."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "bc8c9137-8261-42ea-8e83-3590981d23e2",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain_anthropic import ChatAnthropic\n",
    "\n",
    "llm = ChatAnthropic(model=\"claude-3-haiku-20240307\")\n",
    "\n",
    "\n",
    "def chatbot(state: State):\n",
    "    return {\"messages\": [llm.invoke(state[\"messages\"])]}\n",
    "\n",
    "\n",
    "# The first argument is the unique node name\n",
    "# The second argument is the function or object that will be called whenever\n",
    "# the node is used.\n",
    "graph_builder.add_node(\"chatbot\", chatbot)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b6c1dcd9-fb86-4649-81b4-ff6ce20a2e46",
   "metadata": {},
   "source": [
    "**Notice** how the `chatbot` node function takes the current `State` as input and returns a dictionary containing an updated `messages` list under the key \"messages\". This is the basic pattern for all LangGraph node functions.\n",
    "\n",
    "The `add_messages` function in our `State` will append the llm's response messages to whatever messages are already in the state.\n",
    "\n",
    "Next, add an `entry` point. This tells our graph **where to start its work** each time we run it."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "e331e10d-ebcf-4144-9bd3-999b4d656dd3",
   "metadata": {},
   "outputs": [],
   "source": [
    "graph_builder.add_edge(START, \"chatbot\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0499c318-d1e6-46fa-a652-8f9e65313355",
   "metadata": {},
   "source": [
    "Similarly, set a `finish` point. This instructs the graph **\"any time this node is run, you can exit.\"**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "075f0929-3591-4852-b2d3-eaadde40662d",
   "metadata": {},
   "outputs": [],
   "source": [
    "graph_builder.add_edge(\"chatbot\", END)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "65a9b88c-2c53-4d95-8eb1-d544a8946f65",
   "metadata": {},
   "source": [
    "Finally, we'll want to be able to run our graph. To do so, call \"`compile()`\" on the graph builder. This creates a \"`CompiledGraph`\" we can use invoke on our state."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "0bb67a01-cf5c-4625-8c07-6e8c0af50fca",
   "metadata": {},
   "outputs": [],
   "source": [
    "graph = graph_builder.compile()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0c39407b-d6f6-48a4-b1f6-31fc7f88b275",
   "metadata": {},
   "source": [
    "You can visualize the graph using the `get_graph` method and one of the \"draw\" methods, like `draw_ascii` or `draw_png`. The `draw` methods each require additional dependencies."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "32e4f36e-72ce-4ade-bd7e-94880e0d456b",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/jpeg": "[encoded data, 7356 characters]",
      "text/plain": [
       "<IPython.core.display.Image object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "from IPython.display import Image, display\n",
    "\n",
    "try:\n",
    "    display(Image(graph.get_graph().draw_mermaid_png()))\n",
    "except Exception:\n",
    "    # This requires some extra dependencies and is optional\n",
    "    pass"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a98097a3-a126-4081-b21e-697ec1185fff",
   "metadata": {},
   "source": [
    "Now let's run the chatbot! \n",
    "\n",
    "**Tip:** You can exit the chat loop at any time by typing \"quit\", \"exit\", or \"q\"."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "7afb4c9a-7404-4e92-9945-36f372015f08",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "User:  what's langgraph all about?\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Assistant: LangGraph is a new open-source deep learning framework that focuses on enabling efficient training and deployment of large language models. Some key things to know about LangGraph:\n",
      "\n",
      "1. Efficient Training: LangGraph is designed to accelerate the training of large language models by leveraging advanced optimization techniques and parallelization strategies.\n",
      "\n",
      "2. Modular Architecture: LangGraph has a modular architecture that allows for easy customization and extension of language models, making it flexible for a variety of NLP tasks.\n",
      "\n",
      "3. Hardware Acceleration: The framework is optimized for both CPU and GPU hardware, allowing for efficient model deployment on a wide range of devices.\n",
      "\n",
      "4. Scalability: LangGraph is designed to handle large-scale language models with billions of parameters, enabling the development of state-of-the-art NLP applications.\n",
      "\n",
      "5. Open-Source: LangGraph is an open-source project, allowing developers and researchers to collaborate, contribute, and build upon the framework.\n",
      "\n",
      "6. Performance: The goal of LangGraph is to provide superior performance and efficiency compared to existing deep learning frameworks, particularly for training and deploying large language models.\n",
      "\n",
      "Overall, LangGraph is a promising new deep learning framework that aims to address the challenges of building and deploying advanced natural language processing models at scale. It is an active area of research and development, with the potential to drive further advancements in the field of language AI.\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "User:  hm that doesn't seem right...\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Assistant: I'm sorry, I don't have enough context to determine what doesn't seem right. Could you please provide more details about what you're referring to? That would help me better understand and respond appropriately.\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "User:  q\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Goodbye!\n"
     ]
    }
   ],
   "source": [
    "while True:\n",
    "    user_input = input(\"User: \")\n",
    "    if user_input.lower() in [\"quit\", \"exit\", \"q\"]:\n",
    "        print(\"Goodbye!\")\n",
    "        break\n",
    "    for event in graph.stream({\"messages\": (\"user\", user_input)}):\n",
    "        for value in event.values():\n",
    "            print(\"Assistant:\", value[\"messages\"][-1].content)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "98e1cdb5-869a-41ea-9dab-e28cfc524499",
   "metadata": {},
   "source": [
    "**Congratulations!** You've built your first chatbot using LangGraph. This bot can engage in basic conversation by taking user input and generating responses using an LLM. You can inspect a [LangSmith Trace](https://smith.langchain.com/public/29ab0177-1177-4d25-9341-17ae7d94e0e0/r) for the call above at the provided link.\n",
    "\n",
    "However, you may have noticed that the bot's knowledge is limited to what's in its training data. In the next part, we'll add a web search tool to expand the bot's knowledge and make it more capable.\n",
    "\n",
    "Below is the full code for this section for your reference:\n",
    "\n",
    "<details>\n",
    "<summary>Full Code</summary>\n",
    "    <pre>\n",
    "        \n",
    "```python\n",
    "from typing import Annotated\n",
    "\n",
    "from langchain_anthropic import ChatAnthropic\n",
    "from typing_extensions import TypedDict\n",
    "\n",
    "from langgraph.graph import StateGraph\n",
    "from langgraph.graph.message import add_messages\n",
    "\n",
    "\n",
    "class State(TypedDict):\n",
    "    messages: Annotated[list, add_messages]\n",
    "\n",
    "\n",
    "graph_builder = StateGraph(State)\n",
    "\n",
    "\n",
    "llm = ChatAnthropic(model=\"claude-3-haiku-20240307\")\n",
    "\n",
    "\n",
    "def chatbot(state: State):\n",
    "    return {\"messages\": [llm.invoke(state[\"messages\"])]}\n",
    "\n",
    "\n",
    "# The first argument is the unique node name\n",
    "# The second argument is the function or object that will be called whenever\n",
    "# the node is used.\n",
    "graph_builder.add_node(\"chatbot\", chatbot)\n",
    "graph_builder.set_entry_point(\"chatbot\")\n",
    "graph_builder.set_finish_point(\"chatbot\")\n",
    "graph = graph_builder.compile()\n",
    "```\n",
    "\n",
    "</pre>\n",
    "</details>"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f22c5d4a-3134-413c-81fe-dd9752fbeb66",
   "metadata": {},
   "source": [
    "## Part 2: Enhancing the Chatbot with Tools\n",
    "\n",
    "To handle queries our chatbot can't answer \"from memory\", we'll integrate a web search tool. Our bot can use this tool to find relevant information and provide better responses.\n",
    "\n",
    "#### Requirements\n",
    "\n",
    "Before we start, make sure you have the necessary packages installed and API keys set up:\n",
    "\n",
    "First, install the requirements to use the [Tavily Search Engine](https://python.langchain.com/v0.2/docs/integrations/tools/tavily_search/), and set your [TAVILY_API_KEY](https://tavily.com/)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "7451151f-41fc-4af0-9359-024ae51b7225",
   "metadata": {},
   "outputs": [],
   "source": [
    "%%capture --no-stderr\n",
    "%pip install -U tavily-python\n",
    "%pip install -U langchain_community"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "0c52923c-5665-4f8c-a1ba-9799e369c49e",
   "metadata": {},
   "outputs": [],
   "source": [
    "_set_env(\"TAVILY_API_KEY\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "591ce9ba-c431-4165-b815-25c944ef7cdb",
   "metadata": {},
   "source": [
    "Next, define the tool:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "35c8978e-c07d-4dd0-a97b-0ce3a723eea5",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[{'url': 'https://medium.com/@cplog/introduction-to-langgraph-a-beginners-guide-14f9be027141',\n",
       "  'content': 'Nodes: Nodes are the building blocks of your LangGraph. Each node represents a function or a computation step. You define nodes to perform specific tasks, such as processing input, making ...'},\n",
       " {'url': 'https://js.langchain.com/docs/langgraph',\n",
       "  'content': \"Assuming you have done the above Quick Start, you can build off it like:\\nHere, we manually define the first tool call that we will make.\\nNotice that it does that same thing as agent would have done (adds the agentOutcome key).\\n LangGraph\\n🦜🕸️LangGraph.js\\n⚡ Building language agents as graphs ⚡\\nOverview\\u200b\\nLangGraph is a library for building stateful, multi-actor applications with LLMs, built on top of (and intended to be used with) LangChain.js.\\n Therefore, we will use an object with one key (messages) with the value as an object: { value: Function, default?: () => any }\\nThe default key must be a factory that returns the default value for that attribute.\\n Streaming Node Output\\u200b\\nOne of the benefits of using LangGraph is that it is easy to stream output as it's produced by each node.\\n What this means is that only one of the downstream edges will be taken, and which one that is depends on the results of the start node.\\n\"}]"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from langchain_community.tools.tavily_search import TavilySearchResults\n",
    "\n",
    "tool = TavilySearchResults(max_results=2)\n",
    "tools = [tool]\n",
    "tool.invoke(\"What's a 'node' in LangGraph?\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7f503f02-d23d-42e8-9b5d-eb2681b242f4",
   "metadata": {},
   "source": [
    "The results are page summaries our chat bot can use to answer questions.\n",
    "\n",
    "\n",
    "Next, we'll start defining our graph. The following is all **the same as in Part 1**, except we have added `bind_tools` on our LLM. This lets the LLM know the correct JSON format to use if it wants to use our search engine."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "dc5af88b-47d2-43bf-9a2c-6c07506b1732",
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import Annotated\n",
    "\n",
    "from langchain_anthropic import ChatAnthropic\n",
    "from typing_extensions import TypedDict\n",
    "\n",
    "from langgraph.graph import StateGraph, START\n",
    "from langgraph.graph.message import add_messages\n",
    "\n",
    "\n",
    "class State(TypedDict):\n",
    "    messages: Annotated[list, add_messages]\n",
    "\n",
    "\n",
    "graph_builder = StateGraph(State)\n",
    "\n",
    "\n",
    "llm = ChatAnthropic(model=\"claude-3-haiku-20240307\")\n",
    "# Modification: tell the LLM which tools it can call\n",
    "llm_with_tools = llm.bind_tools(tools)\n",
    "\n",
    "\n",
    "def chatbot(state: State):\n",
    "    return {\"messages\": [llm_with_tools.invoke(state[\"messages\"])]}\n",
    "\n",
    "\n",
    "graph_builder.add_node(\"chatbot\", chatbot)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d1e84cfc-b1b2-48e3-8550-152a408c3926",
   "metadata": {},
   "source": [
    "Next we need to create a function to actually run the tools if they are called. We'll do this by adding the tools to a new node.\n",
    "\n",
    "Below, implement a `BasicToolNode` that checks the most recent message in the state and calls tools if the message contains `tool_calls`. It relies on the LLM's `tool_calling` support, which is available in Anthropic, OpenAI, Google Gemini, and a number of other LLM providers.\n",
    "\n",
    "We will later replace this with LangGraph's prebuilt [ToolNode](https://langchain-ai.github.io/langgraph/reference/prebuilt/#toolnode) to speed things up, but building it ourselves first is instructive."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "12f1fc14-cd91-4cd4-9f2e-1d007f8beafc",
   "metadata": {},
   "outputs": [],
   "source": [
    "import json\n",
    "\n",
    "from langchain_core.messages import ToolMessage\n",
    "\n",
    "\n",
    "class BasicToolNode:\n",
    "    \"\"\"A node that runs the tools requested in the last AIMessage.\"\"\"\n",
    "\n",
    "    def __init__(self, tools: list) -> None:\n",
    "        self.tools_by_name = {tool.name: tool for tool in tools}\n",
    "\n",
    "    def __call__(self, inputs: dict):\n",
    "        if messages := inputs.get(\"messages\", []):\n",
    "            message = messages[-1]\n",
    "        else:\n",
    "            raise ValueError(\"No message found in input\")\n",
    "        outputs = []\n",
    "        for tool_call in message.tool_calls:\n",
    "            tool_result = self.tools_by_name[tool_call[\"name\"]].invoke(\n",
    "                tool_call[\"args\"]\n",
    "            )\n",
    "            outputs.append(\n",
    "                ToolMessage(\n",
    "                    content=json.dumps(tool_result),\n",
    "                    name=tool_call[\"name\"],\n",
    "                    tool_call_id=tool_call[\"id\"],\n",
    "                )\n",
    "            )\n",
    "        return {\"messages\": outputs}\n",
    "\n",
    "\n",
    "tool_node = BasicToolNode(tools=[tool])\n",
    "graph_builder.add_node(\"tools\", tool_node)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b049afc4-7757-40ba-8e00-589d378e816d",
   "metadata": {},
   "source": [
    "With the tool node added, we can define the `conditional_edges`. \n",
    "\n",
    "Recall that **edges** route the control flow from one node to the next. **Conditional edges** usually contain \"if\" statements to route to different nodes depending on the current graph state. These functions receive the current graph `state` and return a string or list of strings indicating which node(s) to call next.\n",
    "\n",
    "Below, call define a router function called `route_tools`, that checks for tool_calls in the chatbot's output. Provide this function to the graph by calling `add_conditional_edges`, which tells the graph that whenever the `chatbot` node completes to check this function to see where to go next. \n",
    "\n",
    "The condition will route to `tools` if tool calls are present and \"`__end__`\" if not.\n",
    "\n",
    "Later, we will replace this with the prebuilt [tools_condition](https://langchain-ai.github.io/langgraph/reference/prebuilt/#tools_condition) to be more concise, but implementing it ourselves first makes things more clear. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "d662df94-66ac-4c6c-92f0-4c93620f1c74",
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import Literal\n",
    "\n",
    "\n",
    "def route_tools(\n",
    "    state: State,\n",
    ") -> Literal[\"tools\", \"__end__\"]:\n",
    "    \"\"\"\n",
    "    Use in the conditional_edge to route to the ToolNode if the last message\n",
    "    has tool calls. Otherwise, route to the end.\n",
    "    \"\"\"\n",
    "    if isinstance(state, list):\n",
    "        ai_message = state[-1]\n",
    "    elif messages := state.get(\"messages\", []):\n",
    "        ai_message = messages[-1]\n",
    "    else:\n",
    "        raise ValueError(f\"No messages found in input state to tool_edge: {state}\")\n",
    "    if hasattr(ai_message, \"tool_calls\") and len(ai_message.tool_calls) > 0:\n",
    "        return \"tools\"\n",
    "    return \"__end__\"\n",
    "\n",
    "\n",
    "# The `tools_condition` function returns \"tools\" if the chatbot asks to use a tool, and \"__end__\" if\n",
    "# it is fine directly responding. This conditional routing defines the main agent loop.\n",
    "graph_builder.add_conditional_edges(\n",
    "    \"chatbot\",\n",
    "    route_tools,\n",
    "    # The following dictionary lets you tell the graph to interpret the condition's outputs as a specific node\n",
    "    # It defaults to the identity function, but if you\n",
    "    # want to use a node named something else apart from \"tools\",\n",
    "    # You can update the value of the dictionary to something else\n",
    "    # e.g., \"tools\": \"my_tools\"\n",
    "    {\"tools\": \"tools\", \"__end__\": \"__end__\"},\n",
    ")\n",
    "# Any time a tool is called, we return to the chatbot to decide the next step\n",
    "graph_builder.add_edge(\"tools\", \"chatbot\")\n",
    "graph_builder.add_edge(START, \"chatbot\")\n",
    "graph = graph_builder.compile()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a2aa67c2-dd1b-4bf2-8c64-eea44296d15f",
   "metadata": {},
   "source": [
    "**Notice** that conditional edges start from a single node. This tells the graph \"any time the '`chatbot`' node runs, either go to 'tools' if it calls a tool, or end the loop if it responds directly. \n",
    "\n",
    "Like the prebuilt `tools_condition`, our function returns the \"`__end__`\" string if no tool calls are made. When the graph transitions to `__end__`, it has no more tasks to complete and ceases execution. Because the condition can return `__end__`, we don't need to explicitly set a `finish_point` this time. Our graph already has a way to finish!\n",
    "\n",
    "Let's visualize the graph we've built. The following function has some additional dependencies to run that are unimportant for this tutorial."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "8b49509c-9d97-457c-a76a-c495fb30ccbc",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/jpeg": "[encoded data, 10844 characters]",
      "text/plain": [
       "<IPython.core.display.Image object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "from IPython.display import Image, display\n",
    "\n",
    "try:\n",
    "    display(Image(graph.get_graph().draw_mermaid_png()))\n",
    "except Exception:\n",
    "    # This requires some extra dependencies and is optional\n",
    "    pass"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c59593ef-5073-4279-931e-828dae971f23",
   "metadata": {},
   "source": [
    "Now we can ask the bot questions outside its training data."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "051dc374-67cc-4371-9dd1-221e07593148",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "User:  what's langgraph all about?\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Assistant: [{'id': 'toolu_01L1TABSBXsHPsebWiMPNqf1', 'input': {'query': 'langgraph'}, 'name': 'tavily_search_results_json', 'type': 'tool_use'}]\n",
      "Assistant: [{\"url\": \"https://langchain-ai.github.io/langgraph/\", \"content\": \"LangGraph is framework agnostic (each node is a regular python function). It extends the core Runnable API (shared interface for streaming, async, and batch calls) to make it easy to: Seamless state management across multiple turns of conversation or tool usage. The ability to flexibly route between nodes based on dynamic criteria.\"}, {\"url\": \"https://blog.langchain.dev/langgraph-multi-agent-workflows/\", \"content\": \"As a part of the launch, we highlighted two simple runtimes: one that is the equivalent of the AgentExecutor in langchain, and a second that was a version of that aimed at message passing and chat models.\\n It's important to note that these three examples are only a few of the possible examples we could highlight - there are almost assuredly other examples out there and we look forward to seeing what the community comes up with!\\n LangGraph: Multi-Agent Workflows\\nLinks\\nLast week we highlighted LangGraph - a new package (available in both Python and JS) to better enable creation of LLM workflows containing cycles, which are a critical component of most agent runtimes. \\\"\\nAnother key difference between Autogen and LangGraph is that LangGraph is fully integrated into the LangChain ecosystem, meaning you take fully advantage of all the LangChain integrations and LangSmith observability.\\n As part of this launch, we're also excited to highlight a few applications built on top of LangGraph that utilize the concept of multiple agents.\\n\"}]\n",
      "Assistant: Based on the search results, LangGraph is a framework-agnostic Python and JavaScript library that extends the core Runnable API from the LangChain project to enable the creation of more complex workflows involving multiple agents or components. Some key things about LangGraph:\n",
      "\n",
      "- It makes it easier to manage state across multiple turns of conversation or tool usage, and to dynamically route between different nodes/components based on criteria.\n",
      "\n",
      "- It is integrated with the LangChain ecosystem, allowing you to take advantage of LangChain integrations and observability features.\n",
      "\n",
      "- It enables the creation of multi-agent workflows, where different components or agents can be chained together in more flexible and complex ways than the standard LangChain AgentExecutor.\n",
      "\n",
      "- The core idea is to provide a more powerful and flexible framework for building LLM-powered applications and workflows, beyond what is possible with just the core LangChain tools.\n",
      "\n",
      "Overall, LangGraph seems to be a useful addition to the LangChain toolkit, focused on enabling more advanced, multi-agent style applications and workflows powered by large language models.\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "User:  neat!\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Assistant: I'm afraid I don't have enough context to provide a substantive response to \"neat!\". As an AI assistant, I'm designed to have conversations and provide information to users, but I need more details or a specific question from you in order to give a helpful reply. Could you please rephrase your request or provide some additional context? I'd be happy to assist further once I understand what you're looking for.\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "User:  what?\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Assistant: I'm afraid I don't have enough context to provide a meaningful response to \"what?\". Could you please rephrase your request or provide more details about what you are asking? I'd be happy to try to assist you further once I have a clearer understanding of your query.\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "User:  q\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Goodbye!\n"
     ]
    }
   ],
   "source": [
    "from langchain_core.messages import BaseMessage\n",
    "\n",
    "while True:\n",
    "    user_input = input(\"User: \")\n",
    "    if user_input.lower() in [\"quit\", \"exit\", \"q\"]:\n",
    "        print(\"Goodbye!\")\n",
    "        break\n",
    "    for event in graph.stream({\"messages\": [(\"user\", user_input)]}):\n",
    "        for value in event.values():\n",
    "            if isinstance(value[\"messages\"][-1], BaseMessage):\n",
    "                print(\"Assistant:\", value[\"messages\"][-1].content)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "89da9e85-2e5d-49c2-8cbd-572cbdb89135",
   "metadata": {},
   "source": [
    "**Congrats!** You've created a conversational agent in langgraph that can use a search engine to retrieve updated information when needed. Now it can handle a wider range of user queries. To inspect all the steps your agent just took, check out this [LangSmith trace](https://smith.langchain.com/public/24b94adc-3356-4d9f-8f94-813f8004fdbe/r).\n",
    "\n",
    "Our chatbot still can't remember past interactions on its own, limiting its ability to have coherent, multi-turn conversations. In the next part, we'll add **memory** to address this.\n",
    "\n",
    "\n",
    "The full code for the graph we've created in this section is reproduced below, replacing our `BasicToolNode` for the prebuilt [ToolNode](https://langchain-ai.github.io/langgraph/reference/prebuilt/#toolnode), and our `route_tools` condition with the prebuilt [tools_condition](https://langchain-ai.github.io/langgraph/reference/prebuilt/#tools_condition)\n",
    "\n",
    "<details>\n",
    "<summary>Full Code</summary>\n",
    "    <pre>\n",
    "\n",
    "```python\n",
    "from typing import Annotated\n",
    "\n",
    "from langchain_anthropic import ChatAnthropic\n",
    "from langchain_community.tools.tavily_search import TavilySearchResults\n",
    "from langchain_core.messages import BaseMessage\n",
    "from typing_extensions import TypedDict\n",
    "\n",
    "from langgraph.graph import StateGraph\n",
    "from langgraph.graph.message import add_messages\n",
    "from langgraph.prebuilt import ToolNode, tools_condition\n",
    "\n",
    "\n",
    "class State(TypedDict):\n",
    "    messages: Annotated[list, add_messages]\n",
    "\n",
    "\n",
    "graph_builder = StateGraph(State)\n",
    "\n",
    "\n",
    "tool = TavilySearchResults(max_results=2)\n",
    "tools = [tool]\n",
    "llm = ChatAnthropic(model=\"claude-3-haiku-20240307\")\n",
    "llm_with_tools = llm.bind_tools(tools)\n",
    "\n",
    "\n",
    "def chatbot(state: State):\n",
    "    return {\"messages\": [llm_with_tools.invoke(state[\"messages\"])]}\n",
    "\n",
    "\n",
    "graph_builder.add_node(\"chatbot\", chatbot)\n",
    "\n",
    "tool_node = ToolNode(tools=[tool])\n",
    "graph_builder.add_node(\"tools\", tool_node)\n",
    "\n",
    "graph_builder.add_conditional_edges(\n",
    "    \"chatbot\",\n",
    "    tools_condition,\n",
    ")\n",
    "# Any time a tool is called, we return to the chatbot to decide the next step\n",
    "graph_builder.add_edge(\"tools\", \"chatbot\")\n",
    "graph_builder.set_entry_point(\"chatbot\")\n",
    "graph = graph_builder.compile()\n",
    "```\n",
    "\n",
    "</pre>\n",
    "</details>"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ae45f2aa-396f-4f3f-848b-7750611617f8",
   "metadata": {},
   "source": [
    "## Part 3: Adding Memory to the Chatbot\n",
    "\n",
    "Our chatbot can now use tools to answer user questions, but it doesn't remember the context of previous interactions. This limits its ability to have coherent, multi-turn conversations.\n",
    "\n",
    "LangGraph solves this problem through **persistent checkpointing**. If you provide a `checkpointer` when compiling the graph and a `thread_id` when calling your graph, LangGraph automatically saves the state after each step. When you invoke the graph again using the same `thread_id`, the graph loads its saved state, allowing the chatbot to pick up where it left off. \n",
    "\n",
    "We will see later that **checkpointing** is _much_ more powerful than simple chat memory - it lets you save and resume complex state at any time for error recovery, human-in-the-loop workflows, time travel interactions, and more. But before we get too ahead of ourselves, let's add checkpointing to enable multi-turn conversations.\n",
    "\n",
    "To get started, create a `MemorySaver` checkpointer."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "6baafdf6-6803-4305-9381-9dc970468a4d",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langgraph.checkpoint.memory import MemorySaver\n",
    "\n",
    "memory = MemorySaver()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "08d3d11a-1b42-4cbb-8e11-2a4294263d90",
   "metadata": {},
   "source": [
    "**Notice** we're using an in-memory checkpointer. This is convenient for our tutorial (it saves it all in-memory). In a production application, you would likely change this to use `SqliteSaver` or `PostgresSaver` and connect to your own DB.\n",
    "\n",
    "Next define the graph. Now that you've already built your own `BasicToolNode`, we'll replace it with LangGraph's prebuilt `ToolNode` and `tools_condition`, since these do some nice things like parallel API execution. Apart from that, the following is all copied from Part 2."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "e6a51f1e-00de-4701-8931-de8cf19294ae",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/Users/wfh/code/lc/langchain/libs/core/langchain_core/_api/beta_decorator.py:87: LangChainBetaWarning: The method `ChatAnthropic.bind_tools` is in beta. It is actively being worked on, so the API may change.\n",
      "  warn_beta(\n"
     ]
    }
   ],
   "source": [
    "from typing import Annotated\n",
    "\n",
    "from langchain_anthropic import ChatAnthropic\n",
    "from langchain_community.tools.tavily_search import TavilySearchResults\n",
    "from langchain_core.messages import BaseMessage\n",
    "from typing_extensions import TypedDict\n",
    "\n",
    "from langgraph.graph import StateGraph, START, END\n",
    "from langgraph.graph.message import add_messages\n",
    "from langgraph.prebuilt import ToolNode, tools_condition\n",
    "\n",
    "\n",
    "class State(TypedDict):\n",
    "    messages: Annotated[list, add_messages]\n",
    "\n",
    "\n",
    "graph_builder = StateGraph(State)\n",
    "\n",
    "\n",
    "tool = TavilySearchResults(max_results=2)\n",
    "tools = [tool]\n",
    "llm = ChatAnthropic(model=\"claude-3-haiku-20240307\")\n",
    "llm_with_tools = llm.bind_tools(tools)\n",
    "\n",
    "\n",
    "def chatbot(state: State):\n",
    "    return {\"messages\": [llm_with_tools.invoke(state[\"messages\"])]}\n",
    "\n",
    "\n",
    "graph_builder.add_node(\"chatbot\", chatbot)\n",
    "\n",
    "tool_node = ToolNode(tools=[tool])\n",
    "graph_builder.add_node(\"tools\", tool_node)\n",
    "\n",
    "graph_builder.add_conditional_edges(\n",
    "    \"chatbot\",\n",
    "    tools_condition,\n",
    ")\n",
    "# Any time a tool is called, we return to the chatbot to decide the next step\n",
    "graph_builder.add_edge(\"tools\", \"chatbot\")\n",
    "graph_builder.add_edge(START, \"chatbot\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8a292dfe-764f-4561-90aa-71317d679d3e",
   "metadata": {},
   "source": [
    "Finally, compile the graph with the provided checkpointer."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "a06548bf-81fa-4436-b4c1-f68601fb4187",
   "metadata": {},
   "outputs": [],
   "source": [
    "graph = graph_builder.compile(checkpointer=memory)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "df01805c-4458-4474-b13b-59ecfe228f12",
   "metadata": {},
   "source": [
    "Notice the connectivity of the graph hasn't changed since Part 2. All we are doing is checkpointing the `State` as the graph works through each node."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "761d15fb-d5e2-4d50-a630-126d77e77294",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/jpeg": "[encoded data, 10844 characters]",
      "text/plain": [
       "<IPython.core.display.Image object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "from IPython.display import Image, display\n",
    "\n",
    "try:\n",
    "    display(Image(graph.get_graph().draw_mermaid_png()))\n",
    "except Exception:\n",
    "    # This requires some extra dependencies and is optional\n",
    "    pass"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2c8265ef-e5b4-4c32-9856-5572b5652142",
   "metadata": {},
   "source": [
    "Now you can interact with your bot! First, pick a thread to use as the key for this conversation."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "be7b5abb-04ef-4d53-83d1-d4d3139cc43a",
   "metadata": {},
   "outputs": [],
   "source": [
    "config = {\"configurable\": {\"thread_id\": \"1\"}}"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d0b1a5ee-7fa2-475c-a9db-749694b90ba9",
   "metadata": {},
   "source": [
    "Next, call your chat bot."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "dba1b168-f8e0-496d-9bd6-37198fb4776e",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "================================\u001b[1m Human Message \u001b[0m=================================\n",
      "\n",
      "Hi there! My name is Will.\n",
      "==================================\u001b[1m Ai Message \u001b[0m==================================\n",
      "\n",
      "It's nice to meet you, Will! I'm an AI assistant created by Anthropic. I'm here to help you with any questions or tasks you may have. Please let me know how I can assist you today.\n"
     ]
    }
   ],
   "source": [
    "user_input = \"Hi there! My name is Will.\"\n",
    "\n",
    "# The config is the **second positional argument** to stream() or invoke()!\n",
    "events = graph.stream(\n",
    "    {\"messages\": [(\"user\", user_input)]}, config, stream_mode=\"values\"\n",
    ")\n",
    "for event in events:\n",
    "    event[\"messages\"][-1].pretty_print()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "33c6b470-5082-4c3e-b732-34de47c88735",
   "metadata": {},
   "source": [
    "**Note:** The config was provided as the **second positional argument** when calling our graph. It importantly is _not_ nested within the graph inputs (`{'messages': []}`).\n",
    "\n",
    "Let's ask a followup: see if it remembers your name."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "f5447778-53d7-47f3-801b-f47bcf2185a0",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "================================\u001b[1m Human Message \u001b[0m=================================\n",
      "\n",
      "Remember my name?\n",
      "==================================\u001b[1m Ai Message \u001b[0m==================================\n",
      "\n",
      "Of course, your name is Will. It's nice to meet you again!\n"
     ]
    }
   ],
   "source": [
    "user_input = \"Remember my name?\"\n",
    "\n",
    "# The config is the **second positional argument** to stream() or invoke()!\n",
    "events = graph.stream(\n",
    "    {\"messages\": [(\"user\", user_input)]}, config, stream_mode=\"values\"\n",
    ")\n",
    "for event in events:\n",
    "    event[\"messages\"][-1].pretty_print()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "33be4cd8-f96f-4949-9d1f-48054502e5d0",
   "metadata": {},
   "source": [
    "**Notice** that we aren't using an external list for memory: it's all handled by the checkpointer! You can inspect the full execution in this [LangSmith trace](https://smith.langchain.com/public/48387889-c002-47a8-9f6a-1f6b298db64b/r) to see what's going on.\n",
    "\n",
    "Don't believe me? Try this using a different config."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "4527cf9a-b191-4bde-858a-e33a74a48c55",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "================================\u001b[1m Human Message \u001b[0m=================================\n",
      "\n",
      "Remember my name?\n",
      "==================================\u001b[1m Ai Message \u001b[0m==================================\n",
      "\n",
      "I'm afraid I don't actually have the capability to remember your name. As an AI assistant, I don't have a persistent memory of our previous conversations or interactions. I respond based on the current context provided to me. Could you please restate your name or provide more information so I can try to assist you?\n"
     ]
    }
   ],
   "source": [
    "# The only difference is we change the `thread_id` here to \"2\" instead of \"1\"\n",
    "events = graph.stream(\n",
    "    {\"messages\": [(\"user\", user_input)]},\n",
    "    {\"configurable\": {\"thread_id\": \"2\"}},\n",
    "    stream_mode=\"values\",\n",
    ")\n",
    "for event in events:\n",
    "    event[\"messages\"][-1].pretty_print()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5eeccbf0-ed74-4838-a7e9-31910d82b0b2",
   "metadata": {},
   "source": [
    "**Notice** that the **only** change we've made is to modify the `thread_id` in the config. See this call's [LangSmith trace](https://smith.langchain.com/public/4647adf6-3835-4ce3-ba39-26ed4f167411/r) for comparison. \n",
    "\n",
    "By now, we have made a few checkpoints across two different threads. But what goes into a checkpoint? To inspect a graph's `state` for a given config at any time, call `get_state(config)`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "0be77c25-1423-4f2d-9b2d-28530cc761a4",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "StateSnapshot(values={'messages': [HumanMessage(content='Hi there! My name is Will.', id='aad97d7f-8845-4f9e-b723-2af3b7c97590'), AIMessage(content=\"It's nice to meet you, Will! I'm an AI assistant created by Anthropic. I'm here to help you with any questions or tasks you may have. Please let me know how I can assist you today.\", response_metadata={'id': 'msg_01VCz7Y5jVmMZXibBtnECyvJ', 'model': 'claude-3-haiku-20240307', 'stop_reason': 'end_turn', 'stop_sequence': None, 'usage': {'input_tokens': 375, 'output_tokens': 49}}, id='run-66cf1695-5ba8-4fd8-a79d-ded9ee3c3b33-0'), HumanMessage(content='Remember my name?', id='ac1e9971-dbee-4622-9e63-5015dee05c20'), AIMessage(content=\"Of course, your name is Will. It's nice to meet you again!\", response_metadata={'id': 'msg_01RsJ6GaQth7r9soxbF7TSpQ', 'model': 'claude-3-haiku-20240307', 'stop_reason': 'end_turn', 'stop_sequence': None, 'usage': {'input_tokens': 431, 'output_tokens': 19}}, id='run-890149d3-214f-44e8-9717-57ec4ef68224-0')]}, next=(), config={'configurable': {'thread_id': '1', 'thread_ts': '2024-05-06T22:23:20.430350+00:00'}}, parent_config=None)"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "snapshot = graph.get_state(config)\n",
    "snapshot"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "c106bd09-f155-4e15-9120-c60c834106e5",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "()"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "snapshot.next  # (since the graph ended this turn, `next` is empty. If you fetch a state from within a graph invocation, next tells which node will execute next)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "627f4998-6780-4cce-8f3c-9a5580888e3a",
   "metadata": {},
   "source": [
    "The snapshot above contains the current state values, corresponding config, and the `next` node to process. In our case, the graph has reached an `__end__` state, so `next` is empty.\n",
    "\n",
    "**Congratulations!** Your chatbot can now maintain conversation state across sessions thanks to LangGraph's checkpointing system. This opens up exciting possibilities for more natural, contextual interactions. LangGraph's checkpointing even handles **arbitrarily complex graph states**, which is much more expressive and powerful than simple chat memory.\n",
    "\n",
    "In the next part, we'll introduce human oversight to our bot to handle situations where it may need guidance or verification before proceeding.\n",
    "  \n",
    "Check out the code snippet below to review our graph from this section.\n",
    "\n",
    "<details>\n",
    "<summary>Full Code</summary>\n",
    "    <pre>\n",
    "\n",
    "```python\n",
    "from typing import Annotated\n",
    "\n",
    "from langchain_anthropic import ChatAnthropic\n",
    "from langchain_community.tools.tavily_search import TavilySearchResults\n",
    "from langchain_core.messages import BaseMessage\n",
    "from typing_extensions import TypedDict\n",
    "\n",
    "from langgraph.checkpoint.memory import MemorySaver\n",
    "from langgraph.graph import StateGraph\n",
    "from langgraph.graph.message import add_messages\n",
    "from langgraph.prebuilt import ToolNode\n",
    "\n",
    "\n",
    "class State(TypedDict):\n",
    "    messages: Annotated[list, add_messages]\n",
    "\n",
    "\n",
    "graph_builder = StateGraph(State)\n",
    "\n",
    "\n",
    "tool = TavilySearchResults(max_results=2)\n",
    "tools = [tool]\n",
    "llm = ChatAnthropic(model=\"claude-3-haiku-20240307\")\n",
    "llm_with_tools = llm.bind_tools(tools)\n",
    "\n",
    "\n",
    "def chatbot(state: State):\n",
    "    return {\"messages\": [llm_with_tools.invoke(state[\"messages\"])]}\n",
    "\n",
    "\n",
    "graph_builder.add_node(\"chatbot\", chatbot)\n",
    "\n",
    "tool_node = ToolNode(tools=[tool])\n",
    "graph_builder.add_node(\"tools\", tool_node)\n",
    "\n",
    "graph_builder.add_conditional_edges(\n",
    "    \"chatbot\",\n",
    "    tools_condition,\n",
    ")\n",
    "graph_builder.add_edge(\"tools\", \"chatbot\")\n",
    "graph_builder.set_entry_point(\"chatbot\")\n",
    "graph = graph_builder.compile(checkpointer=memory)\n",
    "```\n",
    "</pre>\n",
    "</pre>\n",
    "</details>"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6f1da240-ec9b-441f-9d47-44c6dc85d540",
   "metadata": {},
   "source": [
    "## Part 4: Human-in-the-loop\n",
    "\n",
    "Agents can be unreliable and may need human input to successfully accomplish tasks. Similarly, for some actions, you may want to require human approval before running to ensure that everything is running as intended.\n",
    "\n",
    "LangGraph supports `human-in-the-loop` workflows in a number of ways. In this section, we will use LangGraph's `interrupt_before` functionality to always break the tool node.\n",
    "\n",
    "First, start from our existing code. The following is copied from Part 3."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "5a81608a-373a-4339-b1c6-65b73a92b983",
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import Annotated\n",
    "\n",
    "from langchain_anthropic import ChatAnthropic\n",
    "from langchain_community.tools.tavily_search import TavilySearchResults\n",
    "from langchain_core.messages import BaseMessage\n",
    "from typing_extensions import TypedDict\n",
    "\n",
    "from langgraph.checkpoint.memory import MemorySaver\n",
    "from langgraph.graph import StateGraph, START\n",
    "from langgraph.graph.message import add_messages\n",
    "from langgraph.prebuilt import ToolNode, tools_condition\n",
    "\n",
    "memory = MemorySaver()\n",
    "\n",
    "\n",
    "class State(TypedDict):\n",
    "    messages: Annotated[list, add_messages]\n",
    "\n",
    "\n",
    "graph_builder = StateGraph(State)\n",
    "\n",
    "\n",
    "tool = TavilySearchResults(max_results=2)\n",
    "tools = [tool]\n",
    "llm = ChatAnthropic(model=\"claude-3-haiku-20240307\")\n",
    "llm_with_tools = llm.bind_tools(tools)\n",
    "\n",
    "\n",
    "def chatbot(state: State):\n",
    "    return {\"messages\": [llm_with_tools.invoke(state[\"messages\"])]}\n",
    "\n",
    "\n",
    "graph_builder.add_node(\"chatbot\", chatbot)\n",
    "\n",
    "tool_node = ToolNode(tools=[tool])\n",
    "graph_builder.add_node(\"tools\", tool_node)\n",
    "\n",
    "graph_builder.add_conditional_edges(\n",
    "    \"chatbot\",\n",
    "    tools_condition,\n",
    ")\n",
    "graph_builder.add_edge(\"tools\", \"chatbot\")\n",
    "graph_builder.add_edge(START, \"chatbot\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "813505b2-18c1-46e9-b891-20a34232808b",
   "metadata": {},
   "source": [
    "Now, compile the graph, specifying to `interrupt_before` the `tools` node."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "b0883e32-1a39-4ce9-ae32-bbd66708fd84",
   "metadata": {},
   "outputs": [],
   "source": [
    "graph = graph_builder.compile(\n",
    "    checkpointer=memory,\n",
    "    # This is new!\n",
    "    interrupt_before=[\"tools\"],\n",
    "    # Note: can also interrupt __after__ tools, if desired.\n",
    "    # interrupt_after=[\"tools\"]\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "9f318020-ab7e-415b-a5e2-eddec6d9f3a6",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "================================\u001b[1m Human Message \u001b[0m=================================\n",
      "\n",
      "I'm learning LangGraph. Could you do some research on it for me?\n",
      "==================================\u001b[1m Ai Message \u001b[0m==================================\n",
      "\n",
      "[{'text': \"Okay, let's look up some information on LangGraph:\", 'type': 'text'}, {'id': 'toolu_01XoHVKTRbipJokQorfifzvh', 'input': {'query': 'LangGraph'}, 'name': 'tavily_search_results_json', 'type': 'tool_use'}]\n",
      "Tool Calls:\n",
      "  tavily_search_results_json (toolu_01XoHVKTRbipJokQorfifzvh)\n",
      " Call ID: toolu_01XoHVKTRbipJokQorfifzvh\n",
      "  Args:\n",
      "    query: LangGraph\n"
     ]
    }
   ],
   "source": [
    "user_input = \"I'm learning LangGraph. Could you do some research on it for me?\"\n",
    "config = {\"configurable\": {\"thread_id\": \"1\"}}\n",
    "# The config is the **second positional argument** to stream() or invoke()!\n",
    "events = graph.stream(\n",
    "    {\"messages\": [(\"user\", user_input)]}, config, stream_mode=\"values\"\n",
    ")\n",
    "for event in events:\n",
    "    if \"messages\" in event:\n",
    "        event[\"messages\"][-1].pretty_print()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "39405637-13b1-40b1-a51e-6d60bf675ff1",
   "metadata": {},
   "source": [
    "Let's inspect the graph state to confirm it worked."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "9bb7af46-9b4f-4bb1-b8b9-e9ddf7dbc82c",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "('tools',)"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "snapshot = graph.get_state(config)\n",
    "snapshot.next"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "89326046-2b11-4812-8b6d-8780306ec275",
   "metadata": {},
   "source": [
    "**Notice** that unlike last time, the \"next\" node is set to **'tools'**. We've interrupted here! Let's check the tool invocation."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "3facda0a-e6ad-4b28-b627-753ad8c90c15",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[{'name': 'tavily_search_results_json',\n",
       "  'args': {'query': 'LangGraph'},\n",
       "  'id': 'toolu_01XoHVKTRbipJokQorfifzvh',\n",
       "  'type': 'tool_call'}]"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "existing_message = snapshot.values[\"messages\"][-1]\n",
    "existing_message.tool_calls"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a55a4c70-7226-4be0-8562-391f72bc1f2b",
   "metadata": {},
   "source": [
    "This query seems reasonable. Nothing to filter here. The simplest thing the human can do is just let the graph continue executing. Let's do that below.\n",
    "\n",
    "Next, continue the graph! Passing in `None` will just let the graph continue where it left off, without adding anything new to the state."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "effb95d9-b7d5-40c5-9253-253d193b23b2",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "=================================\u001b[1m Tool Message \u001b[0m=================================\n",
      "Name: tavily_search_results_json\n",
      "\n",
      "[{\"url\": \"https://langchain-ai.github.io/langgraph/tutorials/\", \"content\": \"LangGraph is a framework for building language agents as graphs. Learn how to use LangGraph to create chatbots, code assistants, planning agents, reflection agents, and more with these notebooks.\"}, {\"url\": \"https://github.com/langchain-ai/langgraph\", \"content\": \"LangGraph is a library for creating stateful, multi-actor applications with LLMs, using cycles, controllability, and persistence. Learn how to use LangGraph with examples, integration with LangChain, and streaming support.\"}]\n",
      "==================================\u001b[1m Ai Message \u001b[0m==================================\n",
      "\n",
      "Based on the search results, LangGraph seems to be a framework for building language-based AI agents and applications using language models. It provides a modular, graph-based approach for creating chatbots, code assistants, planning agents, and other language-centric applications.\n",
      "\n",
      "Some key things I learned about LangGraph:\n",
      "\n",
      "- It is designed to make it easier to build stateful, multi-actor applications using large language models (LLMs).\n",
      "- It provides features like cycles, controllability, and persistence to help manage the complexity of these types of applications.\n",
      "- LangGraph can be integrated with the LangChain library, which provides additional tools for building LLM-powered applications.\n",
      "- The framework includes examples and tutorials to help get started with using LangGraph.\n",
      "\n",
      "Overall, LangGraph seems like a promising approach for building more advanced, graph-based language applications on top of large language models. Let me know if you need any other details on LangGraph and how it works!\n"
     ]
    }
   ],
   "source": [
    "# `None` will append nothing new to the current state, letting it resume as if it had never been interrupted\n",
    "events = graph.stream(None, config, stream_mode=\"values\")\n",
    "for event in events:\n",
    "    if \"messages\" in event:\n",
    "        event[\"messages\"][-1].pretty_print()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "21e78a97-474f-4709-b51d-9d5e8323e14c",
   "metadata": {},
   "source": [
    "Review this call's [LangSmith trace](https://smith.langchain.com/public/6a9012c0-bfa2-4fba-8dce-961d233f9512/r) to see the exact work that was done in the above call. Notice that the state is loaded in the first step so that your chatbot can continue where it left off.\n",
    "\n",
    "**Congrats!** You've used an `interrupt` to add human-in-the-loop execution to your chatbot, allowing for human oversight and intervention when needed. This opens up the potential UIs you can create with your AI systems. Since we have already added a **checkpointer**, the graph can be paused **indefinitely** and resumed at any time as if nothing had happened.\n",
    "\n",
    "Next, we'll explore how to further customize the bot's behavior using custom state updates.\n",
    "\n",
    "Below is a copy of the code you used in this section. The only difference between this and the previous parts is the addition of the `interrupt_before` argument.\n",
    "\n",
    "<details>\n",
    "<summary>Full Code</summary>\n",
    "    <pre>\n",
    "\n",
    "```python\n",
    "from typing import Annotated\n",
    "\n",
    "from langchain_anthropic import ChatAnthropic\n",
    "from langchain_community.tools.tavily_search import TavilySearchResults\n",
    "from langchain_core.messages import BaseMessage\n",
    "from typing_extensions import TypedDict\n",
    "\n",
    "from langgraph.checkpoint.memory import MemorySaver\n",
    "from langgraph.graph import StateGraph\n",
    "from langgraph.graph.message import add_messages\n",
    "from langgraph.prebuilt import ToolNode\n",
    "\n",
    "\n",
    "class State(TypedDict):\n",
    "    messages: Annotated[list, add_messages]\n",
    "\n",
    "\n",
    "graph_builder = StateGraph(State)\n",
    "\n",
    "\n",
    "tool = TavilySearchResults(max_results=2)\n",
    "tools = [tool]\n",
    "llm = ChatAnthropic(model=\"claude-3-haiku-20240307\")\n",
    "llm_with_tools = llm.bind_tools(tools)\n",
    "\n",
    "\n",
    "def chatbot(state: State):\n",
    "    return {\"messages\": [llm_with_tools.invoke(state[\"messages\"])]}\n",
    "\n",
    "\n",
    "graph_builder.add_node(\"chatbot\", chatbot)\n",
    "\n",
    "tool_node = ToolNode(tools=[tool])\n",
    "graph_builder.add_node(\"tools\", tool_node)\n",
    "\n",
    "graph_builder.add_conditional_edges(\n",
    "    \"chatbot\",\n",
    "    tools_condition,\n",
    ")\n",
    "graph_builder.add_edge(\"tools\", \"chatbot\")\n",
    "graph_builder.set_entry_point(\"chatbot\")\n",
    "\n",
    "memory = MemorySaver()\n",
    "graph = graph_builder.compile(\n",
    "    checkpointer=memory,\n",
    "    # This is new!\n",
    "    interrupt_before=[\"tools\"],\n",
    "    # Note: can also interrupt __after__ actions, if desired.\n",
    "    # interrupt_after=[\"tools\"]\n",
    ")\n",
    "```\n",
    "</pre>\n",
    "</details>"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6df38bc4-c177-4ccd-9ec2-83d32bf66722",
   "metadata": {},
   "source": [
    "## Part 5: Manually Updating the State\n",
    "\n",
    "In the previous section, we showed how to interrupt a graph so that a human could inspect its actions. This lets the human `read` the state, but if they want to change their agent's course, they'll need to have `write` access.\n",
    "\n",
    "Thankfully, LangGraph lets you **manually update state**! Updating the state lets you control the agent's trajectory by modifying its actions (even modifying the past!). This capability is particularly useful when you want to correct the agent's mistakes, explore alternative paths, or guide the agent towards a specific goal.\n",
    "\n",
    "We'll show how to update a checkpointed state below. As before, first, define your graph. We'll reuse the exact same graph as before."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "faa345c6-38a2-42e8-9035-9cf56f7bb5b1",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/Users/wfh/code/lc/langchain/libs/core/langchain_core/_api/beta_decorator.py:87: LangChainBetaWarning: The method `ChatAnthropic.bind_tools` is in beta. It is actively being worked on, so the API may change.\n",
      "  warn_beta(\n"
     ]
    }
   ],
   "source": [
    "from typing import Annotated\n",
    "\n",
    "from langchain_anthropic import ChatAnthropic\n",
    "from langchain_community.tools.tavily_search import TavilySearchResults\n",
    "from langchain_core.messages import BaseMessage\n",
    "from typing_extensions import TypedDict\n",
    "\n",
    "from langgraph.checkpoint.memory import MemorySaver\n",
    "from langgraph.graph import StateGraph, START\n",
    "from langgraph.graph.message import add_messages\n",
    "from langgraph.prebuilt import ToolNode, tools_condition\n",
    "\n",
    "\n",
    "class State(TypedDict):\n",
    "    messages: Annotated[list, add_messages]\n",
    "\n",
    "\n",
    "graph_builder = StateGraph(State)\n",
    "\n",
    "\n",
    "tool = TavilySearchResults(max_results=2)\n",
    "tools = [tool]\n",
    "llm = ChatAnthropic(model=\"claude-3-haiku-20240307\")\n",
    "llm_with_tools = llm.bind_tools(tools)\n",
    "\n",
    "\n",
    "def chatbot(state: State):\n",
    "    return {\"messages\": [llm_with_tools.invoke(state[\"messages\"])]}\n",
    "\n",
    "\n",
    "graph_builder.add_node(\"chatbot\", chatbot)\n",
    "\n",
    "tool_node = ToolNode(tools=[tool])\n",
    "graph_builder.add_node(\"tools\", tool_node)\n",
    "\n",
    "graph_builder.add_conditional_edges(\n",
    "    \"chatbot\",\n",
    "    tools_condition,\n",
    ")\n",
    "graph_builder.add_edge(\"tools\", \"chatbot\")\n",
    "graph_builder.add_edge(START, \"chatbot\")\n",
    "memory = MemorySaver()\n",
    "graph = graph_builder.compile(\n",
    "    checkpointer=memory,\n",
    "    # This is new!\n",
    "    interrupt_before=[\"tools\"],\n",
    "    # Note: can also interrupt **after** actions, if desired.\n",
    "    # interrupt_after=[\"tools\"]\n",
    ")\n",
    "\n",
    "user_input = \"I'm learning LangGraph. Could you do some research on it for me?\"\n",
    "config = {\"configurable\": {\"thread_id\": \"1\"}}\n",
    "# The config is the **second positional argument** to stream() or invoke()!\n",
    "events = graph.stream({\"messages\": [(\"user\", user_input)]}, config)\n",
    "for event in events:\n",
    "    if \"messages\" in event:\n",
    "        event[\"messages\"][-1].pretty_print()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "a6b3bcae-dd04-49da-a4ef-e05634657faf",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "==================================\u001b[1m Ai Message \u001b[0m==================================\n",
      "\n",
      "[{'id': 'toolu_01DTyDpJ1kKdNps5yxv3AGJd', 'input': {'query': 'LangGraph'}, 'name': 'tavily_search_results_json', 'type': 'tool_use'}]\n",
      "Tool Calls:\n",
      "  tavily_search_results_json (toolu_01DTyDpJ1kKdNps5yxv3AGJd)\n",
      " Call ID: toolu_01DTyDpJ1kKdNps5yxv3AGJd\n",
      "  Args:\n",
      "    query: LangGraph\n"
     ]
    }
   ],
   "source": [
    "snapshot = graph.get_state(config)\n",
    "existing_message = snapshot.values[\"messages\"][-1]\n",
    "existing_message.pretty_print()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3bf55a26-8c12-477a-9e83-5011d36ac4ee",
   "metadata": {},
   "source": [
    "So far, all of this is an _exact repeat_ of the previous section. The LLM just requested to use the search engine tool and our graph was interrupted. If we proceed as before, the tool will be called to search the web.\n",
    "\n",
    "But what if the user wants to intercede? What if we think the chat bot doesn't need to use the tool? \n",
    "\n",
    "Let's directly provide the correct response!"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "6a44bedc-ea91-4c22-976c-98b3d5a5e4a7",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "==================================\u001b[1m Ai Message \u001b[0m==================================\n",
      "\n",
      "LangGraph is a library for building stateful, multi-actor applications with LLMs.\n",
      "\n",
      "\n",
      "Last 2 messages;\n",
      "[ToolMessage(content='LangGraph is a library for building stateful, multi-actor applications with LLMs.', id='14589ef1-15db-4a75-82a6-d57c40a216d0', tool_call_id='toolu_01DTyDpJ1kKdNps5yxv3AGJd'), AIMessage(content='LangGraph is a library for building stateful, multi-actor applications with LLMs.', id='1c657bfb-7690-44c7-a26d-d0d22453013d')]\n"
     ]
    }
   ],
   "source": [
    "from langchain_core.messages import AIMessage\n",
    "\n",
    "answer = (\n",
    "    \"LangGraph is a library for building stateful, multi-actor applications with LLMs.\"\n",
    ")\n",
    "new_messages = [\n",
    "    # The LLM API expects some ToolMessage to match its tool call. We'll satisfy that here.\n",
    "    ToolMessage(content=answer, tool_call_id=existing_message.tool_calls[0][\"id\"]),\n",
    "    # And then directly \"put words in the LLM's mouth\" by populating its response.\n",
    "    AIMessage(content=answer),\n",
    "]\n",
    "\n",
    "new_messages[-1].pretty_print()\n",
    "graph.update_state(\n",
    "    # Which state to update\n",
    "    config,\n",
    "    # The updated values to provide. The messages in our `State` are \"append-only\", meaning this will be appended\n",
    "    # to the existing state. We will review how to update existing messages in the next section!\n",
    "    {\"messages\": new_messages},\n",
    ")\n",
    "\n",
    "print(\"\\n\\nLast 2 messages;\")\n",
    "print(graph.get_state(config).values[\"messages\"][-2:])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "584de971-6b10-4931-986e-cc35f7adbb3d",
   "metadata": {},
   "source": [
    "Now the graph is complete, since we've provided the final response message! Since state updates simulate a graph step, they even generate corresponding traces. Inspec the [LangSmith trace](https://smith.langchain.com/public/c45207bb-bd26-4c9a-b631-928bbeebfbcb/r) of the `update_state` call above to see what's going on.\n",
    "\n",
    "**Notice** that our new messages are _appended_ to the messages already in the state. Remember how we defined the `State` type?\n",
    "\n",
    "```python\n",
    "class State(TypedDict):\n",
    "    messages: Annotated[list, add_messages]\n",
    "```\n",
    "\n",
    "We annotated `messages` with the pre-built `add_messages` function. This instructs the graph to always append values to the existing list, rather than overwriting the list directly. The same logic is applied here, so the messages we passed to `update_state` were appended in the same way!\n",
    "\n",
    "The `update_state` function operates as if it were one of the nodes in your graph! By default, the update operation uses the node that was last executed, but you can manually specify it below. Let's add an update and tell the graph to treat it as if it came from the \"chatbot\"."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "d16d95c3-b465-42ac-8015-26b669d45d1f",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'configurable': {'thread_id': '1',\n",
       "  'thread_ts': '2024-05-06T22:27:57.350721+00:00'}}"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "graph.update_state(\n",
    "    config,\n",
    "    {\"messages\": [AIMessage(content=\"I'm an AI expert!\")]},\n",
    "    # Which node for this function to act as. It will automatically continue\n",
    "    # processing as if this node just ran.\n",
    "    as_node=\"chatbot\",\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5a1f0056-6b6f-425f-ac1a-0d4b0e9b85cc",
   "metadata": {},
   "source": [
    "Check out the [LangSmith trace](https://smith.langchain.com/public/ce83989f-6e49-4bdd-bcd5-f54ca55c8d00/r/30b1406a-ae5b-4e9e-9fe5-032be6efb92e) for this update call at the provided link. **Notice** from the trace that the graph continues into the `tools_condition` edge. We just told the graph to treat the update `as_node=\"chatbot\"`. If we follow the diagram below and start from the `chatbot` node, we naturally end up in the `tools_condition` edge and then `__end__` since our updated message lacks tool calls."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "f4009ba6-dc0b-4216-ab0c-fbb104616f73",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/jpeg": "[encoded data, 10844 characters]",
      "text/plain": [
       "<IPython.core.display.Image object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "from IPython.display import Image, display\n",
    "\n",
    "try:\n",
    "    display(Image(graph.get_graph().draw_mermaid_png()))\n",
    "except Exception:\n",
    "    # This requires some extra dependencies and is optional\n",
    "    pass"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "96cd4ffa-8fb2-4bd6-bef9-564cbfe7e3ab",
   "metadata": {},
   "source": [
    "Inspect the current state as before to confirm the checkpoint reflects our manual updates."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "d420e813-a8c7-415d-ab31-5298d42491e4",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[ToolMessage(content='LangGraph is a library for building stateful, multi-actor applications with LLMs.', id='14589ef1-15db-4a75-82a6-d57c40a216d0', tool_call_id='toolu_01DTyDpJ1kKdNps5yxv3AGJd'), AIMessage(content='LangGraph is a library for building stateful, multi-actor applications with LLMs.', id='1c657bfb-7690-44c7-a26d-d0d22453013d'), AIMessage(content=\"I'm an AI expert!\", id='acd668e3-ba31-42c0-843c-00d0994d5885')]\n",
      "()\n"
     ]
    }
   ],
   "source": [
    "snapshot = graph.get_state(config)\n",
    "print(snapshot.values[\"messages\"][-3:])\n",
    "print(snapshot.next)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "380222f4-65fa-4962-afe6-6a715fadb2de",
   "metadata": {},
   "source": [
    "**Notice**: that we've continued to add AI messages to the state. Since we are acting as the `chatbot` and responding with an AIMessage that doesn't contain `tool_calls`, the graph knows that it has entered a finished state (`next` is empty).\n",
    "\n",
    "#### What if you want to **overwrite** existing messages? \n",
    "\n",
    "The [`add_messages`](https://langchain-ai.github.io/langgraph/reference/graphs/?h=add+messages#add_messages) function we used to annotate our graph's `State` above controls how updates are made to the `messages` key. This function looks at any message IDs in the new `messages` list. If the ID matches a message in the existing state, [`add_messages`](https://langchain-ai.github.io/langgraph/reference/graphs/?h=add+messages#add_messages) overwrites the existing message with the new content. \n",
    "\n",
    "As an example, let's update the tool invocation to make sure we get good results from our search engine! First, start a new thread:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "9fc99c7e-b61d-4aec-9c62-042798185ec3",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "================================\u001b[1m Human Message \u001b[0m=================================\n",
      "\n",
      "I'm learning LangGraph. Could you do some research on it for me?\n",
      "==================================\u001b[1m Ai Message \u001b[0m==================================\n",
      "\n",
      "[{'id': 'toolu_013MvjoDHnv476ZGzyPFZhrR', 'input': {'query': 'LangGraph'}, 'name': 'tavily_search_results_json', 'type': 'tool_use'}]\n",
      "Tool Calls:\n",
      "  tavily_search_results_json (toolu_013MvjoDHnv476ZGzyPFZhrR)\n",
      " Call ID: toolu_013MvjoDHnv476ZGzyPFZhrR\n",
      "  Args:\n",
      "    query: LangGraph\n"
     ]
    }
   ],
   "source": [
    "user_input = \"I'm learning LangGraph. Could you do some research on it for me?\"\n",
    "config = {\"configurable\": {\"thread_id\": \"2\"}}  # we'll use thread_id = 2 here\n",
    "events = graph.stream(\n",
    "    {\"messages\": [(\"user\", user_input)]}, config, stream_mode=\"values\"\n",
    ")\n",
    "for event in events:\n",
    "    if \"messages\" in event:\n",
    "        event[\"messages\"][-1].pretty_print()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8b019fc6-7826-4291-9178-6cecb5d7b3d0",
   "metadata": {},
   "source": [
    "**Next,** let's update the tool invocation for our agent. Maybe we want to search for human-in-the-loop workflows in particular."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "7215533a-b7e2-4b2d-bc1d-5122b1d06b8b",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Original\n",
      "Message ID run-59283969-1076-45fe-bee8-ebfccab163c3-0\n",
      "{'name': 'tavily_search_results_json', 'args': {'query': 'LangGraph'}, 'id': 'toolu_013MvjoDHnv476ZGzyPFZhrR'}\n",
      "Updated\n",
      "{'name': 'tavily_search_results_json', 'args': {'query': 'LangGraph human-in-the-loop workflow'}, 'id': 'toolu_013MvjoDHnv476ZGzyPFZhrR'}\n",
      "Message ID run-59283969-1076-45fe-bee8-ebfccab163c3-0\n",
      "\n",
      "\n",
      "Tool calls\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "[{'name': 'tavily_search_results_json',\n",
       "  'args': {'query': 'LangGraph human-in-the-loop workflow'},\n",
       "  'id': 'toolu_013MvjoDHnv476ZGzyPFZhrR'}]"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from langchain_core.messages import AIMessage\n",
    "\n",
    "snapshot = graph.get_state(config)\n",
    "existing_message = snapshot.values[\"messages\"][-1]\n",
    "print(\"Original\")\n",
    "print(\"Message ID\", existing_message.id)\n",
    "print(existing_message.tool_calls[0])\n",
    "new_tool_call = existing_message.tool_calls[0].copy()\n",
    "new_tool_call[\"args\"][\"query\"] = \"LangGraph human-in-the-loop workflow\"\n",
    "new_message = AIMessage(\n",
    "    content=existing_message.content,\n",
    "    tool_calls=[new_tool_call],\n",
    "    # Important! The ID is how LangGraph knows to REPLACE the message in the state rather than APPEND this messages\n",
    "    id=existing_message.id,\n",
    ")\n",
    "\n",
    "print(\"Updated\")\n",
    "print(new_message.tool_calls[0])\n",
    "print(\"Message ID\", new_message.id)\n",
    "graph.update_state(config, {\"messages\": [new_message]})\n",
    "\n",
    "print(\"\\n\\nTool calls\")\n",
    "graph.get_state(config).values[\"messages\"][-1].tool_calls"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "680f0ebd-ebce-4de6-8a9b-37d3d4ef0234",
   "metadata": {},
   "source": [
    "**Notice** that we've modified the AI's tool invocation to search for \"LangGraph human-in-the-loop workflow\" instead of the simple \"LangGraph\".\n",
    "\n",
    "Check out the [LangSmith trace](https://smith.langchain.com/public/cd7c09a6-758d-41d4-8de1-64ab838b2338/r) to see the state update call - you can see our new message has successfully updated the previous AI message.\n",
    "\n",
    "Resume the graph by streaming with an input of `None` and the existing config."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "03a09bfc-3d90-4e54-878f-22e3cb28a418",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "=================================\u001b[1m Tool Message \u001b[0m=================================\n",
      "Name: tavily_search_results_json\n",
      "\n",
      "[{\"url\": \"https://langchain-ai.github.io/langgraph/how-tos/human-in-the-loop/\", \"content\": \"Human-in-the-loop\\u00b6 When creating LangGraph agents, it is often nice to add a human in the loop component. This can be helpful when giving them access to tools. ... from langgraph.graph import MessageGraph, END # Define a new graph workflow = MessageGraph # Define the two nodes we will cycle between workflow. add_node (\\\"agent\\\", call_model) ...\"}, {\"url\": \"https://langchain-ai.github.io/langgraph/how-tos/chat_agent_executor_with_function_calling/human-in-the-loop/\", \"content\": \"Human-in-the-loop. In this example we will build a ReAct Agent that has a human in the loop. We will use the human to approve specific actions. This examples builds off the base chat executor. It is highly recommended you learn about that executor before going through this notebook. You can find documentation for that example here.\"}]\n",
      "==================================\u001b[1m Ai Message \u001b[0m==================================\n",
      "\n",
      "Based on the search results, LangGraph appears to be a framework for building AI agents that can interact with humans in a conversational way. The key points I gathered are:\n",
      "\n",
      "- LangGraph allows for \"human-in-the-loop\" workflows, where a human can be involved in approving or reviewing actions taken by the AI agent.\n",
      "- This can be useful for giving the AI agent access to various tools and capabilities, with the human able to provide oversight and guidance.\n",
      "- The framework includes components like \"MessageGraph\" for defining the conversational flow between the agent and human.\n",
      "\n",
      "Overall, LangGraph seems to be a way to create conversational AI agents that can leverage human input and guidance, rather than operating in a fully autonomous way. Let me know if you need any clarification or have additional questions!\n"
     ]
    }
   ],
   "source": [
    "events = graph.stream(None, config, stream_mode=\"values\")\n",
    "for event in events:\n",
    "    if \"messages\" in event:\n",
    "        event[\"messages\"][-1].pretty_print()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "090b680b-f53f-4af2-a432-45f8c5a10779",
   "metadata": {},
   "source": [
    "Check out the [trace](https://smith.langchain.com/public/2d633326-14ad-4248-a391-2757d01851c4/r/6464f2f2-edb4-4ef3-8f48-ee4e249f2ad0) to see the tool call and later LLM response. **Notice** that now the graph queries the search engine using our updated query term - we were able to manually override the LLM's search here!\n",
    "\n",
    "All of this is reflected in the graph's checkpointed memory, meaning if we continue the conversation, it will recall all the _modified_ state."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "11d5b934-6d8b-4f52-a3bc-b3daa7207e00",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "================================\u001b[1m Human Message \u001b[0m=================================\n",
      "\n",
      "Remember what I'm learning about?\n",
      "==================================\u001b[1m Ai Message \u001b[0m==================================\n",
      "\n",
      "Ah yes, now I remember - you mentioned earlier that you are learning about LangGraph.\n",
      "\n",
      "LangGraph is the framework I researched in my previous response, which is for building conversational AI agents that can incorporate human input and oversight.\n",
      "\n",
      "So based on our earlier discussion, it seems you are currently learning about and exploring the LangGraph system for creating human-in-the-loop AI agents. Please let me know if I have the right understanding now.\n"
     ]
    }
   ],
   "source": [
    "events = graph.stream(\n",
    "    {\n",
    "        \"messages\": (\n",
    "            \"user\",\n",
    "            \"Remember what I'm learning about?\",\n",
    "        )\n",
    "    },\n",
    "    config,\n",
    "    stream_mode=\"values\",\n",
    ")\n",
    "for event in events:\n",
    "    if \"messages\" in event:\n",
    "        event[\"messages\"][-1].pretty_print()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a5166e1b-96a6-4ac0-88a1-bf32a422134a",
   "metadata": {},
   "source": [
    "**Congratulations!** You've used `interrupt_before` and `update_state` to manually modify the state as a part of a human-in-the-loop workflow. Interruptions and state modifications let you control how the agent behaves. Combined with persistent checkpointing, it means you can `pause` an action and `resume` at any point. Your user doesn't have to be available when the graph interrupts!\n",
    "\n",
    "The graph code for this section is identical to previous ones. The key snippets to remember are to add `.compile(..., interrupt_before=[...])` (or `interrupt_after`) if you want to explicitly pause the graph whenever it reaches a node. Then you can use `update_state` to modify the checkpoint and control how the graph should proceed."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d88d4c9e-65c8-4093-a6c2-c261475f7c07",
   "metadata": {},
   "source": [
    "## Part 6: Customizing State\n",
    "\n",
    "So far, we've relied on a simple state (it's just a list of messages!). You can go far with this simple state, but if you want to define complex behavior without relying on the message list, you can add additional fields to the state. In this section, we will extend our chat bot with a new node to illustrate this.\n",
    "\n",
    "In the examples above, we involved a human deterministically: the graph __always__ interrupted whenever an tool was invoked. Suppose we wanted our chat bot to have the choice of relying on a human.\n",
    "\n",
    "One way to do this is to create a passthrough \"human\" node, before which the graph will always stop. We will only execute this node if the LLM invokes a \"human\" tool. For our convenience, we will include an \"ask_human\" flag in our graph state that we will flip if the LLM calls this tool.\n",
    "\n",
    "Below, define this new graph, with an updated `State`"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "3cf7e042-1718-4625-ae30-a9917f595449",
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import Annotated\n",
    "\n",
    "from langchain_anthropic import ChatAnthropic\n",
    "from langchain_community.tools.tavily_search import TavilySearchResults\n",
    "from langchain_core.messages import BaseMessage\n",
    "from typing_extensions import TypedDict\n",
    "\n",
    "from langgraph.checkpoint.memory import MemorySaver\n",
    "from langgraph.graph import StateGraph, START\n",
    "from langgraph.graph.message import add_messages\n",
    "from langgraph.prebuilt import ToolNode, tools_condition\n",
    "\n",
    "\n",
    "class State(TypedDict):\n",
    "    messages: Annotated[list, add_messages]\n",
    "    # This flag is new\n",
    "    ask_human: bool"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e87f2cb8-c066-4b54-acc4-e8c7399c5f3d",
   "metadata": {},
   "source": [
    "Next, define a schema to show the model to let it decide to request assistance."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "e5192e54-6a28-42fe-a8a7-62d45d61f994",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain_core.pydantic_v1 import BaseModel\n",
    "\n",
    "\n",
    "class RequestAssistance(BaseModel):\n",
    "    \"\"\"Escalate the conversation to an expert. Use this if you are unable to assist directly or if the user requires support beyond your permissions.\n",
    "\n",
    "    To use this function, relay the user's 'request' so the expert can provide the right guidance.\n",
    "    \"\"\"\n",
    "\n",
    "    request: str"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2b19c61b-2087-463b-adf8-96dbc193f41c",
   "metadata": {},
   "source": [
    "Next, define the chatbot node. The primary modification here is flip the `ask_human` flag if we see that the chat bot has invoked the `RequestAssistance` flag."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "fa59b266-14e5-4c75-8b3d-54fac28e8290",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/Users/wfh/code/lc/langchain/libs/core/langchain_core/_api/beta_decorator.py:87: LangChainBetaWarning: The method `ChatAnthropic.bind_tools` is in beta. It is actively being worked on, so the API may change.\n",
      "  warn_beta(\n"
     ]
    }
   ],
   "source": [
    "tool = TavilySearchResults(max_results=2)\n",
    "tools = [tool]\n",
    "llm = ChatAnthropic(model=\"claude-3-haiku-20240307\")\n",
    "# We can bind the llm to a tool definition, a pydantic model, or a json schema\n",
    "llm_with_tools = llm.bind_tools(tools + [RequestAssistance])\n",
    "\n",
    "\n",
    "def chatbot(state: State):\n",
    "    response = llm_with_tools.invoke(state[\"messages\"])\n",
    "    ask_human = False\n",
    "    if (\n",
    "        response.tool_calls\n",
    "        and response.tool_calls[0][\"name\"] == RequestAssistance.__name__\n",
    "    ):\n",
    "        ask_human = True\n",
    "    return {\"messages\": [response], \"ask_human\": ask_human}"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "04ca0f57-2519-49c2-9499-888b5a884897",
   "metadata": {},
   "source": [
    "Next, create the graph builder and add the chatbot and tools nodes to the graph, same as before."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "3f4464d2-288b-4689-aaf0-329a55dcb85c",
   "metadata": {},
   "outputs": [],
   "source": [
    "graph_builder = StateGraph(State)\n",
    "\n",
    "graph_builder.add_node(\"chatbot\", chatbot)\n",
    "graph_builder.add_node(\"tools\", ToolNode(tools=[tool]))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7f7a0ff3-b671-45c8-8157-ce5db411d370",
   "metadata": {},
   "source": [
    "Next, create the \"human\" `node`. This `node` function is mostly a placeholder in our graph that will trigger an interrupt. If the human does __not__ manually update the state during the `interrupt`, it inserts a tool message so the LLM knows the user was requested but didn't respond. This node also unsets the `ask_human` flag so the graph knows not to revisit the node unless further requests are made."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "1d70b5a4-ce50-47dc-aa43-ffb5c48c46fc",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain_core.messages import AIMessage, ToolMessage\n",
    "\n",
    "\n",
    "def create_response(response: str, ai_message: AIMessage):\n",
    "    return ToolMessage(\n",
    "        content=response,\n",
    "        tool_call_id=ai_message.tool_calls[0][\"id\"],\n",
    "    )\n",
    "\n",
    "\n",
    "def human_node(state: State):\n",
    "    new_messages = []\n",
    "    if not isinstance(state[\"messages\"][-1], ToolMessage):\n",
    "        # Typically, the user will have updated the state during the interrupt.\n",
    "        # If they choose not to, we will include a placeholder ToolMessage to\n",
    "        # let the LLM continue.\n",
    "        new_messages.append(\n",
    "            create_response(\"No response from human.\", state[\"messages\"][-1])\n",
    "        )\n",
    "    return {\n",
    "        # Append the new messages\n",
    "        \"messages\": new_messages,\n",
    "        # Unset the flag\n",
    "        \"ask_human\": False,\n",
    "    }\n",
    "\n",
    "\n",
    "graph_builder.add_node(\"human\", human_node)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d56e5c65-f7b7-48bd-b0b5-fc8e590eca7d",
   "metadata": {},
   "source": [
    "Next, define the conditional logic. The `select_next_node` will route to the `human` node if the flag is set. Otherwise, it lets the prebuilt `tools_condition` function choose the next node.\n",
    "\n",
    "Recall that the `tools_condition` function simply checks to see if the `chatbot` has responded with any `tool_calls` in its response message. If so, it routes to the `action` node. Otherwise, it ends the graph."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "586a0d07-8303-47f4-b3cf-3bdd043e762b",
   "metadata": {},
   "outputs": [],
   "source": [
    "def select_next_node(state: State):\n",
    "    if state[\"ask_human\"]:\n",
    "        return \"human\"\n",
    "    # Otherwise, we can route as before\n",
    "    return tools_condition(state)\n",
    "\n",
    "\n",
    "graph_builder.add_conditional_edges(\n",
    "    \"chatbot\",\n",
    "    select_next_node,\n",
    "    {\"human\": \"human\", \"tools\": \"tools\", \"__end__\": \"__end__\"},\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "66cd0bb1-b13e-477e-a08a-a7e657e2c19e",
   "metadata": {},
   "source": [
    "Finally, add the simple directed edges and compile the graph. These edges instruct the graph to **always** flow from node `a`->`b` whenever `a` finishes executing."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "84101737-0048-4635-9f68-45b0c508b6b6",
   "metadata": {},
   "outputs": [],
   "source": [
    "# The rest is the same\n",
    "graph_builder.add_edge(\"tools\", \"chatbot\")\n",
    "graph_builder.add_edge(\"human\", \"chatbot\")\n",
    "graph_builder.add_edge(START, \"chatbot\")\n",
    "memory = MemorySaver()\n",
    "graph = graph_builder.compile(\n",
    "    checkpointer=memory,\n",
    "    # We interrupt before 'human' here instead.\n",
    "    interrupt_before=[\"human\"],\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7f855593-8690-4a18-9ef8-7f3ccdc335bf",
   "metadata": {},
   "source": [
    "If you have the visualization dependencies installed, you can see the graph structure below:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "b3220ae2-cba0-4447-96d1-eb0be4684e59",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/jpeg": "[encoded data, 15616 characters]",
      "text/plain": [
       "<IPython.core.display.Image object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "from IPython.display import Image, display\n",
    "\n",
    "try:\n",
    "    display(Image(graph.get_graph().draw_mermaid_png()))\n",
    "except Exception:\n",
    "    # This requires some extra dependencies and is optional\n",
    "    pass"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a3b73851-810e-4466-89d8-37fba87e8494",
   "metadata": {},
   "source": [
    "The chat bot can either request help from a human (chatbot->select->human), invoke the search engine tool (chatbot->select->action), or directly respond (chatbot->select->__end__). Once an action or request has been made, the graph will transition back to the `chatbot` node to continue operations.\n",
    "\n",
    "Let's see this graph in action. We will request for expert assistance to illustrate our graph."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "c1955d79-a1e4-47d0-ba79-b45bd5752a23",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "================================\u001b[1m Human Message \u001b[0m=================================\n",
      "\n",
      "I need some expert guidance for building this AI agent. Could you request assistance for me?\n",
      "==================================\u001b[1m Ai Message \u001b[0m==================================\n",
      "\n",
      "[{'id': 'toolu_017XaQuVsoAyfXeTfDyv55Pc', 'input': {'request': 'I need some expert guidance for building this AI agent.'}, 'name': 'RequestAssistance', 'type': 'tool_use'}]\n",
      "Tool Calls:\n",
      "  RequestAssistance (toolu_017XaQuVsoAyfXeTfDyv55Pc)\n",
      " Call ID: toolu_017XaQuVsoAyfXeTfDyv55Pc\n",
      "  Args:\n",
      "    request: I need some expert guidance for building this AI agent.\n"
     ]
    }
   ],
   "source": [
    "user_input = \"I need some expert guidance for building this AI agent. Could you request assistance for me?\"\n",
    "config = {\"configurable\": {\"thread_id\": \"1\"}}\n",
    "# The config is the **second positional argument** to stream() or invoke()!\n",
    "events = graph.stream(\n",
    "    {\"messages\": [(\"user\", user_input)]}, config, stream_mode=\"values\"\n",
    ")\n",
    "for event in events:\n",
    "    if \"messages\" in event:\n",
    "        event[\"messages\"][-1].pretty_print()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b3945ea4-8dbd-4e14-ae2a-34da7f05a0c1",
   "metadata": {},
   "source": [
    "**Notice:** the LLM has invoked the \"`RequestAssistance`\" tool we provided it, and the interrupt has been set. Let's inspect the graph state to confirm."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "5320ba05-5696-4194-8278-5385c571264d",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "('human',)"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "snapshot = graph.get_state(config)\n",
    "snapshot.next"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ed2dd02e-f0a6-4f63-a7d6-e49ecf40db21",
   "metadata": {},
   "source": [
    "The graph state is indeed **interrupted** before the `'human'` node. We can act as the \"expert\" in this scenario and manually update the state by adding a new ToolMessage with our input.\n",
    "\n",
    "Next, respond to the chatbot's request by:\n",
    "1. Creating a `ToolMessage` with our response. This will be passed back to the `chatbot`.\n",
    "2. Calling `update_state` to manually update the graph state."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "2cbac924-61ce-4282-9b1c-77f9090ea1f5",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'configurable': {'thread_id': '1',\n",
       "  'thread_ts': '2024-05-06T22:31:39.973392+00:00'}}"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "ai_message = snapshot.values[\"messages\"][-1]\n",
    "human_response = (\n",
    "    \"We, the experts are here to help! We'd recommend you check out LangGraph to build your agent.\"\n",
    "    \" It's much more reliable and extensible than simple autonomous agents.\"\n",
    ")\n",
    "tool_message = create_response(human_response, ai_message)\n",
    "graph.update_state(config, {\"messages\": [tool_message]})"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "79492363-7fc6-4ec7-977d-9030648029bc",
   "metadata": {},
   "source": [
    "You can inspect the state to confirm our response was added."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "4b986c66-1c65-4da8-a404-db7e28f8364e",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[HumanMessage(content='I need some expert guidance for building this AI agent. Could you request assistance for me?', id='ab75eb9d-cce7-4e44-8de7-b0b375a86972'),\n",
       " AIMessage(content=[{'id': 'toolu_017XaQuVsoAyfXeTfDyv55Pc', 'input': {'request': 'I need some expert guidance for building this AI agent.'}, 'name': 'RequestAssistance', 'type': 'tool_use'}], response_metadata={'id': 'msg_0199PiK6kmVAbeo1qmephKDq', 'model': 'claude-3-haiku-20240307', 'stop_reason': 'tool_use', 'stop_sequence': None, 'usage': {'input_tokens': 486, 'output_tokens': 63}}, id='run-ff07f108-5055-4343-8910-2fa40ead3fb9-0', tool_calls=[{'name': 'RequestAssistance', 'args': {'request': 'I need some expert guidance for building this AI agent.'}, 'id': 'toolu_017XaQuVsoAyfXeTfDyv55Pc'}]),\n",
       " ToolMessage(content=\"We, the experts are here to help! We'd recommend you check out LangGraph to build your agent. It's much more reliable and extensible than simple autonomous agents.\", id='19f2eb9f-a742-46aa-9047-60909c30e64a', tool_call_id='toolu_017XaQuVsoAyfXeTfDyv55Pc')]"
      ]
     },
     "execution_count": 12,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "graph.get_state(config).values[\"messages\"]"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ea6b8616-de10-44d6-a8f0-3ac73c3c3680",
   "metadata": {},
   "source": [
    "Next, **resume** the graph by invoking it with `None` as the inputs."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "6b32914d-4d60-491f-8e11-1e6867e38ffd",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "=================================\u001b[1m Tool Message \u001b[0m=================================\n",
      "\n",
      "We, the experts are here to help! We'd recommend you check out LangGraph to build your agent. It's much more reliable and extensible than simple autonomous agents.\n",
      "==================================\u001b[1m Ai Message \u001b[0m==================================\n",
      "\n",
      "It looks like the experts have provided some guidance on how to build your AI agent. They suggested checking out LangGraph, which they say is more reliable and extensible than simple autonomous agents. Please let me know if you need any other assistance - I'm happy to help coordinate with the expert team further.\n"
     ]
    }
   ],
   "source": [
    "events = graph.stream(None, config, stream_mode=\"values\")\n",
    "for event in events:\n",
    "    if \"messages\" in event:\n",
    "        event[\"messages\"][-1].pretty_print()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "48e0559b-d653-4dab-8928-b001004d14cb",
   "metadata": {},
   "source": [
    "**Notice** that the chat bot has incorporated the updated state in its final response. Since **everything** was checkpointed, the \"expert\" human in the loop could perform the update at any time without impacting the graph's execution.\n",
    "\n",
    "**Congratulations!** you've now added an additional node to your assistant graph to let the chat bot decide for itself whether or not it needs to interrupt execution. You did so by updating the graph `State` with a new `ask_human` field and modifying the interruption logic when compiling the graph. This lets you dynamically include a human in the loop while maintaining full **memory** every time you execute the graph.\n",
    "\n",
    "We're almost done with the tutorial, but there is one more concept we'd like to review before finishing that connects `checkpointing` and `state updates`. \n",
    "\n",
    "This section's code is reproduced below for your reference.\n",
    "\n",
    "<details>\n",
    "<summary>Full Code</summary>\n",
    "    <pre>\n",
    "\n",
    "```python\n",
    "from typing import Annotated\n",
    "\n",
    "from langchain_anthropic import ChatAnthropic\n",
    "from langchain_community.tools.tavily_search import TavilySearchResults\n",
    "from langchain_core.messages import BaseMessage\n",
    "from langchain_core.pydantic_v1 import BaseModel\n",
    "from typing_extensions import TypedDict\n",
    "\n",
    "from langgraph.checkpoint.memory import MemorySaver\n",
    "from langgraph.graph import StateGraph\n",
    "from langgraph.graph.message import add_messages\n",
    "from langgraph.prebuilt import ToolNode, tools_condition\n",
    "\n",
    "\n",
    "class State(TypedDict):\n",
    "    messages: Annotated[list, add_messages]\n",
    "    # This flag is new\n",
    "    ask_human: bool\n",
    "\n",
    "\n",
    "class RequestAssistance(BaseModel):\n",
    "    \"\"\"Escalate the conversation to an expert. Use this if you are unable to assist directly or if the user requires support beyond your permissions.\n",
    "\n",
    "    To use this function, relay the user's 'request' so the expert can provide the right guidance.\n",
    "    \"\"\"\n",
    "\n",
    "    request: str\n",
    "\n",
    "\n",
    "tool = TavilySearchResults(max_results=2)\n",
    "tools = [tool]\n",
    "llm = ChatAnthropic(model=\"claude-3-haiku-20240307\")\n",
    "# We can bind the llm to a tool definition, a pydantic model, or a json schema\n",
    "llm_with_tools = llm.bind_tools(tools + [RequestAssistance])\n",
    "\n",
    "\n",
    "def chatbot(state: State):\n",
    "    response = llm_with_tools.invoke(state[\"messages\"])\n",
    "    ask_human = False\n",
    "    if (\n",
    "        response.tool_calls\n",
    "        and response.tool_calls[0][\"name\"] == RequestAssistance.__name__\n",
    "    ):\n",
    "        ask_human = True\n",
    "    return {\"messages\": [response], \"ask_human\": ask_human}\n",
    "\n",
    "\n",
    "graph_builder = StateGraph(State)\n",
    "\n",
    "graph_builder.add_node(\"chatbot\", chatbot)\n",
    "graph_builder.add_node(\"tools\", ToolNode(tools=[tool]))\n",
    "\n",
    "\n",
    "def create_response(response: str, ai_message: AIMessage):\n",
    "    return ToolMessage(\n",
    "        content=response,\n",
    "        tool_call_id=ai_message.tool_calls[0][\"id\"],\n",
    "    )\n",
    "\n",
    "\n",
    "def human_node(state: State):\n",
    "    new_messages = []\n",
    "    if not isinstance(state[\"messages\"][-1], ToolMessage):\n",
    "        # Typically, the user will have updated the state during the interrupt.\n",
    "        # If they choose not to, we will include a placeholder ToolMessage to\n",
    "        # let the LLM continue.\n",
    "        new_messages.append(\n",
    "            create_response(\"No response from human.\", state[\"messages\"][-1])\n",
    "        )\n",
    "    return {\n",
    "        # Append the new messages\n",
    "        \"messages\": new_messages,\n",
    "        # Unset the flag\n",
    "        \"ask_human\": False,\n",
    "    }\n",
    "\n",
    "\n",
    "graph_builder.add_node(\"human\", human_node)\n",
    "\n",
    "\n",
    "def select_next_node(state: State):\n",
    "    if state[\"ask_human\"]:\n",
    "        return \"human\"\n",
    "    # Otherwise, we can route as before\n",
    "    return tools_condition(state)\n",
    "\n",
    "\n",
    "graph_builder.add_conditional_edges(\n",
    "    \"chatbot\",\n",
    "    select_next_node,\n",
    "    {\"human\": \"human\", \"tools\": \"tools\", \"__end__\": \"__end__\"},\n",
    ")\n",
    "graph_builder.add_edge(\"tools\", \"chatbot\")\n",
    "graph_builder.add_edge(\"human\", \"chatbot\")\n",
    "graph_builder.set_entry_point(\"chatbot\")\n",
    "memory = MemorySaver()\n",
    "graph = graph_builder.compile(\n",
    "    checkpointer=memory,\n",
    "    interrupt_before=[\"human\"],\n",
    ")\n",
    "```\n",
    "</pre>\n",
    "</details>"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "05283db2-2f26-4800-8eda-78a4468a3d8f",
   "metadata": {},
   "source": [
    "## Part 7: Time Travel\n",
    "\n",
    "In a typical chat bot workflow, the user interacts with the bot 1 or more times to accomplish a task. In the previous sections, we saw how to add memory and a human-in-the-loop to be able to checkpoint our graph state and manually override the state to control future responses.\n",
    "\n",
    "But what if you want to let your user start from a previous response and \"branch off\" to explore a separate outcome? Or what if you want users to be able to \"rewind\" your assistant's work to fix some mistakes or try a different strategy (common in applications like autonomous software engineers)?\n",
    "\n",
    "You can create both of these experiences and more using LangGraph's built-in \"time travel\" functionality. \n",
    "\n",
    "In this section, you will \"rewind\" your graph by fetching a checkpoint using the graph's `get_state_history` method. You can then resume execution at this previous point in time.\n",
    "\n",
    "First, recall our chatbot graph. We don't need to make **any** changes from before:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "bb8a02de-a21b-4ef6-a714-7d6e44435e3a",
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import Annotated, Literal\n",
    "\n",
    "from langchain_anthropic import ChatAnthropic\n",
    "from langchain_community.tools.tavily_search import TavilySearchResults\n",
    "from langchain_core.messages import AIMessage, ToolMessage\n",
    "from langchain_core.pydantic_v1 import BaseModel\n",
    "from typing_extensions import TypedDict\n",
    "\n",
    "from langgraph.checkpoint.memory import MemorySaver\n",
    "from langgraph.graph import StateGraph, START\n",
    "from langgraph.graph.message import add_messages\n",
    "from langgraph.prebuilt import ToolNode, tools_condition\n",
    "\n",
    "\n",
    "class State(TypedDict):\n",
    "    messages: Annotated[list, add_messages]\n",
    "    # This flag is new\n",
    "    ask_human: bool\n",
    "\n",
    "\n",
    "class RequestAssistance(BaseModel):\n",
    "    \"\"\"Escalate the conversation to an expert. Use this if you are unable to assist directly or if the user requires support beyond your permissions.\n",
    "\n",
    "    To use this function, relay the user's 'request' so the expert can provide the right guidance.\n",
    "    \"\"\"\n",
    "\n",
    "    request: str\n",
    "\n",
    "\n",
    "tool = TavilySearchResults(max_results=2)\n",
    "tools = [tool]\n",
    "llm = ChatAnthropic(model=\"claude-3-haiku-20240307\")\n",
    "# We can bind the llm to a tool definition, a pydantic model, or a json schema\n",
    "llm_with_tools = llm.bind_tools(tools + [RequestAssistance])\n",
    "\n",
    "\n",
    "def chatbot(state: State):\n",
    "    response = llm_with_tools.invoke(state[\"messages\"])\n",
    "    ask_human = False\n",
    "    if (\n",
    "        response.tool_calls\n",
    "        and response.tool_calls[0][\"name\"] == RequestAssistance.__name__\n",
    "    ):\n",
    "        ask_human = True\n",
    "    return {\"messages\": [response], \"ask_human\": ask_human}\n",
    "\n",
    "\n",
    "graph_builder = StateGraph(State)\n",
    "\n",
    "graph_builder.add_node(\"chatbot\", chatbot)\n",
    "graph_builder.add_node(\"tools\", ToolNode(tools=[tool]))\n",
    "\n",
    "\n",
    "def create_response(response: str, ai_message: AIMessage):\n",
    "    return ToolMessage(\n",
    "        content=response,\n",
    "        tool_call_id=ai_message.tool_calls[0][\"id\"],\n",
    "    )\n",
    "\n",
    "\n",
    "def human_node(state: State):\n",
    "    new_messages = []\n",
    "    if not isinstance(state[\"messages\"][-1], ToolMessage):\n",
    "        # Typically, the user will have updated the state during the interrupt.\n",
    "        # If they choose not to, we will include a placeholder ToolMessage to\n",
    "        # let the LLM continue.\n",
    "        new_messages.append(\n",
    "            create_response(\"No response from human.\", state[\"messages\"][-1])\n",
    "        )\n",
    "    return {\n",
    "        # Append the new messages\n",
    "        \"messages\": new_messages,\n",
    "        # Unset the flag\n",
    "        \"ask_human\": False,\n",
    "    }\n",
    "\n",
    "\n",
    "graph_builder.add_node(\"human\", human_node)\n",
    "\n",
    "\n",
    "def select_next_node(state: State) -> Literal[\"human\", \"tools\", \"__end__\"]:\n",
    "    if state[\"ask_human\"]:\n",
    "        return \"human\"\n",
    "    # Otherwise, we can route as before\n",
    "    return tools_condition(state)\n",
    "\n",
    "\n",
    "graph_builder.add_conditional_edges(\n",
    "    \"chatbot\",\n",
    "    select_next_node,\n",
    "    {\"human\": \"human\", \"tools\": \"tools\", \"__end__\": \"__end__\"},\n",
    ")\n",
    "graph_builder.add_edge(\"tools\", \"chatbot\")\n",
    "graph_builder.add_edge(\"human\", \"chatbot\")\n",
    "graph_builder.add_edge(START, \"chatbot\")\n",
    "memory = MemorySaver()\n",
    "graph = graph_builder.compile(\n",
    "    checkpointer=memory,\n",
    "    interrupt_before=[\"human\"],\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "a7debb4a-2a3a-40b9-a48c-7052ec2c2726",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/jpeg": "[encoded data, 15616 characters]",
      "text/plain": [
       "<IPython.core.display.Image object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "from IPython.display import Image, display\n",
    "\n",
    "try:\n",
    "    display(Image(graph.get_graph().draw_mermaid_png()))\n",
    "except Exception:\n",
    "    # This requires some extra dependencies and is optional\n",
    "    pass"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5414c482-215e-4cc0-9eef-4a8722d2f468",
   "metadata": {},
   "source": [
    "Let's have our graph take a couple steps. Every step will be checkpointed in its state history:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "69071b02-c011-4b7f-90b1-8e89e032322d",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "================================\u001b[1m Human Message \u001b[0m=================================\n",
      "\n",
      "I'm learning LangGraph. Could you do some research on it for me?\n",
      "==================================\u001b[1m Ai Message \u001b[0m==================================\n",
      "\n",
      "[{'text': \"Okay, let me look into LangGraph for you. Here's what I found:\", 'type': 'text'}, {'id': 'toolu_011AQ2FT4RupVka2LVMV3Gci', 'input': {'query': 'LangGraph'}, 'name': 'tavily_search_results_json', 'type': 'tool_use'}]\n",
      "Tool Calls:\n",
      "  tavily_search_results_json (toolu_011AQ2FT4RupVka2LVMV3Gci)\n",
      " Call ID: toolu_011AQ2FT4RupVka2LVMV3Gci\n",
      "  Args:\n",
      "    query: LangGraph\n",
      "=================================\u001b[1m Tool Message \u001b[0m=================================\n",
      "Name: tavily_search_results_json\n",
      "\n",
      "[{\"url\": \"https://langchain-ai.github.io/langgraph/\", \"content\": \"LangGraph is framework agnostic (each node is a regular python function). It extends the core Runnable API (shared interface for streaming, async, and batch calls) to make it easy to: Seamless state management across multiple turns of conversation or tool usage. The ability to flexibly route between nodes based on dynamic criteria.\"}, {\"url\": \"https://blog.langchain.dev/langgraph-multi-agent-workflows/\", \"content\": \"As a part of the launch, we highlighted two simple runtimes: one that is the equivalent of the AgentExecutor in langchain, and a second that was a version of that aimed at message passing and chat models.\\n It's important to note that these three examples are only a few of the possible examples we could highlight - there are almost assuredly other examples out there and we look forward to seeing what the community comes up with!\\n LangGraph: Multi-Agent Workflows\\nLinks\\nLast week we highlighted LangGraph - a new package (available in both Python and JS) to better enable creation of LLM workflows containing cycles, which are a critical component of most agent runtimes. \\\"\\nAnother key difference between Autogen and LangGraph is that LangGraph is fully integrated into the LangChain ecosystem, meaning you take fully advantage of all the LangChain integrations and LangSmith observability.\\n As part of this launch, we're also excited to highlight a few applications built on top of LangGraph that utilize the concept of multiple agents.\\n\"}]\n",
      "==================================\u001b[1m Ai Message \u001b[0m==================================\n",
      "\n",
      "Based on the search results, here's what I've learned about LangGraph:\n",
      "\n",
      "- LangGraph is a framework-agnostic tool that extends the Runnable API to make it easier to manage state and routing between different nodes or agents in a conversational workflow. \n",
      "\n",
      "- It's part of the LangChain ecosystem, so it integrates with other LangChain tools and observability features.\n",
      "\n",
      "- LangGraph enables the creation of multi-agent workflows, where you can have different \"nodes\" or agents that can communicate and pass information to each other.\n",
      "\n",
      "- This allows for more complex conversational flows and the ability to chain together different capabilities, tools, or models.\n",
      "\n",
      "- The key benefits seem to be around state management, flexible routing between agents, and the ability to create more sophisticated and dynamic conversational workflows.\n",
      "\n",
      "Let me know if you need any clarification or have additional questions! I'm happy to do more research on LangGraph if you need further details.\n"
     ]
    }
   ],
   "source": [
    "config = {\"configurable\": {\"thread_id\": \"1\"}}\n",
    "events = graph.stream(\n",
    "    {\n",
    "        \"messages\": [\n",
    "            (\"user\", \"I'm learning LangGraph. Could you do some research on it for me?\")\n",
    "        ]\n",
    "    },\n",
    "    config,\n",
    "    stream_mode=\"values\",\n",
    ")\n",
    "for event in events:\n",
    "    if \"messages\" in event:\n",
    "        event[\"messages\"][-1].pretty_print()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "acbec099-e5d2-497f-929e-c548d7bcbf77",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "================================\u001b[1m Human Message \u001b[0m=================================\n",
      "\n",
      "Ya that's helpful. Maybe I'll build an autonomous agent with it!\n",
      "==================================\u001b[1m Ai Message \u001b[0m==================================\n",
      "\n",
      "[{'text': \"That's great that you're interested in building an autonomous agent using LangGraph! Here are a few additional thoughts on how you could approach that:\", 'type': 'text'}, {'id': 'toolu_01L3V9FhZG5Qx9jqRGfWGtS2', 'input': {'query': 'building autonomous agents with langgraph'}, 'name': 'tavily_search_results_json', 'type': 'tool_use'}]\n",
      "Tool Calls:\n",
      "  tavily_search_results_json (toolu_01L3V9FhZG5Qx9jqRGfWGtS2)\n",
      " Call ID: toolu_01L3V9FhZG5Qx9jqRGfWGtS2\n",
      "  Args:\n",
      "    query: building autonomous agents with langgraph\n",
      "=================================\u001b[1m Tool Message \u001b[0m=================================\n",
      "Name: tavily_search_results_json\n",
      "\n",
      "[{\"url\": \"https://github.com/langchain-ai/langgraphjs\", \"content\": \"LangGraph is a library for building stateful, multi-actor applications with LLMs, built on top of (and intended to be used with) LangChain.js.It extends the LangChain Expression Language with the ability to coordinate multiple chains (or actors) across multiple steps of computation in a cyclic manner. It is inspired by Pregel and Apache Beam.The current interface exposed is one inspired by ...\"}, {\"url\": \"https://github.com/langchain-ai/langgraph\", \"content\": \"LangGraph is a library for building stateful, multi-actor applications with LLMs. It extends the LangChain Expression Language with the ability to coordinate multiple chains (or actors) across multiple steps of computation in a cyclic manner. It is inspired by Pregel and Apache Beam.The current interface exposed is one inspired by NetworkX.. The main use is for adding cycles to your LLM ...\"}]\n",
      "==================================\u001b[1m Ai Message \u001b[0m==================================\n",
      "\n",
      "The key things to keep in mind:\n",
      "\n",
      "1. LangGraph is designed to help coordinate multiple \"agents\" or \"actors\" that can pass information back and forth. This allows you to build more complex, multi-step workflows.\n",
      "\n",
      "2. You'll likely want to define different nodes or agents that handle specific tasks or capabilities. LangGraph makes it easy to route between these agents based on the state of the conversation.\n",
      "\n",
      "3. Make sure to leverage the LangChain ecosystem - things like prompts, memory, agents, tools etc. LangGraph integrates with these to give you a powerful set of building blocks.\n",
      "\n",
      "4. Pay close attention to state management - LangGraph helps you manage state across multiple interactions, which is crucial for an autonomous agent.\n",
      "\n",
      "5. Consider how you'll handle things like user intent, context, and goal-driven behavior. LangGraph gives you the flexibility to implement these kinds of complex behaviors.\n",
      "\n",
      "Let me know if you have any other specific questions as you start prototyping your autonomous agent! I'm happy to provide more guidance.\n"
     ]
    }
   ],
   "source": [
    "events = graph.stream(\n",
    "    {\n",
    "        \"messages\": [\n",
    "            (\"user\", \"Ya that's helpful. Maybe I'll build an autonomous agent with it!\")\n",
    "        ]\n",
    "    },\n",
    "    config,\n",
    "    stream_mode=\"values\",\n",
    ")\n",
    "for event in events:\n",
    "    if \"messages\" in event:\n",
    "        event[\"messages\"][-1].pretty_print()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b2e48c77-65f3-4075-8030-ebf943a281f1",
   "metadata": {},
   "source": [
    "Now that we've had the agent take a couple steps, we can `replay` the full state history to see everything that occurred."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "6c0dbed5-210d-40ad-b002-0bc52ef28fac",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Num Messages:  8 Next:  ()\n",
      "--------------------------------------------------------------------------------\n",
      "Num Messages:  7 Next:  ('chatbot',)\n",
      "--------------------------------------------------------------------------------\n",
      "Num Messages:  6 Next:  ('action',)\n",
      "--------------------------------------------------------------------------------\n",
      "Num Messages:  5 Next:  ('chatbot',)\n",
      "--------------------------------------------------------------------------------\n",
      "Num Messages:  4 Next:  ()\n",
      "--------------------------------------------------------------------------------\n",
      "Num Messages:  3 Next:  ('chatbot',)\n",
      "--------------------------------------------------------------------------------\n",
      "Num Messages:  2 Next:  ('action',)\n",
      "--------------------------------------------------------------------------------\n",
      "Num Messages:  1 Next:  ('chatbot',)\n",
      "--------------------------------------------------------------------------------\n"
     ]
    }
   ],
   "source": [
    "to_replay = None\n",
    "for state in graph.get_state_history(config):\n",
    "    print(\"Num Messages: \", len(state.values[\"messages\"]), \"Next: \", state.next)\n",
    "    print(\"-\" * 80)\n",
    "    if len(state.values[\"messages\"]) == 6:\n",
    "        # We are somewhat arbitrarily selecting a specific state based on the number of chat messages in the state.\n",
    "        to_replay = state"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b182019e-bae3-4616-ba1b-f845c0ab6636",
   "metadata": {},
   "source": [
    "**Notice** that checkpoints are saved for every step of the graph. This __spans invocations__ so you can rewind across a full thread's history. We've picked out `to_replay` as a state to resume from. This is the state after the `chatbot` node in the second graph invocation above.\n",
    "\n",
    "Resuming from this point should call the **action** node next."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "de8d5521-8d71-4093-a657-4920c790802f",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "('action',)\n",
      "{'configurable': {'thread_id': '1', 'thread_ts': '2024-05-06T22:33:10.211424+00:00'}}\n"
     ]
    }
   ],
   "source": [
    "print(to_replay.next)\n",
    "print(to_replay.config)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7e8c61f5-3a4a-4cce-b81b-43fe1dcc971f",
   "metadata": {},
   "source": [
    "**Notice** that the checkpoint's config (`to_replay.config`) contains a `thread_ts` **timestamp**. Providing this `thread_ts` value tells LangGraph's checkpointer to **load** the state from that moment in time. Let's try it below:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "85f17be3-eaf6-495e-a846-49436916b4ab",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "=================================\u001b[1m Tool Message \u001b[0m=================================\n",
      "Name: tavily_search_results_json\n",
      "\n",
      "[{\"url\": \"https://valentinaalto.medium.com/getting-started-with-langgraph-66388e023754\", \"content\": \"Sign up\\nSign in\\nSign up\\nSign in\\nMember-only story\\nGetting Started with LangGraph\\nBuilding multi-agents application with graph frameworks\\nValentina Alto\\nFollow\\n--\\nShare\\nOver the last year, LangChain has established itself as one of the most popular AI framework available in the market. This new library, introduced in January\\u2026\\n--\\n--\\nWritten by Valentina Alto\\nData&AI Specialist at @Microsoft | MSc in Data Science | AI, Machine Learning and Running enthusiast\\nHelp\\nStatus\\nAbout\\nCareers\\nBlog\\nPrivacy\\nTerms\\nText to speech\\nTeams Since the concept of multi-agent applications \\u2014 the ones exhibiting different agents, each having a specific personality and tools to access \\u2014 is getting real and mainstream (see the rise of libraries projects like AutoGen), LangChain\\u2019s developers introduced a new library to make it easier to manage these kind of agentic applications. Nevertheless, those chains were lacking the capability of introducing cycles into their runtime, meaning that there is no out-of-the-box framework to enable the LLM to reason over the next best action in a kind of for-loop scenario. The main feature of LangChain \\u2014 as the name suggests \\u2014 is its ability to easily create the so-called chains.\"}, {\"url\": \"https://blog.langchain.dev/langgraph-multi-agent-workflows/\", \"content\": \"As a part of the launch, we highlighted two simple runtimes: one that is the equivalent of the AgentExecutor in langchain, and a second that was a version of that aimed at message passing and chat models.\\n It's important to note that these three examples are only a few of the possible examples we could highlight - there are almost assuredly other examples out there and we look forward to seeing what the community comes up with!\\n LangGraph: Multi-Agent Workflows\\nLinks\\nLast week we highlighted LangGraph - a new package (available in both Python and JS) to better enable creation of LLM workflows containing cycles, which are a critical component of most agent runtimes. \\\"\\nAnother key difference between Autogen and LangGraph is that LangGraph is fully integrated into the LangChain ecosystem, meaning you take fully advantage of all the LangChain integrations and LangSmith observability.\\n As part of this launch, we're also excited to highlight a few applications built on top of LangGraph that utilize the concept of multiple agents.\\n\"}]\n",
      "==================================\u001b[1m Ai Message \u001b[0m==================================\n",
      "\n",
      "The key things I gathered are:\n",
      "\n",
      "- LangGraph is well-suited for building multi-agent applications, where you have different agents with their own capabilities, tools, and personality.\n",
      "\n",
      "- It allows you to create more complex workflows with cycles and feedback loops, which is critical for building autonomous agents that can reason about their next best actions.\n",
      "\n",
      "- The integration with LangChain means you can leverage other useful features like state management, observability, and integrations with various language models and data sources.\n",
      "\n",
      "Some tips for building an autonomous agent with LangGraph:\n",
      "\n",
      "1. Define the different agents/nodes in your workflow and their specific responsibilities/capabilities.\n",
      "2. Set up the connections and routing between the agents so they can pass information and decisions back and forth.\n",
      "3. Implement logic within each agent to assess the current state and determine the optimal next action.\n",
      "4. Use LangChain features like memory and toolkits to give your agents access to relevant information and abilities.\n",
      "5. Monitor the overall system behavior and iteratively improve the agent interactions and decision-making.\n",
      "\n",
      "Let me know if you have any other questions! I'm happy to provide more guidance as you start building your autonomous agent with LangGraph.\n"
     ]
    }
   ],
   "source": [
    "# The `thread_ts` in the `to_replay.config` corresponds to a state we've persisted to our checkpointer.\n",
    "for event in graph.stream(None, to_replay.config, stream_mode=\"values\"):\n",
    "    if \"messages\" in event:\n",
    "        event[\"messages\"][-1].pretty_print()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c2501fed-2591-420d-98e0-4a3836fb99a8",
   "metadata": {},
   "source": [
    "Notice that the graph resumed execution from the `**action**` node. You can tell this is the case since the first value printed above is the response from our search engine tool.\n",
    "\n",
    "**Congratulations!** You've now used time-travel checkpoint traversal in LangGraph. Being able to rewind and explore alternative paths opens up a world of possibilities for debugging, experimentation, and interactive applications."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e584d57f-5aad-4507-815f-0b2e4b64b791",
   "metadata": {},
   "source": [
    "## Conclusion\n",
    "\n",
    "Congrats! You've completed the intro tutorial and built a chat bot in LangGraph that supports tool calling, persistent memory, human-in-the-loop interactivity, and even time-travel!\n",
    "\n",
    "The [LangGraph documentation](https://langchain-ai.github.io/langgraph/) is a great resource for diving deeper into the library's capabilities."
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "env",
   "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.9"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
