{
 "cells": [
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "51466c8d-8ce4-4b3d-be4e-18fdbeda5f53",
   "metadata": {},
   "source": [
    "# Review Tool Calls\n",
    "\n",
    "Human-in-the-loop (HIL) interactions are crucial for [agentic systems](https://langchain-ai.github.io/langgraph/concepts/agentic_concepts/#human-in-the-loop). A common pattern is to add some human in the loop step after certain tool calls. These tool calls often lead to either a function call or saving of some information. Examples include:\n",
    "\n",
    "- A tool call to execute SQL, which will then be run by the tool\n",
    "- A tool call to generate a summary, which will then be saved to the State of the graph\n",
    "\n",
    "Note that using tool calls is common **whether actually calling tools or not**.\n",
    "\n",
    "There are typically a few different interactions you may want to do here:\n",
    "\n",
    "1. Approve the tool call and continue\n",
    "2. Modify the tool call manually and then continue\n",
    "3. Give natural language feedback, and then pass that back to the agent instead of continuing\n",
    "\n",
    "We can implement this in LangGraph using a [breakpoint](https://langchain-ai.github.io/langgraph/how-tos/human_in_the_loop/breakpoints/): breakpoints allow us to interrupt graph execution before a specific step. At this breakpoint, we can manually update the graph state taking one of the three options above"
   ]
  },
  {
   "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_anthropic"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0abe11f4-62ed-4dc4-8875-3db21e260d1d",
   "metadata": {},
   "source": [
    "Next, we need to set API keys for Anthropic (the LLM 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(\"ANTHROPIC_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": "035e567c-db5c-4085-ba4e-5b3814561c21",
   "metadata": {},
   "source": [
    "## Simple Usage\n",
    "\n",
    "Let's set up a very simple graph that facilitates this.\n",
    "First, we will have an LLM call that decides what action to take.\n",
    "Then we go to a human node. This node actually doesn't do anything - the idea is that we interrupt before this node and then apply any updates to the state.\n",
    "After that, we check the state and either route back to the LLM or to the correct tool.\n",
    "\n",
    "Let's see this in action!"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "85e452f8-f33a-4ead-bb4d-7386cdba8edc",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/jpeg": "[encoded data, 18700 characters]",
      "text/plain": [
       "<IPython.core.display.Image object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "from typing import TypedDict, Literal\n",
    "from langgraph.graph import StateGraph, START, END, MessagesState\n",
    "from langgraph.checkpoint.memory import MemorySaver\n",
    "from langchain_anthropic import ChatAnthropic\n",
    "from langchain_core.tools import tool\n",
    "from langchain_core.messages import AIMessage\n",
    "from IPython.display import Image, display\n",
    "\n",
    "\n",
    "@tool\n",
    "def weather_search(city: str):\n",
    "    \"\"\"Search for the weather\"\"\"\n",
    "    print(\"----\")\n",
    "    print(f\"Searching for: {city}\")\n",
    "    print(\"----\")\n",
    "    return \"Sunny!\"\n",
    "\n",
    "model = ChatAnthropic(model_name=\"claude-3-5-sonnet-20240620\").bind_tools([weather_search])\n",
    "\n",
    "class State(MessagesState):\n",
    "    \"\"\"Simple state.\"\"\"\n",
    "\n",
    "def call_llm(state):\n",
    "    return {\n",
    "        \"messages\": [model.invoke(state['messages'])]\n",
    "    }\n",
    "\n",
    "\n",
    "def human_review_node(state):\n",
    "    pass\n",
    "\n",
    "\n",
    "def run_tool(state):\n",
    "    new_messages = []\n",
    "    tools = {\"weather_search\": weather_search}\n",
    "    tool_calls = state['messages'][-1].tool_calls\n",
    "    for tool_call in tool_calls:\n",
    "        tool = tools[tool_call['name']]\n",
    "        result = tool.invoke(tool_call['args'])\n",
    "        new_messages.append({\n",
    "            \"role\": \"tool\",\n",
    "            \"name\": tool_call['name'],\n",
    "            \"content\": result,\n",
    "            \"tool_call_id\": tool_call['id']\n",
    "        })\n",
    "    return {\"messages\": new_messages}\n",
    "\n",
    "\n",
    "def route_after_llm(state) -> Literal[END, \"human_review_node\"]:\n",
    "    if len(state['messages'][-1].tool_calls) == 0:\n",
    "        return END\n",
    "    else:\n",
    "        return \"human_review_node\"\n",
    "\n",
    "\n",
    "def route_after_human(state) -> Literal[\"run_tool\", \"call_llm\"]:\n",
    "    if isinstance(state['messages'][-1], AIMessage):\n",
    "        return \"run_tool\"\n",
    "    else:\n",
    "        return \"call_llm\"\n",
    "\n",
    "\n",
    "builder = StateGraph(State)\n",
    "builder.add_node(call_llm)\n",
    "builder.add_node(run_tool)\n",
    "builder.add_node(human_review_node)\n",
    "builder.add_edge(START, \"call_llm\")\n",
    "builder.add_conditional_edges(\"call_llm\", route_after_llm)\n",
    "builder.add_conditional_edges(\"human_review_node\", route_after_human)\n",
    "builder.add_edge(\"run_tool\", \"call_llm\")\n",
    "\n",
    "# Set up memory\n",
    "memory = MemorySaver()\n",
    "\n",
    "# Add\n",
    "graph = builder.compile(checkpointer=memory, interrupt_before=[\"human_review_node\"])\n",
    "\n",
    "# View\n",
    "display(Image(graph.get_graph().draw_mermaid_png()))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d246d39f-4b36-459b-bd54-bf363753e590",
   "metadata": {},
   "source": [
    "## Example with no review\n",
    "\n",
    "Let's look at an example when no review is required (because no tools are called)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "1b3aa6fc-c7fb-4819-8d7f-ba6057cc4edf",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'messages': [HumanMessage(content='hi!', id='393fa21d-4bfb-445b-8faa-78e22b92e346')]}\n",
      "{'messages': [HumanMessage(content='hi!', id='393fa21d-4bfb-445b-8faa-78e22b92e346'), AIMessage(content=\"Hello! Welcome to our conversation. How can I assist you today? Is there anything specific you'd like to know or discuss?\", response_metadata={'id': 'msg_017S671xYvZm1mi9EcsKvPzF', 'model': 'claude-3-5-sonnet-20240620', 'stop_reason': 'end_turn', 'stop_sequence': None, 'usage': {'input_tokens': 355, 'output_tokens': 29}}, id='run-8ec507a1-5caf-47d6-89eb-1a2e8f38423c-0', usage_metadata={'input_tokens': 355, 'output_tokens': 29, 'total_tokens': 384})]}\n"
     ]
    }
   ],
   "source": [
    "# Input\n",
    "initial_input = {\"messages\": [{\"role\": \"user\", \"content\": \"hi!\"}]}\n",
    "\n",
    "# Thread\n",
    "thread = {\"configurable\": {\"thread_id\": \"1\"}}\n",
    "\n",
    "# Run the graph until the first interruption\n",
    "for event in graph.stream(initial_input, thread, stream_mode=\"values\"):\n",
    "    print(event)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d59dc607-e70d-497b-aac9-78c847c27042",
   "metadata": {},
   "source": [
    "If we check the state, we can see that it is finished"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "213323cc-0320-4313-ab11-19042e28b495",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Pending Executions!\n",
      "()\n"
     ]
    }
   ],
   "source": [
    "print(\"Pending Executions!\")\n",
    "print(graph.get_state(thread).next)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5c1985f7-54f1-420f-a2b6-5e6154909966",
   "metadata": {},
   "source": [
    "## Example of approving tool\n",
    "\n",
    "Let's now look at what it looks like to approve a tool call"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "2561a38f-edb5-4b44-b2d7-6a7b70d2e6b7",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'messages': [HumanMessage(content=\"what's the weather in sf?\", id='8bda37cc-4bd3-4a14-bca5-b992934e710b')]}\n",
      "{'messages': [HumanMessage(content=\"what's the weather in sf?\", id='8bda37cc-4bd3-4a14-bca5-b992934e710b'), AIMessage(content=[{'text': 'To get the weather information for San Francisco, I can use the weather_search function. Let me do that for you.', 'type': 'text'}, {'id': 'toolu_01MW3ETLpq4b8s6VaAMgDBZP', 'input': {'city': 'San Francisco'}, 'name': 'weather_search', 'type': 'tool_use'}], response_metadata={'id': 'msg_019FjC1prjVv8BuQX7DmF65F', 'model': 'claude-3-5-sonnet-20240620', 'stop_reason': 'tool_use', 'stop_sequence': None, 'usage': {'input_tokens': 360, 'output_tokens': 80}}, id='run-1b580410-173c-4fe0-a149-22e8f516b259-0', tool_calls=[{'name': 'weather_search', 'args': {'city': 'San Francisco'}, 'id': 'toolu_01MW3ETLpq4b8s6VaAMgDBZP', 'type': 'tool_call'}], usage_metadata={'input_tokens': 360, 'output_tokens': 80, 'total_tokens': 440})]}\n"
     ]
    }
   ],
   "source": [
    "# Input\n",
    "initial_input = {\"messages\": [{\"role\": \"user\", \"content\": \"what's the weather in sf?\"}]}\n",
    "\n",
    "# Thread\n",
    "thread = {\"configurable\": {\"thread_id\": \"2\"}}\n",
    "\n",
    "# Run the graph until the first interruption\n",
    "for event in graph.stream(initial_input, thread, stream_mode=\"values\"):\n",
    "    print(event)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4ef6d51c-e2b6-4266-8de7-acf1a0b62a57",
   "metadata": {},
   "source": [
    "If we now check, we can see that it is waiting on human review"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "33d68f0f-d435-4dd1-8013-6a59186dc9f5",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Pending Executions!\n",
      "('human_review_node',)\n"
     ]
    }
   ],
   "source": [
    "print(\"Pending Executions!\")\n",
    "print(graph.get_state(thread).next)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "14c99fdd-4204-4c2d-b1af-02f38ab6ad57",
   "metadata": {},
   "source": [
    "To approve the tool call, we can just continue the thread with no edits. To do this, we just create a new run with no inputs."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "f9a0d5d4-52ff-49e0-a6f4-41f9a0e844d8",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "----\n",
      "Searching for: San Francisco\n",
      "----\n",
      "{'messages': [HumanMessage(content=\"what's the weather in sf?\", id='8bda37cc-4bd3-4a14-bca5-b992934e710b'), AIMessage(content=[{'text': 'To get the weather information for San Francisco, I can use the weather_search function. Let me do that for you.', 'type': 'text'}, {'id': 'toolu_01MW3ETLpq4b8s6VaAMgDBZP', 'input': {'city': 'San Francisco'}, 'name': 'weather_search', 'type': 'tool_use'}], response_metadata={'id': 'msg_019FjC1prjVv8BuQX7DmF65F', 'model': 'claude-3-5-sonnet-20240620', 'stop_reason': 'tool_use', 'stop_sequence': None, 'usage': {'input_tokens': 360, 'output_tokens': 80}}, id='run-1b580410-173c-4fe0-a149-22e8f516b259-0', tool_calls=[{'name': 'weather_search', 'args': {'city': 'San Francisco'}, 'id': 'toolu_01MW3ETLpq4b8s6VaAMgDBZP', 'type': 'tool_call'}], usage_metadata={'input_tokens': 360, 'output_tokens': 80, 'total_tokens': 440}), ToolMessage(content='Sunny!', name='weather_search', id='835b0fe3-8aa0-45d5-ac29-03bbe57cc767', tool_call_id='toolu_01MW3ETLpq4b8s6VaAMgDBZP')]}\n",
      "{'messages': [HumanMessage(content=\"what's the weather in sf?\", id='8bda37cc-4bd3-4a14-bca5-b992934e710b'), AIMessage(content=[{'text': 'To get the weather information for San Francisco, I can use the weather_search function. Let me do that for you.', 'type': 'text'}, {'id': 'toolu_01MW3ETLpq4b8s6VaAMgDBZP', 'input': {'city': 'San Francisco'}, 'name': 'weather_search', 'type': 'tool_use'}], response_metadata={'id': 'msg_019FjC1prjVv8BuQX7DmF65F', 'model': 'claude-3-5-sonnet-20240620', 'stop_reason': 'tool_use', 'stop_sequence': None, 'usage': {'input_tokens': 360, 'output_tokens': 80}}, id='run-1b580410-173c-4fe0-a149-22e8f516b259-0', tool_calls=[{'name': 'weather_search', 'args': {'city': 'San Francisco'}, 'id': 'toolu_01MW3ETLpq4b8s6VaAMgDBZP', 'type': 'tool_call'}], usage_metadata={'input_tokens': 360, 'output_tokens': 80, 'total_tokens': 440}), ToolMessage(content='Sunny!', name='weather_search', id='835b0fe3-8aa0-45d5-ac29-03bbe57cc767', tool_call_id='toolu_01MW3ETLpq4b8s6VaAMgDBZP'), AIMessage(content=\"Based on the search results, the weather in San Francisco is sunny! It's a beautiful day in the city. Is there anything else you'd like to know about the weather or any other information I can help you with?\", response_metadata={'id': 'msg_01UY2d6RCzvwagwMb1J5etek', 'model': 'claude-3-5-sonnet-20240620', 'stop_reason': 'end_turn', 'stop_sequence': None, 'usage': {'input_tokens': 453, 'output_tokens': 49}}, id='run-7137f52c-abe6-4dc1-b536-92dd1d9187b0-0', usage_metadata={'input_tokens': 453, 'output_tokens': 49, 'total_tokens': 502})]}\n"
     ]
    }
   ],
   "source": [
    "for event in graph.stream(None, thread, stream_mode=\"values\"):\n",
    "    print(event)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8d30c4a7-b480-4ede-b2b4-8ec11de95e30",
   "metadata": {},
   "source": [
    "## Edit Tool Call\n",
    "\n",
    "Let's now say we want to edit the tool call. E.g. change some of the parameters (or even the tool called!) but then execute that tool."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "ec77831c-e6b8-4903-9146-e098a4b2fda1",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'messages': [HumanMessage(content=\"what's the weather in sf?\", id='0c488edd-7b9c-4416-ba02-8a2d7e9f2597')]}\n",
      "{'messages': [HumanMessage(content=\"what's the weather in sf?\", id='0c488edd-7b9c-4416-ba02-8a2d7e9f2597'), AIMessage(content=[{'text': \"Certainly! I can help you check the weather in San Francisco. To get this information, I'll use the weather search tool. Let me fetch that for you.\", 'type': 'text'}, {'id': 'toolu_01CpbVmprQnjxpQzx8MzE1g8', 'input': {'city': 'San Francisco'}, 'name': 'weather_search', 'type': 'tool_use'}], response_metadata={'id': 'msg_01Mv7iqdtPgZEX2LiBBqWDuY', 'model': 'claude-3-5-sonnet-20240620', 'stop_reason': 'tool_use', 'stop_sequence': None, 'usage': {'input_tokens': 360, 'output_tokens': 88}}, id='run-52a09799-efb5-4fff-82c3-884e20119ad3-0', tool_calls=[{'name': 'weather_search', 'args': {'city': 'San Francisco'}, 'id': 'toolu_01CpbVmprQnjxpQzx8MzE1g8', 'type': 'tool_call'}], usage_metadata={'input_tokens': 360, 'output_tokens': 88, 'total_tokens': 448})]}\n"
     ]
    }
   ],
   "source": [
    "# Input\n",
    "initial_input = {\"messages\": [{\"role\": \"user\", \"content\": \"what's the weather in sf?\"}]}\n",
    "\n",
    "# Thread\n",
    "thread = {\"configurable\": {\"thread_id\": \"5\"}}\n",
    "\n",
    "# Run the graph until the first interruption\n",
    "for event in graph.stream(initial_input, thread, stream_mode=\"values\"):\n",
    "    print(event)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "edcffbd7-829b-4d0c-88bf-cd531bc0e6b2",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Pending Executions!\n",
      "('human_review_node',)\n"
     ]
    }
   ],
   "source": [
    "print(\"Pending Executions!\")\n",
    "print(graph.get_state(thread).next)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "87358aca-9b8f-48c7-98d4-3d755f6b0104",
   "metadata": {},
   "source": [
    "To do this, we first need to update the state. We can do this by passing a message in with the **same** id of the message we want to overwrite. This will have the effect of **replacing** that old message. Note that this is only possible because of the **reducer** we are using that replaces messages with the same ID - read more about that [here](https://langchain-ai.github.io/langgraph/concepts/low_level/#working-with-messages-in-graph-state)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "df4a9900-d953-4465-b8af-bd2858cb63ea",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Current State:\n",
      "{'messages': [HumanMessage(content=\"what's the weather in sf?\", id='0c488edd-7b9c-4416-ba02-8a2d7e9f2597'), AIMessage(content=[{'text': \"Certainly! I can help you check the weather in San Francisco. To get this information, I'll use the weather search tool. Let me fetch that for you.\", 'type': 'text'}, {'id': 'toolu_01CpbVmprQnjxpQzx8MzE1g8', 'input': {'city': 'San Francisco'}, 'name': 'weather_search', 'type': 'tool_use'}], response_metadata={'id': 'msg_01Mv7iqdtPgZEX2LiBBqWDuY', 'model': 'claude-3-5-sonnet-20240620', 'stop_reason': 'tool_use', 'stop_sequence': None, 'usage': {'input_tokens': 360, 'output_tokens': 88}}, id='run-52a09799-efb5-4fff-82c3-884e20119ad3-0', tool_calls=[{'name': 'weather_search', 'args': {'city': 'San Francisco'}, 'id': 'toolu_01CpbVmprQnjxpQzx8MzE1g8', 'type': 'tool_call'}], usage_metadata={'input_tokens': 360, 'output_tokens': 88, 'total_tokens': 448})]}\n",
      "\n",
      "Current Tool Call ID:\n",
      "toolu_01CpbVmprQnjxpQzx8MzE1g8\n",
      "----\n",
      "Searching for: San Francisco, USA\n",
      "----\n",
      "{'messages': [HumanMessage(content=\"what's the weather in sf?\", id='0c488edd-7b9c-4416-ba02-8a2d7e9f2597'), AIMessage(content=[{'text': \"Certainly! I can help you check the weather in San Francisco. To get this information, I'll use the weather search tool. Let me fetch that for you.\", 'type': 'text'}, {'id': 'toolu_01CpbVmprQnjxpQzx8MzE1g8', 'input': {'city': 'San Francisco'}, 'name': 'weather_search', 'type': 'tool_use'}], id='run-52a09799-efb5-4fff-82c3-884e20119ad3-0', tool_calls=[{'name': 'weather_search', 'args': {'city': 'San Francisco, USA'}, 'id': 'toolu_01CpbVmprQnjxpQzx8MzE1g8', 'type': 'tool_call'}]), ToolMessage(content='Sunny!', name='weather_search', id='ff968b9f-9b87-4893-9f32-dfb88dbe0536', tool_call_id='toolu_01CpbVmprQnjxpQzx8MzE1g8')]}\n",
      "{'messages': [HumanMessage(content=\"what's the weather in sf?\", id='0c488edd-7b9c-4416-ba02-8a2d7e9f2597'), AIMessage(content=[{'text': \"Certainly! I can help you check the weather in San Francisco. To get this information, I'll use the weather search tool. Let me fetch that for you.\", 'type': 'text'}, {'id': 'toolu_01CpbVmprQnjxpQzx8MzE1g8', 'input': {'city': 'San Francisco'}, 'name': 'weather_search', 'type': 'tool_use'}], id='run-52a09799-efb5-4fff-82c3-884e20119ad3-0', tool_calls=[{'name': 'weather_search', 'args': {'city': 'San Francisco, USA'}, 'id': 'toolu_01CpbVmprQnjxpQzx8MzE1g8', 'type': 'tool_call'}]), ToolMessage(content='Sunny!', name='weather_search', id='ff968b9f-9b87-4893-9f32-dfb88dbe0536', tool_call_id='toolu_01CpbVmprQnjxpQzx8MzE1g8'), AIMessage(content=\"Great news! The weather in San Francisco is currently sunny. It's a beautiful day in the city by the bay. Is there anything else you'd like to know about the weather or any other information I can help you with?\", response_metadata={'id': 'msg_01PhwUeRWkSJB6kzHZS361XZ', 'model': 'claude-3-5-sonnet-20240620', 'stop_reason': 'end_turn', 'stop_sequence': None, 'usage': {'input_tokens': 464, 'output_tokens': 50}}, id='run-5aebcf37-626e-4675-b225-476bc99bdbb8-0', usage_metadata={'input_tokens': 464, 'output_tokens': 50, 'total_tokens': 514})]}\n"
     ]
    }
   ],
   "source": [
    "# To get the ID of the message we want to replace, we need to fetch the current state and find it there.\n",
    "state = graph.get_state(thread)\n",
    "print(\"Current State:\")\n",
    "print(state.values)\n",
    "print(\"\\nCurrent Tool Call ID:\")\n",
    "current_content = state.values['messages'][-1].content\n",
    "current_id = state.values['messages'][-1].id\n",
    "tool_call_id = state.values['messages'][-1].tool_calls[0]['id']\n",
    "print(tool_call_id)\n",
    "\n",
    "# We now need to construct a replacement tool call.\n",
    "# We will change the argument to be `San Francisco, USA`\n",
    "# Note that we could change any number of arguments or tool names - it just has to be a valid one\n",
    "new_message = {\n",
    "    \"role\": \"assistant\", \n",
    "    \"content\": current_content,\n",
    "    \"tool_calls\": [\n",
    "        {\n",
    "            \"id\": tool_call_id,\n",
    "            \"name\": \"weather_search\",\n",
    "            \"args\": {\"city\": \"San Francisco, USA\"}\n",
    "        }\n",
    "    ],\n",
    "    # This is important - this needs to be the same as the message you replacing!\n",
    "    # Otherwise, it will show up as a separate message\n",
    "    \"id\": current_id\n",
    "}\n",
    "graph.update_state(\n",
    "    # This is the config which represents this thread\n",
    "    thread, \n",
    "    # This is the updated value we want to push\n",
    "    {\"messages\": [new_message]}, \n",
    "    # We push this update acting as our human_review_node\n",
    "    as_node=\"human_review_node\"\n",
    ")\n",
    "\n",
    "# Let's now continue executing from here\n",
    "for event in graph.stream(None, thread, stream_mode=\"values\"):\n",
    "    print(event)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e14acc96-3d50-44b1-8616-b8d9131e46c4",
   "metadata": {},
   "source": [
    "## Give feedback to a tool call\n",
    "\n",
    "Sometimes, you may not want to execute a tool call, but you also may not want to ask the user to manually modify the tool call. In that case it may be better to get natural language feedback from the user. You can then insert these feedback as a mock **RESULT** of the tool call.\n",
    "\n",
    "There are multiple ways to do this:\n",
    "\n",
    "1. You could add a new message to the state (representing the \"result\" of a tool call)\n",
    "2. You could add TWO new messages to the state - one representing an \"error\" from the tool call, other HumanMessage representing the feedback\n",
    "\n",
    "Both are similar in that they involve adding messages to the state. The main difference lies in the logic AFTER the `human_node` and how it handles different types of messages.\n",
    "\n",
    "For this example we will just add a single tool call representing the feedback. Let's see this in action!"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "d57d5131-7912-4216-aa87-b7272507fa51",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'messages': [HumanMessage(content=\"what's the weather in sf?\", id='601c4c75-f506-4d91-896d-5e382123de24')]}\n",
      "{'messages': [HumanMessage(content=\"what's the weather in sf?\", id='601c4c75-f506-4d91-896d-5e382123de24'), AIMessage(content=[{'text': \"Certainly! I can help you check the weather in San Francisco. To get the most accurate and up-to-date information, I'll use the weather search tool. Let me fetch that for you right away.\", 'type': 'text'}, {'id': 'toolu_014UTKh5uqfc885Fj4RRqGdg', 'input': {'city': 'San Francisco'}, 'name': 'weather_search', 'type': 'tool_use'}], response_metadata={'id': 'msg_013nHyPYxNXFSoXeS6q4oWua', 'model': 'claude-3-5-sonnet-20240620', 'stop_reason': 'tool_use', 'stop_sequence': None, 'usage': {'input_tokens': 360, 'output_tokens': 98}}, id='run-0537e15e-86a4-4c6f-8dfb-6e4c160812c4-0', tool_calls=[{'name': 'weather_search', 'args': {'city': 'San Francisco'}, 'id': 'toolu_014UTKh5uqfc885Fj4RRqGdg', 'type': 'tool_call'}], usage_metadata={'input_tokens': 360, 'output_tokens': 98, 'total_tokens': 458})]}\n"
     ]
    }
   ],
   "source": [
    "# Input\n",
    "initial_input = {\"messages\": [{\"role\": \"user\", \"content\": \"what's the weather in sf?\"}]}\n",
    "\n",
    "# Thread\n",
    "thread = {\"configurable\": {\"thread_id\": \"6\"}}\n",
    "\n",
    "# Run the graph until the first interruption\n",
    "for event in graph.stream(initial_input, thread, stream_mode=\"values\"):\n",
    "    print(event)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "e33ad664-0307-43c5-b85a-1e02eebceb5c",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Pending Executions!\n",
      "('human_review_node',)\n"
     ]
    }
   ],
   "source": [
    "print(\"Pending Executions!\")\n",
    "print(graph.get_state(thread).next)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "483d9455-8625-4c6a-9b98-f731403b2ed3",
   "metadata": {},
   "source": [
    "To do this, we first need to update the state. We can do this by passing a message in with the same **tool call id** of the tool call we want to respond to. Note that this is a **different** ID from above."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "3f05f8b6-6128-4de5-8884-862fc93f1227",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Current State:\n",
      "{'messages': [HumanMessage(content=\"what's the weather in sf?\", id='601c4c75-f506-4d91-896d-5e382123de24'), AIMessage(content=[{'text': \"Certainly! I can help you check the weather in San Francisco. To get the most accurate and up-to-date information, I'll use the weather search tool. Let me fetch that for you right away.\", 'type': 'text'}, {'id': 'toolu_014UTKh5uqfc885Fj4RRqGdg', 'input': {'city': 'San Francisco'}, 'name': 'weather_search', 'type': 'tool_use'}], response_metadata={'id': 'msg_013nHyPYxNXFSoXeS6q4oWua', 'model': 'claude-3-5-sonnet-20240620', 'stop_reason': 'tool_use', 'stop_sequence': None, 'usage': {'input_tokens': 360, 'output_tokens': 98}}, id='run-0537e15e-86a4-4c6f-8dfb-6e4c160812c4-0', tool_calls=[{'name': 'weather_search', 'args': {'city': 'San Francisco'}, 'id': 'toolu_014UTKh5uqfc885Fj4RRqGdg', 'type': 'tool_call'}], usage_metadata={'input_tokens': 360, 'output_tokens': 98, 'total_tokens': 458})]}\n",
      "\n",
      "Current Tool Call ID:\n",
      "toolu_014UTKh5uqfc885Fj4RRqGdg\n",
      "{'messages': [HumanMessage(content=\"what's the weather in sf?\", id='601c4c75-f506-4d91-896d-5e382123de24'), AIMessage(content=[{'text': \"Certainly! I can help you check the weather in San Francisco. To get the most accurate and up-to-date information, I'll use the weather search tool. Let me fetch that for you right away.\", 'type': 'text'}, {'id': 'toolu_014UTKh5uqfc885Fj4RRqGdg', 'input': {'city': 'San Francisco'}, 'name': 'weather_search', 'type': 'tool_use'}], response_metadata={'id': 'msg_013nHyPYxNXFSoXeS6q4oWua', 'model': 'claude-3-5-sonnet-20240620', 'stop_reason': 'tool_use', 'stop_sequence': None, 'usage': {'input_tokens': 360, 'output_tokens': 98}}, id='run-0537e15e-86a4-4c6f-8dfb-6e4c160812c4-0', tool_calls=[{'name': 'weather_search', 'args': {'city': 'San Francisco'}, 'id': 'toolu_014UTKh5uqfc885Fj4RRqGdg', 'type': 'tool_call'}], usage_metadata={'input_tokens': 360, 'output_tokens': 98, 'total_tokens': 458}), ToolMessage(content='User requested changes: pass in the country as well', name='weather_search', id='e20ceddc-a0d3-469d-b31e-512f3042a07e', tool_call_id='toolu_014UTKh5uqfc885Fj4RRqGdg'), AIMessage(content=[{'text': \"I apologize for the oversight. It seems that the weather search function requires more specific information. Let's try again with a more detailed search, including the country. Since San Francisco is commonly associated with the one in California, USA, I'll use that. Here's the updated search:\", 'type': 'text'}, {'id': 'toolu_01AaipBbWDLjHnPcoApx8wRq', 'input': {'city': 'San Francisco, USA'}, 'name': 'weather_search', 'type': 'tool_use'}], response_metadata={'id': 'msg_018rErqC2cLe2VVhebdJf81e', 'model': 'claude-3-5-sonnet-20240620', 'stop_reason': 'tool_use', 'stop_sequence': None, 'usage': {'input_tokens': 480, 'output_tokens': 116}}, id='run-fcba65ed-400a-4783-9ecd-e22051682399-0', tool_calls=[{'name': 'weather_search', 'args': {'city': 'San Francisco, USA'}, 'id': 'toolu_01AaipBbWDLjHnPcoApx8wRq', 'type': 'tool_call'}], usage_metadata={'input_tokens': 480, 'output_tokens': 116, 'total_tokens': 596})]}\n"
     ]
    }
   ],
   "source": [
    "# To get the ID of the message we want to replace, we need to fetch the current state and find it there.\n",
    "state = graph.get_state(thread)\n",
    "print(\"Current State:\")\n",
    "print(state.values)\n",
    "print(\"\\nCurrent Tool Call ID:\")\n",
    "tool_call_id = state.values['messages'][-1].tool_calls[0]['id']\n",
    "print(tool_call_id)\n",
    "\n",
    "# We now need to construct a replacement tool call.\n",
    "# We will change the argument to be `San Francisco, USA`\n",
    "# Note that we could change any number of arguments or tool names - it just has to be a valid one\n",
    "new_message = {\n",
    "    \"role\": \"tool\", \n",
    "    # This is our natural language feedback\n",
    "    \"content\": \"User requested changes: pass in the country as well\",\n",
    "    \"name\": \"weather_search\",\n",
    "    \"tool_call_id\": tool_call_id\n",
    "}\n",
    "graph.update_state(\n",
    "    # This is the config which represents this thread\n",
    "    thread, \n",
    "    # This is the updated value we want to push\n",
    "    {\"messages\": [new_message]}, \n",
    "    # We push this update acting as our human_review_node\n",
    "    as_node=\"human_review_node\"\n",
    ")\n",
    "\n",
    "# Let's now continue executing from here\n",
    "for event in graph.stream(None, thread, stream_mode=\"values\"):\n",
    "    print(event)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2d2e79ab-7cdb-42ce-b2ca-2932f8782c90",
   "metadata": {},
   "source": [
    "We can see that we now get to another breakpoint - because it went back to the model and got an entirely new prediction of what to call. Let's now approve this one and continue."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "a30d40ad-611d-4ec3-84be-869ea05acb89",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Pending Executions!\n",
      "('human_review_node',)\n",
      "----\n",
      "Searching for: San Francisco, USA\n",
      "----\n",
      "{'messages': [HumanMessage(content=\"what's the weather in sf?\", id='601c4c75-f506-4d91-896d-5e382123de24'), AIMessage(content=[{'text': \"Certainly! I can help you check the weather in San Francisco. To get the most accurate and up-to-date information, I'll use the weather search tool. Let me fetch that for you right away.\", 'type': 'text'}, {'id': 'toolu_014UTKh5uqfc885Fj4RRqGdg', 'input': {'city': 'San Francisco'}, 'name': 'weather_search', 'type': 'tool_use'}], response_metadata={'id': 'msg_013nHyPYxNXFSoXeS6q4oWua', 'model': 'claude-3-5-sonnet-20240620', 'stop_reason': 'tool_use', 'stop_sequence': None, 'usage': {'input_tokens': 360, 'output_tokens': 98}}, id='run-0537e15e-86a4-4c6f-8dfb-6e4c160812c4-0', tool_calls=[{'name': 'weather_search', 'args': {'city': 'San Francisco'}, 'id': 'toolu_014UTKh5uqfc885Fj4RRqGdg', 'type': 'tool_call'}], usage_metadata={'input_tokens': 360, 'output_tokens': 98, 'total_tokens': 458}), ToolMessage(content='User requested changes: pass in the country as well', name='weather_search', id='e20ceddc-a0d3-469d-b31e-512f3042a07e', tool_call_id='toolu_014UTKh5uqfc885Fj4RRqGdg'), AIMessage(content=[{'text': \"I apologize for the oversight. It seems that the weather search function requires more specific information. Let's try again with a more detailed search, including the country. Since San Francisco is commonly associated with the one in California, USA, I'll use that. Here's the updated search:\", 'type': 'text'}, {'id': 'toolu_01AaipBbWDLjHnPcoApx8wRq', 'input': {'city': 'San Francisco, USA'}, 'name': 'weather_search', 'type': 'tool_use'}], response_metadata={'id': 'msg_018rErqC2cLe2VVhebdJf81e', 'model': 'claude-3-5-sonnet-20240620', 'stop_reason': 'tool_use', 'stop_sequence': None, 'usage': {'input_tokens': 480, 'output_tokens': 116}}, id='run-fcba65ed-400a-4783-9ecd-e22051682399-0', tool_calls=[{'name': 'weather_search', 'args': {'city': 'San Francisco, USA'}, 'id': 'toolu_01AaipBbWDLjHnPcoApx8wRq', 'type': 'tool_call'}], usage_metadata={'input_tokens': 480, 'output_tokens': 116, 'total_tokens': 596}), ToolMessage(content='Sunny!', name='weather_search', id='3f3ee262-70f5-422c-8e3f-6a9af758514d', tool_call_id='toolu_01AaipBbWDLjHnPcoApx8wRq')]}\n",
      "{'messages': [HumanMessage(content=\"what's the weather in sf?\", id='601c4c75-f506-4d91-896d-5e382123de24'), AIMessage(content=[{'text': \"Certainly! I can help you check the weather in San Francisco. To get the most accurate and up-to-date information, I'll use the weather search tool. Let me fetch that for you right away.\", 'type': 'text'}, {'id': 'toolu_014UTKh5uqfc885Fj4RRqGdg', 'input': {'city': 'San Francisco'}, 'name': 'weather_search', 'type': 'tool_use'}], response_metadata={'id': 'msg_013nHyPYxNXFSoXeS6q4oWua', 'model': 'claude-3-5-sonnet-20240620', 'stop_reason': 'tool_use', 'stop_sequence': None, 'usage': {'input_tokens': 360, 'output_tokens': 98}}, id='run-0537e15e-86a4-4c6f-8dfb-6e4c160812c4-0', tool_calls=[{'name': 'weather_search', 'args': {'city': 'San Francisco'}, 'id': 'toolu_014UTKh5uqfc885Fj4RRqGdg', 'type': 'tool_call'}], usage_metadata={'input_tokens': 360, 'output_tokens': 98, 'total_tokens': 458}), ToolMessage(content='User requested changes: pass in the country as well', name='weather_search', id='e20ceddc-a0d3-469d-b31e-512f3042a07e', tool_call_id='toolu_014UTKh5uqfc885Fj4RRqGdg'), AIMessage(content=[{'text': \"I apologize for the oversight. It seems that the weather search function requires more specific information. Let's try again with a more detailed search, including the country. Since San Francisco is commonly associated with the one in California, USA, I'll use that. Here's the updated search:\", 'type': 'text'}, {'id': 'toolu_01AaipBbWDLjHnPcoApx8wRq', 'input': {'city': 'San Francisco, USA'}, 'name': 'weather_search', 'type': 'tool_use'}], response_metadata={'id': 'msg_018rErqC2cLe2VVhebdJf81e', 'model': 'claude-3-5-sonnet-20240620', 'stop_reason': 'tool_use', 'stop_sequence': None, 'usage': {'input_tokens': 480, 'output_tokens': 116}}, id='run-fcba65ed-400a-4783-9ecd-e22051682399-0', tool_calls=[{'name': 'weather_search', 'args': {'city': 'San Francisco, USA'}, 'id': 'toolu_01AaipBbWDLjHnPcoApx8wRq', 'type': 'tool_call'}], usage_metadata={'input_tokens': 480, 'output_tokens': 116, 'total_tokens': 596}), ToolMessage(content='Sunny!', name='weather_search', id='3f3ee262-70f5-422c-8e3f-6a9af758514d', tool_call_id='toolu_01AaipBbWDLjHnPcoApx8wRq'), AIMessage(content=\"Great news! The weather in San Francisco, USA is currently sunny. \\n\\nHere's a summary of the weather information:\\n- Location: San Francisco, USA\\n- Current conditions: Sunny\\n\\nIt's a beautiful day in San Francisco! The sunny weather is perfect for outdoor activities or simply enjoying the city. Remember to wear sunscreen and stay hydrated if you plan to spend time outside. \\n\\nIs there anything else you'd like to know about the weather in San Francisco or any other location?\", response_metadata={'id': 'msg_017Pnjyte2ZXAREgUvEqbUVt', 'model': 'claude-3-5-sonnet-20240620', 'stop_reason': 'end_turn', 'stop_sequence': None, 'usage': {'input_tokens': 609, 'output_tokens': 107}}, id='run-30c0d0ef-09a3-40ad-b410-80019b284983-0', usage_metadata={'input_tokens': 609, 'output_tokens': 107, 'total_tokens': 716})]}\n"
     ]
    }
   ],
   "source": [
    "print(\"Pending Executions!\")\n",
    "print(graph.get_state(thread).next)\n",
    "\n",
    "for event in graph.stream(None, thread, stream_mode=\"values\"):\n",
    "    print(event)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.1"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
