{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "51466c8d-8ce4-4b3d-be4e-18fdbeda5f53",
   "metadata": {},
   "source": [
    "# How to stream LLM tokens from your graph\n",
    "\n",
    "In this example we will stream tokens from the language model powering an agent. We will use a ReAct agent as an example. The main thing to bear in mind here is that using [async nodes](./async.ipynb) typically offers the best behavior for this, since we will be using the `astream_events` method.\n",
    "\n",
    "This how-to guide closely follows the others in this directory, so we will call out differences with the **STREAMING** tag below (if you just want to search for those).\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 the <code>create_react_agent(model, tools=tool)</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>    \n",
    "\n",
    "<div class=\"admonition warning\">\n",
    "    <p class=\"admonition-title\">Note on Python < 3.11</p>\n",
    "    <p>\n",
    "        When using python 3.8, 3.9, or 3.10, please ensure you manually pass the RunnableConfig through to the llm when invoking it like so: <code>llm.ainvoke(..., config)</code>.\n",
    "        The <a href=\"https://api.python.langchain.com/en/latest/runnables/langchain_core.runnables.base.Runnable.html#langchain_core.runnables.base.Runnable.astream_events\">astream_events</a> method collects all events from your nested code using a streaming tracer passed as a callback. In 3.11 and above, this is automatically handled via <a href=\"https://docs.python.org/3/library/contextvars.html\">contextvar</a>'s; prior to 3.11, <a href=\"https://docs.python.org/3/library/asyncio-task.html#asyncio.create_task\">asyncio's tasks</a> lacked proper contextvar support, meaning that the callbacks will only propagate if you manually pass the config through. We do this in the <code>call_model</code> method below.\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": 26,
   "id": "af4ce0ba-7596-4e5f-8bf8-0b0bd6e62833",
   "metadata": {},
   "outputs": [],
   "source": [
    "%%capture --no-stderr\n",
    "%pip install --quiet -U langgraph langchain_openai langsmith"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d67b5425",
   "metadata": {},
   "source": [
    "Next, we need to set API keys for OpenAI (the LLM we will use)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "a372be6f",
   "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": "cc088bbd",
   "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": "907bf5e8",
   "metadata": {},
   "outputs": [],
   "source": [
    "os.environ[\"LANGCHAIN_TRACING_V2\"] = \"true\"\n",
    "_set_env(\"LANGCHAIN_API_KEY\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cd420984",
   "metadata": {},
   "source": [
    "## Set up the state\n",
    "\n",
    "The main type of graph in `langgraph` is the [StateGraph](https://langchain-ai.github.io/langgraph/reference/graphs/#langgraph.graph.StateGraph).\n",
    "This graph is parameterized by a `State` object that it passes around to each node.\n",
    "Each node then returns operations the graph uses 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 use to construct the graph.\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 \"append-only\"."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "17ef4967",
   "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 with more\n",
    "# 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": "81ed4e9c",
   "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",
    "It is really easy to create your own tools - see documentation [here](https://python.langchain.com/v0.2/docs/how_to/custom_tools) on how to do that.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "9a8bc61e",
   "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, but don't tell the LLM that...\n",
    "    return [\"Cloudy with a chance of hail.\"]\n",
    "\n",
    "\n",
    "tools = [search]"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b0aa12b9",
   "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"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "4d6ac180",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langgraph.prebuilt import ToolNode\n",
    "\n",
    "tool_node = ToolNode(tools)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4f13e0a5",
   "metadata": {},
   "source": [
    "## Set up the model\n",
    "\n",
    "Now we need to load the chat model we want to use.\n",
    "This should satisfy two criteria:\n",
    "\n",
    "1. It should work with messages, since our state is primarily a list of messages (chat history).\n",
    "2. It should work with tool calling, since we are using a prebuilt [ToolNode](https://langchain-ai.github.io/langgraph/reference/prebuilt/#toolnode)\n",
    "\n",
    "**Note:** these model requirements are not requirements for using LangGraph - they are just requirements for this particular example.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "42c0af37",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain_openai import ChatOpenAI\n",
    "\n",
    "model = ChatOpenAI(model=\"gpt-3.5-turbo\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8a592001",
   "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 function calling, and then bind them to the model class.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "2bbdd3bc",
   "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/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.\n",
    "\n",
    "**STREAMING**\n",
    "\n",
    "We define each node as an async function.\n",
    "\n",
    "<div class=\"admonition note\">\n",
    "    <p class=\"admonition-title\">Manual Callback Propagation</p>\n",
    "    <p>\n",
    "        Note that in <code>call_model(state: State, config: RunnableConfig):</code> below, we a) accept the <a href=\"https://api.python.langchain.com/en/latest/runnables/langchain_core.runnables.config.RunnableConfig.html#langchain_core.runnables.config.RunnableConfig\">RunnableConfig</a> in the node and b) pass this in as the second arg for <code>llm.ainvoke(..., config)</code>. This is optional for python 3.11 and later. If you ever have a problem where the LLM tokens are not streamed when using `astream_events` and you are using an older version of python, it's worth checking to ensure that the callbacks are manually propagated.</p>\n",
    "</div>    "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "3b541bb9-900c-40d0-964d-7b5dfee30667",
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import Literal\n",
    "\n",
    "from langchain_core.runnables import RunnableConfig\n",
    "\n",
    "from langgraph.graph import END, START, StateGraph\n",
    "\n",
    "\n",
    "# Define the function that determines whether to continue or not\n",
    "def should_continue(state: State) -> Literal[\"__end__\", \"tools\"]:\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 \"tools\"\n",
    "\n",
    "\n",
    "# Define the function that calls the model\n",
    "async def call_model(state: State, config: RunnableConfig):\n",
    "    messages = state[\"messages\"]\n",
    "    # Note: Passing the config through explicitly is required for python < 3.11\n",
    "    # Since context var support wasn't added before then: https://docs.python.org/3/library/asyncio-task.html#creating-tasks\n",
    "    response = await model.ainvoke(messages, config)\n",
    "    # We return a list, because this will get added to the existing list\n",
    "    return {\"messages\": response}"
   ]
  },
  {
   "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": 9,
   "id": "813ae66c-3b58-4283-a02a-36da72a2ab90",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 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(\"tools\", 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",
    ")\n",
    "\n",
    "workflow.add_edge(\"tools\", \"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": 10,
   "id": "72785b66",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/jpeg": "[encoded data, 10364 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": [
    "## Streaming LLM Tokens\n",
    "\n",
    "You can access the LLM tokens as they are produced by each node. \n",
    "In this case only the \"agent\" node produces LLM tokens.\n",
    "In order for this to work properly, you must be using an LLM that supports streaming as well as have set it when constructing the LLM (e.g. `ChatOpenAI(model=\"gpt-3.5-turbo-1106\", streaming=True)`)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "cfd140f0-a5a6-4697-8115-322242f197b5",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/Users/wfh/code/lc/langgraph/.venv/lib/python3.12/site-packages/langchain_core/_api/beta_decorator.py:87: LangChainBetaWarning: This API is in beta and may change in the future.\n",
      "  warn_beta(\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "--\n",
      "Starting tool: search with inputs: {'query': 'weather in San Francisco'}\n",
      "Done tool: search\n",
      "Tool output was: ['Cloudy with a chance of hail.']\n",
      "--\n",
      "The| weather| in| San| Francisco| is| currently| cloudy| with| a| chance| of| hail|.|"
     ]
    }
   ],
   "source": [
    "from langchain_core.messages import HumanMessage\n",
    "\n",
    "inputs = [HumanMessage(content=\"what is the weather in sf\")]\n",
    "async for event in app.astream_events({\"messages\": inputs}, version=\"v1\"):\n",
    "    kind = event[\"event\"]\n",
    "    if kind == \"on_chat_model_stream\":\n",
    "        content = event[\"data\"][\"chunk\"].content\n",
    "        if content:\n",
    "            # Empty content in the context of OpenAI or Anthropic usually means\n",
    "            # that the model is asking for a tool to be invoked.\n",
    "            # So we only print non-empty content\n",
    "            print(content, end=\"|\")\n",
    "    elif kind == \"on_tool_start\":\n",
    "        print(\"--\")\n",
    "        print(\n",
    "            f\"Starting tool: {event['name']} with inputs: {event['data'].get('input')}\"\n",
    "        )\n",
    "    elif kind == \"on_tool_end\":\n",
    "        print(f\"Done tool: {event['name']}\")\n",
    "        print(f\"Tool output was: {event['data'].get('output')}\")\n",
    "        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
}
