{ "cells": [ { "cell_type": "markdown", "id": "b23ced4e-dc29-43be-9f94-0c36bb181b8a", "metadata": {}, "source": [ "# How to stream events from within a tool" ] }, { "cell_type": "markdown", "id": "7044eeb8-4074-4f9c-8a62-962488744557", "metadata": {}, "source": [ "If your LangGraph graph needs to use tools that call LLMs (or any other LangChain `Runnable` objects -- other graphs, LCEL chains, retrievers, etc.), you might want to stream events from the underlying `Runnable`. This guide shows how you can do that." ] }, { "cell_type": "markdown", "id": "a37f60af-43ea-4aa6-847a-df8cc47065f5", "metadata": {}, "source": [ "## Setup" ] }, { "cell_type": "code", "execution_count": 1, "id": "47f79af8-58d8-4a48-8d9a-88823d88701f", "metadata": {}, "outputs": [], "source": [ "%%capture --no-stderr\n", "%pip install -U langgraph langchain-openai" ] }, { "cell_type": "code", "execution_count": 2, "id": "0cf6b41d-7fcb-40b6-9a72-229cdd00a094", "metadata": {}, "outputs": [ { "name": "stdin", "output_type": "stream", "text": [ "OPENAI_API_KEY: ········\n" ] } ], "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": "e3d02ebb-c2e1-4ef7-b187-810d55139317", "metadata": {}, "source": [ "## Define graph and tools" ] }, { "cell_type": "markdown", "id": "d74a1760-a063-4d05-8c6f-9d16bc31fa82", "metadata": {}, "source": [ "We'll use a prebuilt ReAct agent for this guide" ] }, { "cell_type": "code", "execution_count": 3, "id": "083757a9-26d7-481e-8f3d-3e34bcba154b", "metadata": {}, "outputs": [], "source": [ "from langchain_core.callbacks import Callbacks\n", "from langchain_core.prompts import ChatPromptTemplate\n", "from langchain_core.tools import tool\n", "\n", "from langgraph.prebuilt import create_react_agent\n", "from langchain_openai import ChatOpenAI" ] }, { "cell_type": "markdown", "id": "9378fd4a-69e4-49e2-b34c-a98a0505ea35", "metadata": {}, "source": [ "
ASYNC IN PYTHON<=3.10
\n", "\n", "Any Langchain RunnableLambda, a RunnableGenerator, or Tool that invokes other runnables and is running async in python<=3.10, will have to propagate callbacks to child objects manually. This is because LangChain cannot automatically propagate callbacks to child objects in this case.\n", " \n", "This is a common reason why you may fail to see events being emitted from custom runnables or tools.\n", "
\n", "