{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "51466c8d-8ce4-4b3d-be4e-18fdbeda5f53",
   "metadata": {},
   "source": [
    "# How to pass graph state to tools\n",
    "\n",
    "Sometimes we need to pass in agent state to our tools. This type of stateful tools is useful when a tool's output is affected by past agent steps (e.g. if you're using a sub-agent as a tool, and want to pass the message history in to the sub-agent), or when a tool's input needs to be validated given context from past agent steps. \n",
    "\n",
    "In this guide we'll demonstrate how to create tools that take agent state as input.\n",
    "\n",
    "This is a special case of [passing runtime arguments to tools](https://python.langchain.com/v0.2/docs/how_to/tool_runtime/), which you can learn about in the LangChain docs."
   ]
  },
  {
   "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": 41,
   "id": "af4ce0ba-7596-4e5f-8bf8-0b0bd6e62833",
   "metadata": {},
   "outputs": [],
   "source": [
    "%%capture --no-stderr\n",
    "%pip install --quiet -U langgraph langchain langchain-openai"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0abe11f4-62ed-4dc4-8875-3db21e260d1d",
   "metadata": {},
   "source": [
    "Next, we need to set API keys for OpenAI (the chat model we will use)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "c903a1cf-2977-4e2d-ad7d-8b3946821d89",
   "metadata": {},
   "outputs": [],
   "source": [
    "import getpass\n",
    "import os\n",
    "\n",
    "os.environ[\"OPENAI_API_KEY\"] = os.environ.get(\"OPENAI_API_KEY\") or getpass.getpass(\n",
    "    \"OpenAI API Key:\"\n",
    ")"
   ]
  },
  {
   "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": 2,
   "id": "95e25aec-7c9f-4a63-b143-225d0e9a79c3",
   "metadata": {},
   "outputs": [],
   "source": [
    "os.environ[\"LANGCHAIN_TRACING_V2\"] = \"true\"\n",
    "os.environ[\"LANGCHAIN_API_KEY\"] = os.environ.get(\n",
    "    \"LANGCHAIN_API_KEY\"\n",
    ") or getpass.getpass(\"LangSmith API Key:\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "21ac643b-cb06-4724-a80c-2862ba4773f1",
   "metadata": {},
   "source": [
    "## Defining the tools\n",
    "\n",
    "We'll want our tool to take graph state as an input, but we don't want the model to try to generate this input when calling the tool. We can use the `InjectedState` annotation to mark arguments as required graph state (or some field of graph state. These arguments will not be generated by the model. When using `ToolNode`, graph state will automatically be passed in to the relevant tools and arguments.\n",
    "\n",
    "In this example we'll create a tool that returns Documents and then another tool that actually cites the Documents that justify a claim."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "1d36e782-80f4-4334-b7d7-ee4c79864480",
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List, Tuple\n",
    "from typing_extensions import Annotated\n",
    "\n",
    "from langchain_core.documents import Document\n",
    "from langchain_core.pydantic_v1 import BaseModel\n",
    "from langchain_core.tools import tool\n",
    "\n",
    "from langgraph.prebuilt import InjectedState\n",
    "\n",
    "\n",
    "@tool(parse_docstring=True, response_format=\"content_and_artifact\")\n",
    "def get_context(question: List[str]) -> Tuple[str, List[Document]]:\n",
    "    \"\"\"Get context on the question.\n",
    "\n",
    "    Args:\n",
    "        question: The user question\n",
    "    \"\"\"\n",
    "    # return constant dummy output\n",
    "    docs = [\n",
    "        Document(\n",
    "            \"FooBar company just raised 1 Billion dollars!\",\n",
    "            metadata={\"source\": \"twitter\"},\n",
    "        ),\n",
    "        Document(\n",
    "            \"FooBar company is now only hiring AI's\", metadata={\"source\": \"twitter\"}\n",
    "        ),\n",
    "        Document(\n",
    "            \"FooBar company was founded in 2019\", metadata={\"source\": \"wikipedia\"}\n",
    "        ),\n",
    "        Document(\n",
    "            \"FooBar company makes friendly robots\", metadata={\"source\": \"wikipedia\"}\n",
    "        ),\n",
    "    ]\n",
    "    return \"\\n\\n\".join(doc.page_content for doc in docs), docs\n",
    "\n",
    "\n",
    "@tool(parse_docstring=True, response_format=\"content_and_artifact\")\n",
    "def cite_context_sources(\n",
    "    claim: str, state: Annotated[dict, InjectedState]\n",
    ") -> Tuple[str, List[Document]]:\n",
    "    \"\"\"Cite which source a claim was based on.\n",
    "\n",
    "    Args:\n",
    "        claim: The claim that was made.\n",
    "    \"\"\"\n",
    "    docs = []\n",
    "    # We get the potentially cited docs from past ToolMessages in our state.\n",
    "    for msg in state[\"messages\"]:\n",
    "        if isinstance(msg, ToolMessage) and msg.name == \"get_context\":\n",
    "            docs.extend(msg.artifact)\n",
    "\n",
    "    class Cite(BaseModel):\n",
    "        \"\"\"Return the index(es) of the documents that justify the claim\"\"\"\n",
    "\n",
    "        indexes: List[int]\n",
    "\n",
    "    structured_model = model.with_structured_output(Cite)\n",
    "    system = f\"Which of the following documents best justifies the claim:\\n\\n{claim}\"\n",
    "    context = \"\\n\\n\".join(\n",
    "        f\"Document {i}:\\n\" + doc.page_content for i, doc in enumerate(docs)\n",
    "    )\n",
    "    citation = structured_model.invoke([(\"system\", system), (\"human\", context)])\n",
    "    cited_docs = [docs[i] for i in citation.indexes]\n",
    "    sources = \", \".join(doc.metadata[\"source\"] for doc in cited_docs)\n",
    "    return sources, cited_docs"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1c2d0de0-0f3e-4bbe-b0b6-cc0f70b11993",
   "metadata": {},
   "source": [
    "If we look at the input schemas for these tools, we'll see that `state` is still listed:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "1092929b-c939-4b2a-9f9c-e725b0e34af2",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'title': 'cite_context_sourcesSchema',\n",
       " 'description': 'Cite which source a claim was based on.',\n",
       " 'type': 'object',\n",
       " 'properties': {'claim': {'title': 'Claim',\n",
       "   'description': 'The claim that was made.',\n",
       "   'type': 'string'},\n",
       "  'state': {'title': 'State', 'type': 'object'}},\n",
       " 'required': ['claim', 'state']}"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "cite_context_sources.get_input_schema().schema()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e346a26e-e00b-48e5-82c5-c930ea6084a4",
   "metadata": {},
   "source": [
    "But if we look at the tool call schema, which is what is passed to the model for tool-calling, `state` has been removed:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "3912bb51-3107-4335-a659-021c5d89fb37",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'title': 'cite_context_sources',\n",
       " 'description': 'Cite which source a claim was based on.',\n",
       " 'type': 'object',\n",
       " 'properties': {'claim': {'title': 'Claim',\n",
       "   'description': 'The claim that was made.',\n",
       "   'type': 'string'}},\n",
       " 'required': ['claim']}"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "cite_context_sources.tool_call_schema.schema()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8e8b9211-93d0-4ad5-aa7a-9c09099c53ff",
   "metadata": {},
   "source": [
    "## Define the agent state\n",
    "\n",
    "The main type of graph in `langgraph` is the `StateGraph`.\n",
    "This graph is parameterized by a state object that it passes around to each node.\n",
    "Each node then returns operations to update that state.\n",
    "These operations can either SET specific attributes on the state (e.g. overwrite the existing values) or ADD to the existing attribute.\n",
    "Whether to set or add is denoted by annotating the state object you construct the graph with.\n",
    "\n",
    "For this example, the state we will track will just be a list of messages.\n",
    "We want each node to just add messages to that list.\n",
    "Therefore, we will use a `TypedDict` with one key (`messages`) and annotate it so that the `messages` attribute is always added to.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "ea793afa-2eab-4901-910d-6eed90cd6564",
   "metadata": {},
   "outputs": [],
   "source": [
    "import operator\n",
    "from typing import Annotated, Sequence, TypedDict\n",
    "\n",
    "from langchain_core.messages import BaseMessage\n",
    "\n",
    "\n",
    "class AgentState(TypedDict):\n",
    "    messages: Annotated[Sequence[BaseMessage], operator.add]"
   ]
  },
  {
   "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/v0.2/docs/concepts/#langchain-expression-language-lcel).\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": 18,
   "id": "3b541bb9-900c-40d0-964d-7b5dfee30667",
   "metadata": {},
   "outputs": [],
   "source": [
    "from copy import deepcopy\n",
    "\n",
    "from langchain_core.messages import ToolMessage\n",
    "from langchain_openai import ChatOpenAI\n",
    "\n",
    "from langgraph.prebuilt import ToolNode\n",
    "\n",
    "model = ChatOpenAI(model=\"gpt-4o\", temperature=0)\n",
    "\n",
    "\n",
    "# Define the function that determines whether to continue or not\n",
    "def should_continue(state, config):\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",
    "tools = [get_context, cite_context_sources]\n",
    "\n",
    "# Define the function that calls the model\n",
    "def call_model(state, config):\n",
    "    messages = state[\"messages\"]\n",
    "    model_with_tools = model.bind_tools(tools)\n",
    "    response = model_with_tools.invoke(messages)\n",
    "    # We return a list, because this will get added to the existing list\n",
    "    return {\"messages\": [response]}\n",
    "\n",
    "\n",
    "# ToolNode will automatically take care of injecting state into tools\n",
    "tool_node = ToolNode(tools)"
   ]
  },
  {
   "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": 19,
   "id": "813ae66c-3b58-4283-a02a-36da72a2ab90",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langgraph.graph import END, START, StateGraph\n",
    "\n",
    "# Define a new graph\n",
    "workflow = StateGraph(AgentState)\n",
    "\n",
    "# Define the two nodes we will cycle between\n",
    "workflow.add_node(\"agent\", call_model)\n",
    "workflow.add_node(\"action\", tool_node)\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\")\n",
    "\n",
    "# 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()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "id": "a8afd6ef",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/jpeg": "[encoded data, 12480 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(app.get_graph(xray=True).draw_mermaid_png()))\n",
    "except Exception:\n",
    "    # This requires some extra dependencies and is optional\n",
    "    pass"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "547c3931-3dae-4281-ad4e-4b51305594d4",
   "metadata": {},
   "source": [
    "## Use it!\n",
    "\n",
    "We can now use it!\n",
    "This now exposes the [same interface](https://python.langchain.com/v0.2/docs/concepts/#langchain-expression-language-lcel) as all other LangChain runnables."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "id": "8edb04b9-40b6-46f1-a7a8-4b2d8aba7752",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Output from node 'agent':\n",
      "---\n",
      "{'messages': [AIMessage(content='', additional_kwargs={'tool_calls': [{'id': 'call_BidVTw5NiW2wp8Ez7m8dDoHI', 'function': {'arguments': '{\"question\":[\"latest news about FooBar\"]}', 'name': 'get_context'}, 'type': 'function'}]}, response_metadata={'token_usage': {'completion_tokens': 19, 'prompt_tokens': 87, 'total_tokens': 106}, 'model_name': 'gpt-4o-2024-05-13', 'system_fingerprint': 'fp_c4e5b6fa31', 'finish_reason': 'tool_calls', 'logprobs': None}, id='run-fcac1b73-563e-4f4c-b1b0-626f55d377be-0', tool_calls=[{'name': 'get_context', 'args': {'question': ['latest news about FooBar']}, 'id': 'call_BidVTw5NiW2wp8Ez7m8dDoHI', 'type': 'tool_call'}], usage_metadata={'input_tokens': 87, 'output_tokens': 19, 'total_tokens': 106})]}\n",
      "\n",
      "---\n",
      "\n",
      "Output from node 'action':\n",
      "---\n",
      "{'messages': [ToolMessage(content=\"FooBar company just raised 1 Billion dollars!\\n\\nFooBar company is now only hiring AI's\\n\\nFooBar company was founded in 2019\\n\\nFooBar company makes friendly robots\", name='get_context', tool_call_id='call_BidVTw5NiW2wp8Ez7m8dDoHI', artifact=[Document(metadata={'source': 'twitter'}, page_content='FooBar company just raised 1 Billion dollars!'), Document(metadata={'source': 'twitter'}, page_content=\"FooBar company is now only hiring AI's\"), Document(metadata={'source': 'wikipedia'}, page_content='FooBar company was founded in 2019'), Document(metadata={'source': 'wikipedia'}, page_content='FooBar company makes friendly robots')])]}\n",
      "\n",
      "---\n",
      "\n",
      "Output from node 'agent':\n",
      "---\n",
      "{'messages': [AIMessage(content='The latest news about FooBar is that the company has just raised 1 billion dollars!', response_metadata={'token_usage': {'completion_tokens': 19, 'prompt_tokens': 150, 'total_tokens': 169}, 'model_name': 'gpt-4o-2024-05-13', 'system_fingerprint': 'fp_c4e5b6fa31', 'finish_reason': 'stop', 'logprobs': None}, id='run-a8407471-7715-4c16-bd46-c29e5751e882-0', usage_metadata={'input_tokens': 150, 'output_tokens': 19, 'total_tokens': 169})]}\n",
      "\n",
      "---\n",
      "\n"
     ]
    }
   ],
   "source": [
    "from langchain_core.messages import HumanMessage\n",
    "\n",
    "messages = [HumanMessage(\"what's the latest news about FooBar\")]\n",
    "for output in app.stream({\"messages\": messages}):\n",
    "    # stream() yields dictionaries with output keyed by node name\n",
    "    for key, value in output.items():\n",
    "        print(f\"Output from node '{key}':\")\n",
    "        print(\"---\")\n",
    "        print(value)\n",
    "        messages.extend(value[\"messages\"])\n",
    "    print(\"\\n---\\n\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "id": "4a2128ed-e23f-4f25-a026-0c6590f01a1c",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Output from node 'agent':\n",
      "---\n",
      "{'messages': [AIMessage(content='', additional_kwargs={'tool_calls': [{'id': 'call_EB0zaQypXMqEUzaqwflUr0zH', 'function': {'arguments': '{\"claim\":\"FooBar company just raised 1 Billion dollars!\"}', 'name': 'cite_context_sources'}, 'type': 'function'}]}, response_metadata={'token_usage': {'completion_tokens': 25, 'prompt_tokens': 183, 'total_tokens': 208}, 'model_name': 'gpt-4o-2024-05-13', 'system_fingerprint': 'fp_c4e5b6fa31', 'finish_reason': 'tool_calls', 'logprobs': None}, id='run-b4952777-e2b3-4448-be87-200e6e80981b-0', tool_calls=[{'name': 'cite_context_sources', 'args': {'claim': 'FooBar company just raised 1 Billion dollars!'}, 'id': 'call_EB0zaQypXMqEUzaqwflUr0zH', 'type': 'tool_call'}], usage_metadata={'input_tokens': 183, 'output_tokens': 25, 'total_tokens': 208})]}\n",
      "\n",
      "---\n",
      "\n",
      "Output from node 'action':\n",
      "---\n",
      "{'messages': [ToolMessage(content='twitter', name='cite_context_sources', tool_call_id='call_EB0zaQypXMqEUzaqwflUr0zH', artifact=[Document(metadata={'source': 'twitter'}, page_content='FooBar company just raised 1 Billion dollars!')])]}\n",
      "\n",
      "---\n",
      "\n",
      "Output from node 'agent':\n",
      "---\n",
      "{'messages': [AIMessage(content='The information that FooBar company just raised 1 billion dollars comes from Twitter.', response_metadata={'token_usage': {'completion_tokens': 17, 'prompt_tokens': 218, 'total_tokens': 235}, 'model_name': 'gpt-4o-2024-05-13', 'system_fingerprint': 'fp_400f27fa1f', 'finish_reason': 'stop', 'logprobs': None}, id='run-a0dede05-dadd-46f6-8654-746520d4cef8-0', usage_metadata={'input_tokens': 218, 'output_tokens': 17, 'total_tokens': 235})]}\n",
      "\n",
      "---\n",
      "\n"
     ]
    }
   ],
   "source": [
    "messages.append(HumanMessage(\"where did you get this information?\"))\n",
    "for output in app.stream({\"messages\": messages}):\n",
    "    # stream() yields dictionaries with output keyed by node name\n",
    "    for key, value in output.items():\n",
    "        print(f\"Output from node '{key}':\")\n",
    "        print(\"---\")\n",
    "        print(value)\n",
    "    print(\"\\n---\\n\")"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "poetry-venv-311",
   "language": "python",
   "name": "poetry-venv-311"
  },
  "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
}
