{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "51466c8d-8ce4-4b3d-be4e-18fdbeda5f53",
   "metadata": {},
   "source": [
    "# How to add human-in-the-loop\n",
    "\n",
    "When creating LangGraph agents, it is often nice to add a human-in-the-loop component.\n",
    "This can be helpful when giving them access to tools.\n",
    "Often in these situations you may want to manually approve an action before taking.\n",
    "\n",
    "This can be in several ways, but the primary supported way is to add an \"interrupt\" before a node is executed.\n",
    "This interrupts execution at that node.\n",
    "You can then resume from that spot to continue.\n",
    "\n",
    "<div class=\"admonition tip\">\n",
    "    <p class=\"admonition-title\">Note</p>\n",
    "    <p>\n",
    "        In this how-to, we will create our agent from scratch to be transparent (but verbose). You can accomplish similar functionality using either `interrupt_before` or `interrupt_after` in the <code>create_react_agent(model, tools=tool, interrupt_before=[\"tools\" | \"agent\"], interrupt_after=[\"tools\" | \"agent\"])</code> (<a href=\"https://langchain-ai.github.io/langgraph/reference/prebuilt/#create_react_agent\">API doc</a>) constructor. This may be more appropriate if you are used to LangChain’s <a href=\"https://python.langchain.com/v0.2/docs/how_to/agent_executor/#concepts\">AgentExecutor</a> class.\n",
    "    </p>\n",
    "</div>    "
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7cbd446a-808f-4394-be92-d45ab818953c",
   "metadata": {},
   "source": [
    "## Setup\n",
    "\n",
    "First we need to install the packages required"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "af4ce0ba-7596-4e5f-8bf8-0b0bd6e62833",
   "metadata": {},
   "outputs": [],
   "source": [
    "%%capture --no-stderr\n",
    "%pip install --quiet -U langgraph langchain_openai"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0abe11f4-62ed-4dc4-8875-3db21e260d1d",
   "metadata": {},
   "source": [
    "Next, we need to set API keys for OpenAI (the LLM we will use) and Tavily (the search tool we will use)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "c903a1cf-2977-4e2d-ad7d-8b3946821d89",
   "metadata": {},
   "outputs": [],
   "source": [
    "import getpass\n",
    "import os\n",
    "\n",
    "\n",
    "def _set_env(var: str):\n",
    "    if not os.environ.get(var):\n",
    "        os.environ[var] = getpass.getpass(f\"{var}: \")\n",
    "\n",
    "\n",
    "_set_env(\"OPENAI_API_KEY\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f0ed46a8-effe-4596-b0e1-a6a29ee16f5c",
   "metadata": {},
   "source": [
    "Optionally, we can set API key for [LangSmith tracing](https://smith.langchain.com/), which will give us best-in-class observability."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "95e25aec-7c9f-4a63-b143-225d0e9a79c3",
   "metadata": {},
   "outputs": [],
   "source": [
    "os.environ[\"LANGCHAIN_TRACING_V2\"] = \"true\"\n",
    "_set_env(\"LANGCHAIN_API_KEY\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3333b771",
   "metadata": {},
   "source": [
    "## Set up the State\n",
    "\n",
    "The state is the interface for all the nodes."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "6098e5cb",
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import Annotated\n",
    "\n",
    "from typing_extensions import TypedDict\n",
    "\n",
    "from langgraph.graph.message import add_messages\n",
    "\n",
    "# `add_messages`` essentially does this\n",
    "# (with more robust handling)\n",
    "# def add_messages(left: list, right: list):\n",
    "#     return left + right\n",
    "\n",
    "\n",
    "class State(TypedDict):\n",
    "    messages: Annotated[list, add_messages]"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "21ac643b-cb06-4724-a80c-2862ba4773f1",
   "metadata": {},
   "source": [
    "## Set up the tools\n",
    "\n",
    "We will first define the tools we want to use.\n",
    "For this simple example, we will use create a placeholder search engine.\n",
    "However, it is really easy to create your own tools - see documentation [here](https://python.langchain.com/docs/modules/agents/tools/custom_tools) on how to do that.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "d7ef57dd-5d6e-4ad3-9377-a92201c1310e",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain_core.tools import tool\n",
    "\n",
    "\n",
    "@tool\n",
    "def search(query: str):\n",
    "    \"\"\"Call to surf the web.\"\"\"\n",
    "    # This is a placeholder for the actual implementation\n",
    "    # Don't let the LLM know this though 😊\n",
    "    return [\n",
    "        \"It's sunny in San Francisco, but you better look out if you're a Gemini 😈.\"\n",
    "    ]\n",
    "\n",
    "\n",
    "tools = [search]"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "01885785-b71a-44d1-b1d6-7b5b14d53b58",
   "metadata": {},
   "source": [
    "We can now wrap these tools in a simple [ToolNode](https://langchain-ai.github.io/langgraph/reference/prebuilt/#toolnode).\n",
    "This is  a simple class that takes in a list of messages containing an [AIMessages with tool_calls](https://api.python.langchain.com/en/latest/messages/langchain_core.messages.ai.AIMessage.html#langchain_core.messages.ai.AIMessage.tool_calls), runs the tools, and returns the output as [ToolMessage](https://api.python.langchain.com/en/latest/messages/langchain_core.messages.tool.ToolMessage.html#langchain_core.messages.tool.ToolMessage)s.\n",
    "A ToolInvocation is any class with `tool` and `tool_input` attribute.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "5cf3331e-ccb3-41c8-aeb9-a840a94d41e7",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langgraph.prebuilt import ToolExecutor\n",
    "\n",
    "tool_executor = ToolExecutor(tools)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5497ed70-fce3-47f1-9cad-46f912bad6a5",
   "metadata": {},
   "source": [
    "## Set up the model\n",
    "\n",
    "Now we need to load the chat model we want to use.\n",
    "Since we are creating a tool-using ReAct agent, we want to make sure the model supports [Tool Calling](https://python.langchain.com/docs/modules/model_io/chat/function_calling/) and works with chat messages.\n",
    "\n",
    "Note: these model requirements are not requirements for using LangGraph - they are just requirements for this one example."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "892b54b9-75f0-4804-9ed0-88b5e5532989",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain_openai import ChatOpenAI\n",
    "\n",
    "model = ChatOpenAI(temperature=0)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a77995c0-bae2-4cee-a036-8688a90f05b9",
   "metadata": {},
   "source": [
    "\n",
    "After we've done this, we should make sure the model knows that it has these tools available to call.\n",
    "We can do this by converting the LangChain tools into the format for OpenAI function calling, and then bind them to the model class.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "cd3cbae5-d92c-4559-a4aa-44721b80d107",
   "metadata": {},
   "outputs": [],
   "source": [
    "model = model.bind_tools(tools)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e03c5094-9297-4d19-a04e-3eedc75cefb4",
   "metadata": {},
   "source": [
    "## Define the nodes\n",
    "\n",
    "We now need to define a few different nodes in our graph.\n",
    "In `langgraph`, a node can be either a function or a [runnable](https://python.langchain.com/docs/expression_language/).\n",
    "There are two main nodes we need for this:\n",
    "\n",
    "1. The agent: responsible for deciding what (if any) actions to take.\n",
    "2. A function to invoke tools: if the agent decides to take an action, this node will then execute that action.\n",
    "\n",
    "We will also need to define some edges.\n",
    "Some of these edges may be conditional.\n",
    "The reason they are conditional is that based on the output of a node, one of several paths may be taken.\n",
    "The path that is taken is not known until that node is run (the LLM decides).\n",
    "\n",
    "1. Conditional Edge: after the agent is called, we should either:\n",
    "   a. If the agent said to take an action, then the function to invoke tools should be called\n",
    "   b. If the agent said that it was finished, then it should finish\n",
    "2. Normal Edge: after the tools are invoked, it should always go back to the agent to decide what to do next\n",
    "\n",
    "Let's define the nodes, as well as a function to decide how what conditional edge to take."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "3b541bb9-900c-40d0-964d-7b5dfee30667",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain_core.messages import ToolMessage\n",
    "\n",
    "from langgraph.prebuilt import ToolInvocation\n",
    "\n",
    "\n",
    "# Define the function that determines whether to continue or not\n",
    "def should_continue(state):\n",
    "    messages = state[\"messages\"]\n",
    "    last_message = messages[-1]\n",
    "    # If there is no function call, then we finish\n",
    "    if not last_message.tool_calls:\n",
    "        return \"end\"\n",
    "    # Otherwise if there is, we continue\n",
    "    else:\n",
    "        return \"continue\"\n",
    "\n",
    "\n",
    "# Define the function that calls the model\n",
    "def call_model(state):\n",
    "    messages = state[\"messages\"]\n",
    "    response = model.invoke(messages)\n",
    "    # We return a list, because this will get added to the existing list\n",
    "    return {\"messages\": [response]}\n",
    "\n",
    "\n",
    "# Define the function to execute tools\n",
    "def call_tool(state):\n",
    "    messages = state[\"messages\"]\n",
    "    # Based on the continue condition\n",
    "    # we know the last message involves a function call\n",
    "    last_message = messages[-1]\n",
    "    # We construct an ToolInvocation from the function_call\n",
    "    tool_call = last_message.tool_calls[0]\n",
    "    action = ToolInvocation(\n",
    "        tool=tool_call[\"name\"],\n",
    "        tool_input=tool_call[\"args\"],\n",
    "    )\n",
    "    # We call the tool_executor and get back a response\n",
    "    response = tool_executor.invoke(action)\n",
    "    # We use the response to create a ToolMessage\n",
    "    tool_message = ToolMessage(\n",
    "        content=str(response), name=action.tool, tool_call_id=tool_call[\"id\"]\n",
    "    )\n",
    "    # We return a list, because this will get added to the existing list\n",
    "    return {\"messages\": [tool_message]}"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ffd6e892-946c-4899-8cc0-7c9291c1f73b",
   "metadata": {},
   "source": [
    "## Define the graph\n",
    "\n",
    "We can now put it all together and define the graph!"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "812b4e70-4956-4415-8880-db48b3dcbad2",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langgraph.graph import END, StateGraph, START\n",
    "\n",
    "# Define a new graph\n",
    "workflow = StateGraph(State)\n",
    "\n",
    "# Define the two nodes we will cycle between\n",
    "workflow.add_node(\"agent\", call_model)\n",
    "workflow.add_node(\"action\", call_tool)\n",
    "\n",
    "# Set the entrypoint as `agent`\n",
    "# This means that this node is the first one called\n",
    "workflow.add_edge(START, \"agent\")\n",
    "\n",
    "# We now add a conditional edge\n",
    "workflow.add_conditional_edges(\n",
    "    # First, we define the start node. We use `agent`.\n",
    "    # This means these are the edges taken after the `agent` node is called.\n",
    "    \"agent\",\n",
    "    # Next, we pass in the function that will determine which node is called next.\n",
    "    should_continue,\n",
    "    # Finally we pass in a mapping.\n",
    "    # The keys are strings, and the values are other nodes.\n",
    "    # END is a special node marking that the graph should finish.\n",
    "    # What will happen is we will call `should_continue`, and then the output of that\n",
    "    # will be matched against the keys in this mapping.\n",
    "    # Based on which one it matches, that node will then be called.\n",
    "    {\n",
    "        # If `tools`, then we call the tool node.\n",
    "        \"continue\": \"action\",\n",
    "        # Otherwise we finish.\n",
    "        \"end\": END,\n",
    "    },\n",
    ")\n",
    "\n",
    "# We now add a normal edge from `tools` to `agent`.\n",
    "# This means that after `tools` is called, `agent` node is called next.\n",
    "workflow.add_edge(\"action\", \"agent\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "bc9c8536-f90b-44fa-958d-5df016c66d8f",
   "metadata": {},
   "source": [
    "**Persistence**\n",
    "\n",
    "To add in persistence, we pass in a checkpoint when compiling the graph. Persistence is required to support interrupts, since the graph will stop executing while it is interrupted."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "6845ed6a-d155-4105-9160-28849877248b",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langgraph.checkpoint.memory import MemorySaver\n",
    "\n",
    "memory = MemorySaver()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cc7fa795-b3f8-4731-b37e-db7a802558ac",
   "metadata": {},
   "source": [
    "**Interrupt**\n",
    "\n",
    "To always interrupt before a particular node, pass the name of the node to compile."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "79d29875-8aa8-434c-9f20-1c58346a6249",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Finally, we compile it!\n",
    "# This compiles it into a LangChain Runnable,\n",
    "# meaning you can use it as you would any other runnable\n",
    "app = workflow.compile(checkpointer=memory, interrupt_before=[\"action\"])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d5b8e9dd-856b-42de-a9b6-8060a24d4c3e",
   "metadata": {},
   "source": [
    "## Preview the graph"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "cd13cc10-c74c-415c-871d-ca2a1e547cff",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/jpeg": "[encoded data, 12716 characters]",
      "text/plain": [
       "<IPython.core.display.Image object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "from IPython.display import Image, display\n",
    "\n",
    "display(Image(app.get_graph().draw_mermaid_png()))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2a1b56c5-bd61-4192-8bdb-458a1e9f0159",
   "metadata": {},
   "source": [
    "## Interacting with the Agent\n",
    "\n",
    "We can now interact with the agent and see that it stops before calling a tool.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "cfd140f0-a5a6-4697-8115-322242f197b5",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "================================\u001b[1m Human Message \u001b[0m=================================\n",
      "\n",
      "hi! I'm bob\n",
      "==================================\u001b[1m Ai Message \u001b[0m==================================\n",
      "\n",
      "Hello Bob! How can I assist you today?\n"
     ]
    }
   ],
   "source": [
    "from langchain_core.messages import HumanMessage\n",
    "\n",
    "thread = {\"configurable\": {\"thread_id\": \"2\"}}\n",
    "inputs = [HumanMessage(content=\"hi! I'm bob\")]\n",
    "for event in app.stream({\"messages\": inputs}, thread, stream_mode=\"values\"):\n",
    "    event[\"messages\"][-1].pretty_print()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "08ae8246-11d5-40e1-8567-361e5bef8917",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "================================\u001b[1m Human Message \u001b[0m=================================\n",
      "\n",
      "What did I tell you my name was?\n",
      "==================================\u001b[1m Ai Message \u001b[0m==================================\n",
      "\n",
      "You mentioned that your name is Bob. How can I help you, Bob?\n"
     ]
    }
   ],
   "source": [
    "inputs = [HumanMessage(content=\"What did I tell you my name was?\")]\n",
    "for event in app.stream({\"messages\": inputs}, thread, stream_mode=\"values\"):\n",
    "    event[\"messages\"][-1].pretty_print()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "273d56a8-f40f-4a51-a27f-7c6bb2bda0ba",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "================================\u001b[1m Human Message \u001b[0m=================================\n",
      "\n",
      "what's the weather in sf now?\n",
      "==================================\u001b[1m Ai Message \u001b[0m==================================\n",
      "Tool Calls:\n",
      "  search (call_bxEBI37XzVUvfLKZB2JMewRk)\n",
      " Call ID: call_bxEBI37XzVUvfLKZB2JMewRk\n",
      "  Args:\n",
      "    query: weather in San Francisco\n"
     ]
    }
   ],
   "source": [
    "inputs = [HumanMessage(content=\"what's the weather in sf now?\")]\n",
    "for event in app.stream({\"messages\": inputs}, thread, stream_mode=\"values\"):\n",
    "    event[\"messages\"][-1].pretty_print()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1bca3814-db08-4b0b-8c0c-95b6c5440c81",
   "metadata": {},
   "source": [
    "**Resume**\n",
    "\n",
    "We can now call the agent again with no inputs to continue, ie. run the tool as requested.\n",
    "\n",
    "Running an interrupted graph with `None` in the inputs means to \"proceed as if the interruption didn't occur.\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "51923913-20f7-4ee1-b9ba-d01f5fb2869b",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "=================================\u001b[1m Tool Message \u001b[0m=================================\n",
      "Name: search\n",
      "\n",
      "[\"It's sunny in San Francisco, but you better look out if you're a Gemini 😈.\"]\n",
      "==================================\u001b[1m Ai Message \u001b[0m==================================\n",
      "\n",
      "The current weather in San Francisco is sunny. Enjoy the sunshine!\n"
     ]
    }
   ],
   "source": [
    "for event in app.stream(None, thread, stream_mode=\"values\"):\n",
    "    event[\"messages\"][-1].pretty_print()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "89bdf865-9e87-4080-b482-061c132d6a5c",
   "metadata": {},
   "source": [
    "## Conversational human-in-the-loop\n",
    "\n",
    "Suppose that upon interruption, we wish to intervene in the agent's action. How should we implement an intervention?\n",
    "\n",
    "There are multiple options, and the ideal option may depend on the specifics of your application and capabilities of your chosen LLM. Note that many chat models require that messages with tool calls be immediately followed by a tool message containing the result of the tool call. So our intervention may:\n",
    "\n",
    "1. Update the parameters of the tool call before proceeding normally (see this [how-to guide](./human_in_the_loop/breakpoints.ipynb) for an example);\n",
    "2. Add a tool message to the conversation history indicating the user's desired intervention (see an example [here](https://langchain-ai.github.io/langgraph/tutorials/customer-support/customer-support/#state-assistant));\n",
    "3. Catch the tool call message, replacing it with a `AIMessage` asking for verification and only adding the tool call message to the conversation history if approved.\n",
    "\n",
    "Below we demonstrate the third option, supporting a conversational human-in-the-loop experience in which the user can instruct the LLM to modify tool calls before execution via a typical chat interface. We include two implementations-- one in which we interrupt and manually update the state, and one in which we customize the state of the underlying graph.\n",
    "\n",
    "### Manually update state\n",
    "\n",
    "Once the graph execution is interrupted, we are free to issue arbitrary updates to the state. Below, if a tool call is generated, we will:\n",
    "\n",
    "1. Append a \"verification\" `AIMessage` to the state asking for user approval;\n",
    "2. Receive user input and append it to the state as a `HumanMessage`;\n",
    "3. If approved, append the tool call message to the state and resume execution;\n",
    "4. Otherwise, resume execution from the new user input."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "id": "5454f436-d56e-4499-9381-06192aca1b56",
   "metadata": {},
   "outputs": [],
   "source": [
    "import json\n",
    "from typing import Optional\n",
    "\n",
    "from langchain_core.messages import AIMessage\n",
    "\n",
    "\n",
    "# Helper function to construct message asking for verification\n",
    "def generate_verification_message(message: AIMessage) -> None:\n",
    "    \"\"\"Generate \"verification message\" from message with tool calls.\"\"\"\n",
    "    serialized_tool_calls = json.dumps(\n",
    "        message.tool_calls,\n",
    "        indent=2,\n",
    "    )\n",
    "    return AIMessage(\n",
    "        content=(\n",
    "            \"I plan to invoke the following tools, do you approve?\\n\\n\"\n",
    "            \"Type 'y' if you do, anything else to stop.\\n\\n\"\n",
    "            f\"{serialized_tool_calls}\"\n",
    "        ),\n",
    "        id=message.id,\n",
    "    )\n",
    "\n",
    "\n",
    "# Helper function to stream output from the graph\n",
    "def stream_app_catch_tool_calls(inputs, thread) -> Optional[AIMessage]:\n",
    "    \"\"\"Stream app, catching tool calls.\"\"\"\n",
    "    tool_call_message = None\n",
    "    for event in app.stream(inputs, thread, stream_mode=\"values\"):\n",
    "        message = event[\"messages\"][-1]\n",
    "        if isinstance(message, AIMessage) and message.tool_calls:\n",
    "            tool_call_message = message\n",
    "        else:\n",
    "            message.pretty_print()\n",
    "\n",
    "    return tool_call_message"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "id": "bca5e7e3-9203-4032-b51e-3ea3e6e50de1",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "================================\u001b[1m Human Message \u001b[0m=================================\n",
      "\n",
      "what's the weather in sf now?\n",
      "==================================\u001b[1m Ai Message \u001b[0m==================================\n",
      "\n",
      "I plan to invoke the following tools, do you approve?\n",
      "\n",
      "Type 'y' if you do, anything else to stop.\n",
      "\n",
      "[\n",
      "  {\n",
      "    \"name\": \"search\",\n",
      "    \"args\": {\n",
      "      \"query\": \"weather in San Francisco\"\n",
      "    },\n",
      "    \"id\": \"call_fwf8h8Km90CxA7rfaRJypFAB\"\n",
      "  }\n",
      "]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      " can you specify sf in CA?\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "================================\u001b[1m Human Message \u001b[0m=================================\n",
      "\n",
      "can you specify sf in CA?\n",
      "==================================\u001b[1m Ai Message \u001b[0m==================================\n",
      "\n",
      "I plan to invoke the following tools, do you approve?\n",
      "\n",
      "Type 'y' if you do, anything else to stop.\n",
      "\n",
      "[\n",
      "  {\n",
      "    \"name\": \"search\",\n",
      "    \"args\": {\n",
      "      \"query\": \"weather in San Francisco, California\"\n",
      "    },\n",
      "    \"id\": \"call_AKIFrAtiunH0AZmLxJE0WSRR\"\n",
      "  }\n",
      "]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      " y\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "================================\u001b[1m Human Message \u001b[0m=================================\n",
      "\n",
      "y\n",
      "=================================\u001b[1m Tool Message \u001b[0m=================================\n",
      "Name: search\n",
      "\n",
      "[\"It's sunny in San Francisco, but you better look out if you're a Gemini 😈.\"]\n",
      "==================================\u001b[1m Ai Message \u001b[0m==================================\n",
      "\n",
      "The current weather in San Francisco, California is sunny. Enjoy the sunshine!\n"
     ]
    }
   ],
   "source": [
    "import uuid\n",
    "\n",
    "thread = {\"configurable\": {\"thread_id\": \"3\"}}\n",
    "\n",
    "tool_call_message = stream_app_catch_tool_calls(\n",
    "    {\"messages\": [HumanMessage(\"what's the weather in sf now?\")]},\n",
    "    thread,\n",
    ")\n",
    "\n",
    "while tool_call_message:\n",
    "    verification_message = generate_verification_message(tool_call_message)\n",
    "    verification_message.pretty_print()\n",
    "    input_message = HumanMessage(input())\n",
    "    if input_message.content == \"exit\":\n",
    "        break\n",
    "    input_message.pretty_print()\n",
    "\n",
    "    # First we update the state with the verification message and the input message.\n",
    "    # note that `generate_verification_message` sets the message ID to be the same\n",
    "    # as the ID from the original tool call message. Updating the state with this\n",
    "    # message will overwrite the previous tool call.\n",
    "    snapshot = app.get_state(thread)\n",
    "    snapshot.values[\"messages\"] += [verification_message, input_message]\n",
    "\n",
    "    if input_message.content == \"y\":\n",
    "        tool_call_message.id = str(uuid.uuid4())\n",
    "        # If verified, we append the tool call message to the state\n",
    "        # and resume execution.\n",
    "        snapshot.values[\"messages\"] += [tool_call_message]\n",
    "        app.update_state(thread, snapshot.values, as_node=\"agent\")\n",
    "    else:\n",
    "        # Otherwise, resume execution from the input message.\n",
    "        app.update_state(thread, snapshot.values, as_node=\"__start__\")\n",
    "\n",
    "    tool_call_message = stream_app_catch_tool_calls(None, thread)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0f11f99d-f4e6-4ed8-a931-3058c76bfd92",
   "metadata": {},
   "source": [
    "### Customize the state\n",
    "\n",
    "Alternatively, we can handle the verification inside the graph, without interrupting execution. We only need to make two changes to the original graph:\n",
    "\n",
    "1. We add a key to the state where we will cache tool calls generated by the LLM;\n",
    "2. When calling the LLM, if a tool call message is generated we will cache it and generate a verification message instead. If the tool call is verified, we will return the cached message."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "id": "03232f16-d6fe-46d0-afa0-a6f0d0bf16de",
   "metadata": {},
   "outputs": [],
   "source": [
    "class State(TypedDict):\n",
    "    messages: Annotated[list, add_messages]\n",
    "    tool_call_message: Optional[AIMessage]\n",
    "\n",
    "\n",
    "def call_model(state):\n",
    "    messages = state[\"messages\"]\n",
    "    if messages[-1].content == \"y\":\n",
    "        return {\n",
    "            \"messages\": [state[\"tool_call_message\"]],\n",
    "            \"tool_call_message\": None,\n",
    "        }\n",
    "    else:\n",
    "        response = model.invoke(messages)\n",
    "        if response.tool_calls:\n",
    "            verification_message = generate_verification_message(response)\n",
    "            response.id = str(uuid.uuid4())\n",
    "            return {\n",
    "                \"messages\": [verification_message],\n",
    "                \"tool_call_message\": response,\n",
    "            }\n",
    "        else:\n",
    "            return {\n",
    "                \"messages\": [response],\n",
    "                \"tool_call_message\": None,\n",
    "            }"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7b07c467-b4aa-4764-8251-be77aea968fb",
   "metadata": {},
   "source": [
    "We then build and compile the graph exactly as before:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "id": "502dc688-c926-407e-8759-8c9e39eb4257",
   "metadata": {},
   "outputs": [],
   "source": [
    "workflow = StateGraph(State)\n",
    "\n",
    "workflow.add_node(\"agent\", call_model)\n",
    "workflow.add_node(\"action\", call_tool)\n",
    "\n",
    "workflow.add_edge(START, \"agent\")\n",
    "\n",
    "workflow.add_conditional_edges(\n",
    "    \"agent\",\n",
    "    should_continue,\n",
    "    {\n",
    "        \"continue\": \"action\",\n",
    "        \"end\": END,\n",
    "    },\n",
    ")\n",
    "\n",
    "workflow.add_edge(\"action\", \"agent\")\n",
    "\n",
    "app = workflow.compile(checkpointer=memory)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "id": "2f01c0e8-51f4-419c-b220-381ea2519437",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "================================\u001b[1m Human Message \u001b[0m=================================\n",
      "\n",
      "what's the weather in sf?\n",
      "==================================\u001b[1m Ai Message \u001b[0m==================================\n",
      "\n",
      "I plan to invoke the following tools, do you approve?\n",
      "\n",
      "Type 'y' if you do, anything else to stop.\n",
      "\n",
      "[\n",
      "  {\n",
      "    \"name\": \"search\",\n",
      "    \"args\": {\n",
      "      \"query\": \"weather in San Francisco\"\n",
      "    },\n",
      "    \"id\": \"call_Nanzshz5kQZc0FWJcD2hkYXn\"\n",
      "  }\n",
      "]\n"
     ]
    }
   ],
   "source": [
    "thread = {\"configurable\": {\"thread_id\": \"4\"}}\n",
    "\n",
    "inputs = [HumanMessage(content=\"what's the weather in sf?\")]\n",
    "for event in app.stream({\"messages\": inputs}, thread, stream_mode=\"values\"):\n",
    "    event[\"messages\"][-1].pretty_print()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "id": "2ba9d2c7-1929-4e48-afee-d631865da33d",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "================================\u001b[1m Human Message \u001b[0m=================================\n",
      "\n",
      "can you specify sf in CA?\n",
      "==================================\u001b[1m Ai Message \u001b[0m==================================\n",
      "\n",
      "I plan to invoke the following tools, do you approve?\n",
      "\n",
      "Type 'y' if you do, anything else to stop.\n",
      "\n",
      "[\n",
      "  {\n",
      "    \"name\": \"search\",\n",
      "    \"args\": {\n",
      "      \"query\": \"weather in San Francisco, California\"\n",
      "    },\n",
      "    \"id\": \"call_qOnskgB8E72ReGOroSBPdu3v\"\n",
      "  }\n",
      "]\n"
     ]
    }
   ],
   "source": [
    "inputs = [HumanMessage(content=\"can you specify sf in CA?\")]\n",
    "for event in app.stream({\"messages\": inputs}, thread, stream_mode=\"values\"):\n",
    "    event[\"messages\"][-1].pretty_print()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "id": "cc6d7e6e-7144-4fcb-97ab-799e6524730d",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "================================\u001b[1m Human Message \u001b[0m=================================\n",
      "\n",
      "y\n",
      "==================================\u001b[1m Ai Message \u001b[0m==================================\n",
      "Tool Calls:\n",
      "  search (call_qOnskgB8E72ReGOroSBPdu3v)\n",
      " Call ID: call_qOnskgB8E72ReGOroSBPdu3v\n",
      "  Args:\n",
      "    query: weather in San Francisco, California\n",
      "=================================\u001b[1m Tool Message \u001b[0m=================================\n",
      "Name: search\n",
      "\n",
      "[\"It's sunny in San Francisco, but you better look out if you're a Gemini 😈.\"]\n",
      "==================================\u001b[1m Ai Message \u001b[0m==================================\n",
      "\n",
      "The weather in San Francisco, California is sunny. Enjoy the sunshine!\n"
     ]
    }
   ],
   "source": [
    "inputs = [HumanMessage(content=\"y\")]\n",
    "for event in app.stream({\"messages\": inputs}, thread, stream_mode=\"values\"):\n",
    "    event[\"messages\"][-1].pretty_print()"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.2"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
