mirror of
https://github.com/langchain-ai/langgraph.git
synced 2026-08-20 14:42:28 +02:00
3079 lines
196 KiB
Plaintext
3079 lines
196 KiB
Plaintext
{
|
|
"cells": [
|
|
{
|
|
"cell_type": "markdown",
|
|
"id": "4a1aae78-88a6-4133-b905-7e46c8e3772f",
|
|
"metadata": {},
|
|
"source": [
|
|
"# Quick Start\n",
|
|
"\n",
|
|
"In this comprehensive quick start, we will build a support chatbot in LangGraph that can:\n",
|
|
"\n",
|
|
"- Answer common questions by searching the web\n",
|
|
"- Maintain conversation state across calls\n",
|
|
"- Route complex queries to a human for review\n",
|
|
"- Use custom state to control its behavior\n",
|
|
"- Rewind and explore alternative conversation paths\n",
|
|
"\n",
|
|
"We'll start with a basic chatbot and progressively add more sophisticated capabilities, introducing key LangGraph concepts along the way.\n",
|
|
"\n",
|
|
"## Setup\n",
|
|
"\n",
|
|
"First, install the required packages:"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"id": "6f11d631-8679-4f28-822f-cdf1f2ddc21c",
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"%%capture --no-stderr\n",
|
|
"%pip install -U langgraph langsmith\n",
|
|
"\n",
|
|
"# Used for this tutorial; not a requirement for LangGraph\n",
|
|
"%pip install -U langchain_anthropic"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"id": "a6d1e870-1bc0-4d44-86c0-96681ccf6113",
|
|
"metadata": {},
|
|
"source": [
|
|
"Next, set your API keys:"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 1,
|
|
"id": "705d4020-6ee8-44cc-b1a5-8c34e7172fc7",
|
|
"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": "a98c72cf-33f9-4a37-9634-6c93a7c28815",
|
|
"metadata": {},
|
|
"source": [
|
|
"(Encouraged) [LangSmith](https://smith.langchain.com/) makes it a lot easier to see what's going on \"under the hood.\""
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 2,
|
|
"id": "13cba9af-0572-41df-92f8-d6f56d5b5322",
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"_set_env(\"LANGSMITH_API_KEY\")\n",
|
|
"os.environ[\"LANGCHAIN_TRACING_V2\"] = \"true\"\n",
|
|
"os.environ[\"LANGCHAIN_PROJECT\"] = \"LangGraph Tutorial\""
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"id": "ef7bcad1-1274-4b7c-a2e9-365180ef3a31",
|
|
"metadata": {},
|
|
"source": [
|
|
"## Part 1: Build a Basic Chatbot\n",
|
|
"\n",
|
|
"We'll first create a simple chatbot using LangGraph. This chatbot will respond directly to user messages. Though simple, it will illustrate the core concepts of building with LangGraph. By the end of this section, you will have a built rudimentary chatbot.\n",
|
|
"\n",
|
|
"Start by creating a `StateGraph`. A `StateGraph` object defines the structure of our chatbot as a \"state machine\". We'll add `nodes` to represent the llm and functions our chatbot can call and `edges` to specify how the bot should transition between these functions."
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 3,
|
|
"id": "e58df974-7579-4f25-9d91-66389b94eba2",
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"from typing import Annotated\n",
|
|
"\n",
|
|
"from typing_extensions import TypedDict\n",
|
|
"\n",
|
|
"from langgraph.graph import StateGraph, START, END\n",
|
|
"from langgraph.graph.message import add_messages\n",
|
|
"\n",
|
|
"\n",
|
|
"class State(TypedDict):\n",
|
|
" # Messages have the type \"list\". The `add_messages` function\n",
|
|
" # in the annotation defines how this state key should be updated\n",
|
|
" # (in this case, it appends messages to the list, rather than overwriting them)\n",
|
|
" messages: Annotated[list, add_messages]\n",
|
|
"\n",
|
|
"\n",
|
|
"graph_builder = StateGraph(State)"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"id": "4137feed-746e-4c72-a34a-f7a699ad5dcf",
|
|
"metadata": {},
|
|
"source": [
|
|
"**Notice** that we've defined our `State` as a TypedDict with a single key: `messages`. The `messages` key is annotated with the [`add_messages`](https://langchain-ai.github.io/langgraph/reference/graphs/?h=add+messages#add_messages) function, which tells LangGraph to append new messages to the existing list, rather than overwriting it.\n",
|
|
"\n",
|
|
"So now our graph knows two things:\n",
|
|
"\n",
|
|
"1. Every `node` we define will receive the current `State` as input and return a value that updates that state.\n",
|
|
"2. `messages` will be _appended_ to the current list, rather than directly overwritten. This is communicated via the prebuilt [`add_messages`](https://langchain-ai.github.io/langgraph/reference/graphs/?h=add+messages#add_messages) function in the `Annotated` syntax.\n",
|
|
"\n",
|
|
"Next, add a \"`chatbot`\" node. Nodes represent units of work. They are typically regular python functions."
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 4,
|
|
"id": "bc8c9137-8261-42ea-8e83-3590981d23e2",
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"from langchain_anthropic import ChatAnthropic\n",
|
|
"\n",
|
|
"llm = ChatAnthropic(model=\"claude-3-haiku-20240307\")\n",
|
|
"\n",
|
|
"\n",
|
|
"def chatbot(state: State):\n",
|
|
" return {\"messages\": [llm.invoke(state[\"messages\"])]}\n",
|
|
"\n",
|
|
"\n",
|
|
"# The first argument is the unique node name\n",
|
|
"# The second argument is the function or object that will be called whenever\n",
|
|
"# the node is used.\n",
|
|
"graph_builder.add_node(\"chatbot\", chatbot)"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"id": "b6c1dcd9-fb86-4649-81b4-ff6ce20a2e46",
|
|
"metadata": {},
|
|
"source": [
|
|
"**Notice** how the `chatbot` node function takes the current `State` as input and returns an updated `messages` list. This is the basic pattern for all LangGraph node functions.\n",
|
|
"\n",
|
|
"The `add_messages` function in our `State` will append the llm's response messages to whatever messages are already in the state.\n",
|
|
"\n",
|
|
"Next, add an `entry` point. This tells our graph **where to start its work** each time we run it."
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 5,
|
|
"id": "e331e10d-ebcf-4144-9bd3-999b4d656dd3",
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"graph_builder.add_edge(START, \"chatbot\")"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"id": "0499c318-d1e6-46fa-a652-8f9e65313355",
|
|
"metadata": {},
|
|
"source": [
|
|
"Similarly, set a `finish` point. This instructs the graph **\"any time this node is run, you can exit.\"**"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 6,
|
|
"id": "075f0929-3591-4852-b2d3-eaadde40662d",
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"graph_builder.add_edge(\"chatbot\", END)"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"id": "65a9b88c-2c53-4d95-8eb1-d544a8946f65",
|
|
"metadata": {},
|
|
"source": [
|
|
"Finally, we'll want to be able to run our graph. To do so, call \"`compile()`\" on the graph builder. This creates a \"`CompiledGraph`\" we can use invoke on our state."
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 7,
|
|
"id": "0bb67a01-cf5c-4625-8c07-6e8c0af50fca",
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"graph = graph_builder.compile()"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"id": "0c39407b-d6f6-48a4-b1f6-31fc7f88b275",
|
|
"metadata": {},
|
|
"source": [
|
|
"You can visualize the graph using the `get_graph` method and one of the \"draw\" methods, like `draw_ascii` or `draw_png`. The `draw` methods each require additional dependencies."
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 8,
|
|
"id": "32e4f36e-72ce-4ade-bd7e-94880e0d456b",
|
|
"metadata": {},
|
|
"outputs": [
|
|
{
|
|
"data": {
|
|
"image/jpeg": "/9j/4AAQSkZJRgABAQAAAQABAAD/4gHYSUNDX1BST0ZJTEUAAQEAAAHIAAAAAAQwAABtbnRyUkdCIFhZWiAH4AABAAEAAAAAAABhY3NwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAA9tYAAQAAAADTLQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAlkZXNjAAAA8AAAACRyWFlaAAABFAAAABRnWFlaAAABKAAAABRiWFlaAAABPAAAABR3dHB0AAABUAAAABRyVFJDAAABZAAAAChnVFJDAAABZAAAAChiVFJDAAABZAAAAChjcHJ0AAABjAAAADxtbHVjAAAAAAAAAAEAAAAMZW5VUwAAAAgAAAAcAHMAUgBHAEJYWVogAAAAAAAAb6IAADj1AAADkFhZWiAAAAAAAABimQAAt4UAABjaWFlaIAAAAAAAACSgAAAPhAAAts9YWVogAAAAAAAA9tYAAQAAAADTLXBhcmEAAAAAAAQAAAACZmYAAPKnAAANWQAAE9AAAApbAAAAAAAAAABtbHVjAAAAAAAAAAEAAAAMZW5VUwAAACAAAAAcAEcAbwBvAGcAbABlACAASQBuAGMALgAgADIAMAAxADb/2wBDAAMCAgMCAgMDAwMEAwMEBQgFBQQEBQoHBwYIDAoMDAsKCwsNDhIQDQ4RDgsLEBYQERMUFRUVDA8XGBYUGBIUFRT/2wBDAQMEBAUEBQkFBQkUDQsNFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBT/wAARCADaAGIDASIAAhEBAxEB/8QAHQABAAMBAQADAQAAAAAAAAAAAAUGBwgE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D4v2jB97arX6vrNFFFZU4nX0ovKE9j0O27M68z8kKUpXUvBWaZN/SZJ+yI3/NIrS6zTJv6TJP2RG/5pFazP0Jvd9UVvSPskz5eaP7pVaynZpiWcSmZOQ41ar3IZRybbtwhtvKQnXXdBUDoNTrUL+9/2Z6Acwcc0HHT5sZ0+7Xm1o72eFSgpi3l/pWPCSxO5XyPht3hwrtdYFivHyu4QLFJcYmrZUy40XGVNqSsrQVg7qSCQVCqRf8ACLfdsFuV1xrGszTc5l9srUhWSGY/LksR5jTm+lD61uJbQFuakhOmij0ca37FMAxnBRKGOWC22ISt0vi3xUM8ru67u9uga6bytNfSan66KZopJbiRDaHAlDDsXy31xXec3bc9nmRZll20VizW2Q8J+G29plZQUMy3mpz7q44cI3d9Tfk6a8A4NdAambLkMrPtuGDXaLiOSWK226yXJiQu72pyK2y4tUbda1I018hWhHA6eSTodN4rwXyxW7JrVItl2gx7nbpAAeiy2g424AQRvJPA8QD+yl5hRr82BWj0VC1+NUZ76VQUbAdmjZ1TgOOJOhGotjI4EaEfyfRX3W/Ybs7tM+NOhYPj8SZGdS8w+zbmkrbWkgpUkhOoIIBBHorn6PE4Ul8Xl/pYco/B8X7Rg+9tVr9ZBlH4Pi/aMH3tqtfq/snsq+KLyhPXdDezP4n5IUpSu5eiqzkOAQMiuwuTsqdElBhMcqhv8mFISpSgCND51q/zqzUraGJw7DDSiVGqopPiqg9cXvtvwp4qoPXF77b8Ku1K2vH2ZI5XMrkWSKT4qoPXF77b8KeKqD1xe+2/CrtSl4+zJC5lciyRSfFVB64vfbfhTxVQeuL3234VdqUvH2ZIXMrkWSKT4qoPXF77b8KeKqD1xe+2/CrtSl4+zJC5lciyRSRsnthdYW7cbtISy82+G3peqCpCwtOo04jVIq7UpWIo3EqM6QwwwKkKoKUpWhsf/9k=",
|
|
"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(graph.get_graph().draw_mermaid_png()))\n",
|
|
"except Exception:\n",
|
|
" # This requires some extra dependencies and is optional\n",
|
|
" pass"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"id": "a98097a3-a126-4081-b21e-697ec1185fff",
|
|
"metadata": {},
|
|
"source": [
|
|
"Now let's run the chatbot! \n",
|
|
"\n",
|
|
"**Tip:** You can exit the chat loop at any time by typing \"quit\", \"exit\", or \"q\"."
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 9,
|
|
"id": "7afb4c9a-7404-4e92-9945-36f372015f08",
|
|
"metadata": {},
|
|
"outputs": [
|
|
{
|
|
"name": "stdout",
|
|
"output_type": "stream",
|
|
"text": [
|
|
"User: what's langgraph all about?\n"
|
|
]
|
|
},
|
|
{
|
|
"name": "stdout",
|
|
"output_type": "stream",
|
|
"text": [
|
|
"Assistant: LangGraph is a new open-source deep learning framework that focuses on enabling efficient training and deployment of large language models. Some key things to know about LangGraph:\n",
|
|
"\n",
|
|
"1. Efficient Training: LangGraph is designed to accelerate the training of large language models by leveraging advanced optimization techniques and parallelization strategies.\n",
|
|
"\n",
|
|
"2. Modular Architecture: LangGraph has a modular architecture that allows for easy customization and extension of language models, making it flexible for a variety of NLP tasks.\n",
|
|
"\n",
|
|
"3. Hardware Acceleration: The framework is optimized for both CPU and GPU hardware, allowing for efficient model deployment on a wide range of devices.\n",
|
|
"\n",
|
|
"4. Scalability: LangGraph is designed to handle large-scale language models with billions of parameters, enabling the development of state-of-the-art NLP applications.\n",
|
|
"\n",
|
|
"5. Open-Source: LangGraph is an open-source project, allowing developers and researchers to collaborate, contribute, and build upon the framework.\n",
|
|
"\n",
|
|
"6. Performance: The goal of LangGraph is to provide superior performance and efficiency compared to existing deep learning frameworks, particularly for training and deploying large language models.\n",
|
|
"\n",
|
|
"Overall, LangGraph is a promising new deep learning framework that aims to address the challenges of building and deploying advanced natural language processing models at scale. It is an active area of research and development, with the potential to drive further advancements in the field of language AI.\n"
|
|
]
|
|
},
|
|
{
|
|
"name": "stdout",
|
|
"output_type": "stream",
|
|
"text": [
|
|
"User: hm that doesn't seem right...\n"
|
|
]
|
|
},
|
|
{
|
|
"name": "stdout",
|
|
"output_type": "stream",
|
|
"text": [
|
|
"Assistant: I'm sorry, I don't have enough context to determine what doesn't seem right. Could you please provide more details about what you're referring to? That would help me better understand and respond appropriately.\n"
|
|
]
|
|
},
|
|
{
|
|
"name": "stdout",
|
|
"output_type": "stream",
|
|
"text": [
|
|
"User: q\n"
|
|
]
|
|
},
|
|
{
|
|
"name": "stdout",
|
|
"output_type": "stream",
|
|
"text": [
|
|
"Goodbye!\n"
|
|
]
|
|
}
|
|
],
|
|
"source": [
|
|
"while True:\n",
|
|
" user_input = input(\"User: \")\n",
|
|
" if user_input.lower() in [\"quit\", \"exit\", \"q\"]:\n",
|
|
" print(\"Goodbye!\")\n",
|
|
" break\n",
|
|
" for event in graph.stream({\"messages\": (\"user\", user_input)}):\n",
|
|
" for value in event.values():\n",
|
|
" print(\"Assistant:\", value[\"messages\"][-1].content)"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"id": "98e1cdb5-869a-41ea-9dab-e28cfc524499",
|
|
"metadata": {},
|
|
"source": [
|
|
"**Congratulations!** You've built your first chatbot using LangGraph. This bot can engage in basic conversation by taking user input and generating responses using an LLM. You can inspect a [LangSmith Trace](https://smith.langchain.com/public/29ab0177-1177-4d25-9341-17ae7d94e0e0/r) for the call above at the provided link.\n",
|
|
"\n",
|
|
"However, you may have noticed that the bot's knowledge is limited to what's in its training data. In the next part, we'll add a web search tool to expand the bot's knowledge and make it more capable.\n",
|
|
"\n",
|
|
"Below is the full code for this section for your reference:\n",
|
|
"\n",
|
|
"<details>\n",
|
|
"<summary>Full Code</summary>\n",
|
|
" <pre>\n",
|
|
" \n",
|
|
"```python\n",
|
|
"from typing import Annotated\n",
|
|
"\n",
|
|
"from langchain_anthropic import ChatAnthropic\n",
|
|
"from typing_extensions import TypedDict\n",
|
|
"\n",
|
|
"from langgraph.graph import StateGraph\n",
|
|
"from langgraph.graph.message import add_messages\n",
|
|
"\n",
|
|
"\n",
|
|
"class State(TypedDict):\n",
|
|
" messages: Annotated[list, add_messages]\n",
|
|
"\n",
|
|
"\n",
|
|
"graph_builder = StateGraph(State)\n",
|
|
"\n",
|
|
"\n",
|
|
"llm = ChatAnthropic(model=\"claude-3-haiku-20240307\")\n",
|
|
"\n",
|
|
"\n",
|
|
"def chatbot(state: State):\n",
|
|
" return {\"messages\": [llm.invoke(state[\"messages\"])]}\n",
|
|
"\n",
|
|
"\n",
|
|
"# The first argument is the unique node name\n",
|
|
"# The second argument is the function or object that will be called whenever\n",
|
|
"# the node is used.\n",
|
|
"graph_builder.add_node(\"chatbot\", chatbot)\n",
|
|
"graph_builder.set_entry_point(\"chatbot\")\n",
|
|
"graph_builder.set_finish_point(\"chatbot\")\n",
|
|
"graph = graph_builder.compile()\n",
|
|
"```\n",
|
|
"\n",
|
|
"</pre>\n",
|
|
"</details>"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"id": "f22c5d4a-3134-413c-81fe-dd9752fbeb66",
|
|
"metadata": {},
|
|
"source": [
|
|
"## Part 2: Enhancing the Chatbot with Tools\n",
|
|
"\n",
|
|
"To handle queries our chatbot can't answer \"from memory\", we'll integrate a web search tool. Our bot can use this tool to find relevant information and provide better responses.\n",
|
|
"\n",
|
|
"#### Requirements\n",
|
|
"\n",
|
|
"Before we start, make sure you have the necessary packages installed and API keys set up:\n",
|
|
"\n",
|
|
"First, install the requirements to use the [Tavily Search Engine](https://python.langchain.com/v0.2/docs/integrations/tools/tavily_search/), and set your [TAVILY_API_KEY](https://tavily.com/)."
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"id": "7451151f-41fc-4af0-9359-024ae51b7225",
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"%%capture --no-stderr\n",
|
|
"%pip install -U tavily-python\n",
|
|
"%pip install -U langchain_community"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 3,
|
|
"id": "0c52923c-5665-4f8c-a1ba-9799e369c49e",
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"_set_env(\"TAVILY_API_KEY\")"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"id": "591ce9ba-c431-4165-b815-25c944ef7cdb",
|
|
"metadata": {},
|
|
"source": [
|
|
"Next, define the tool:"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 4,
|
|
"id": "35c8978e-c07d-4dd0-a97b-0ce3a723eea5",
|
|
"metadata": {},
|
|
"outputs": [
|
|
{
|
|
"data": {
|
|
"text/plain": [
|
|
"[{'url': 'https://medium.com/@cplog/introduction-to-langgraph-a-beginners-guide-14f9be027141',\n",
|
|
" 'content': 'Nodes: Nodes are the building blocks of your LangGraph. Each node represents a function or a computation step. You define nodes to perform specific tasks, such as processing input, making ...'},\n",
|
|
" {'url': 'https://js.langchain.com/docs/langgraph',\n",
|
|
" 'content': \"Assuming you have done the above Quick Start, you can build off it like:\\nHere, we manually define the first tool call that we will make.\\nNotice that it does that same thing as agent would have done (adds the agentOutcome key).\\n LangGraph\\n🦜🕸️LangGraph.js\\n⚡ Building language agents as graphs ⚡\\nOverview\\u200b\\nLangGraph is a library for building stateful, multi-actor applications with LLMs, built on top of (and intended to be used with) LangChain.js.\\n Therefore, we will use an object with one key (messages) with the value as an object: { value: Function, default?: () => any }\\nThe default key must be a factory that returns the default value for that attribute.\\n Streaming Node Output\\u200b\\nOne of the benefits of using LangGraph is that it is easy to stream output as it's produced by each node.\\n What this means is that only one of the downstream edges will be taken, and which one that is depends on the results of the start node.\\n\"}]"
|
|
]
|
|
},
|
|
"execution_count": 4,
|
|
"metadata": {},
|
|
"output_type": "execute_result"
|
|
}
|
|
],
|
|
"source": [
|
|
"from langchain_community.tools.tavily_search import TavilySearchResults\n",
|
|
"\n",
|
|
"tool = TavilySearchResults(max_results=2)\n",
|
|
"tools = [tool]\n",
|
|
"tool.invoke(\"What's a 'node' in LangGraph?\")"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"id": "7f503f02-d23d-42e8-9b5d-eb2681b242f4",
|
|
"metadata": {},
|
|
"source": [
|
|
"The results are page summaries our chat bot can use to answer questions.\n",
|
|
"\n",
|
|
"\n",
|
|
"Next, we'll start defining our graph. The following is all **the same as in Part 1**, except we have added `bind_tools` on our LLM. This lets the LLM know the correct JSON format to use if it wants to use our search engine."
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 11,
|
|
"id": "dc5af88b-47d2-43bf-9a2c-6c07506b1732",
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"from typing import Annotated\n",
|
|
"\n",
|
|
"from langchain_anthropic import ChatAnthropic\n",
|
|
"from typing_extensions import TypedDict\n",
|
|
"\n",
|
|
"from langgraph.graph import StateGraph, START\n",
|
|
"from langgraph.graph.message import add_messages\n",
|
|
"\n",
|
|
"\n",
|
|
"class State(TypedDict):\n",
|
|
" messages: Annotated[list, add_messages]\n",
|
|
"\n",
|
|
"\n",
|
|
"graph_builder = StateGraph(State)\n",
|
|
"\n",
|
|
"\n",
|
|
"llm = ChatAnthropic(model=\"claude-3-haiku-20240307\")\n",
|
|
"# Modification: tell the LLM which tools it can call\n",
|
|
"llm_with_tools = llm.bind_tools(tools)\n",
|
|
"\n",
|
|
"\n",
|
|
"def chatbot(state: State):\n",
|
|
" return {\"messages\": [llm_with_tools.invoke(state[\"messages\"])]}\n",
|
|
"\n",
|
|
"\n",
|
|
"graph_builder.add_node(\"chatbot\", chatbot)"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"id": "d1e84cfc-b1b2-48e3-8550-152a408c3926",
|
|
"metadata": {},
|
|
"source": [
|
|
"Next we need to create a function to actually run the tools if they are called. We'll do this by adding the tools to a new node.\n",
|
|
"\n",
|
|
"Below, implement a `BasicToolNode` that checks the most recent message in the state and calls tools if the message contains `tool_calls`. It relies on the LLM's `tool_calling` support, which is available in Anthropic, OpenAI, Google Gemini, and a number of other LLM providers.\n",
|
|
"\n",
|
|
"We will later replace this with LangGraph's prebuilt [ToolNode](https://langchain-ai.github.io/langgraph/reference/prebuilt/#toolnode) to speed things up, but building it ourselves first is instructive."
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 12,
|
|
"id": "12f1fc14-cd91-4cd4-9f2e-1d007f8beafc",
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"import json\n",
|
|
"\n",
|
|
"from langchain_core.messages import ToolMessage\n",
|
|
"\n",
|
|
"\n",
|
|
"class BasicToolNode:\n",
|
|
" \"\"\"A node that runs the tools requested in the last AIMessage.\"\"\"\n",
|
|
"\n",
|
|
" def __init__(self, tools: list) -> None:\n",
|
|
" self.tools_by_name = {tool.name: tool for tool in tools}\n",
|
|
"\n",
|
|
" def __call__(self, inputs: dict):\n",
|
|
" if messages := inputs.get(\"messages\", []):\n",
|
|
" message = messages[-1]\n",
|
|
" else:\n",
|
|
" raise ValueError(\"No message found in input\")\n",
|
|
" outputs = []\n",
|
|
" for tool_call in message.tool_calls:\n",
|
|
" tool_result = self.tools_by_name[tool_call[\"name\"]].invoke(\n",
|
|
" tool_call[\"args\"]\n",
|
|
" )\n",
|
|
" outputs.append(\n",
|
|
" ToolMessage(\n",
|
|
" content=json.dumps(tool_result),\n",
|
|
" name=tool_call[\"name\"],\n",
|
|
" tool_call_id=tool_call[\"id\"],\n",
|
|
" )\n",
|
|
" )\n",
|
|
" return {\"messages\": outputs}\n",
|
|
"\n",
|
|
"\n",
|
|
"tool_node = BasicToolNode(tools=[tool])\n",
|
|
"graph_builder.add_node(\"tools\", tool_node)"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"id": "b049afc4-7757-40ba-8e00-589d378e816d",
|
|
"metadata": {},
|
|
"source": [
|
|
"With the tool node added, we can define the `conditional_edges`. \n",
|
|
"\n",
|
|
"Recall that **edges** route the control flow from one node to the next. **Conditional edges** usually contain \"if\" statements to route to different nodes depending on the current graph state. These functions receive the current graph `state` and return a string or list of strings indicating which node(s) to call next.\n",
|
|
"\n",
|
|
"Below, call define a router function called `route_tools`, that checks for tool_calls in the chatbot's output. Provide this function to the graph by calling `add_conditional_edges`, which tells the graph that whenever the `chatbot` node completes to check this function to see where to go next. \n",
|
|
"\n",
|
|
"The condition will route to `tools` if tool calls are present and \"`__end__`\" if not.\n",
|
|
"\n",
|
|
"Later, we will replace this with the prebuilt [tools_condition](https://langchain-ai.github.io/langgraph/reference/prebuilt/#tools_condition) to be more concise, but implementing it ourselves first makes things more clear. "
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 13,
|
|
"id": "d662df94-66ac-4c6c-92f0-4c93620f1c74",
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"from typing import Literal\n",
|
|
"\n",
|
|
"\n",
|
|
"def route_tools(\n",
|
|
" state: State,\n",
|
|
") -> Literal[\"tools\", \"__end__\"]:\n",
|
|
" \"\"\"\n",
|
|
" Use in the conditional_edge to route to the ToolNode if the last message\n",
|
|
" has tool calls. Otherwise, route to the end.\n",
|
|
" \"\"\"\n",
|
|
" if isinstance(state, list):\n",
|
|
" ai_message = state[-1]\n",
|
|
" elif messages := state.get(\"messages\", []):\n",
|
|
" ai_message = messages[-1]\n",
|
|
" else:\n",
|
|
" raise ValueError(f\"No messages found in input state to tool_edge: {state}\")\n",
|
|
" if hasattr(ai_message, \"tool_calls\") and len(ai_message.tool_calls) > 0:\n",
|
|
" return \"tools\"\n",
|
|
" return \"__end__\"\n",
|
|
"\n",
|
|
"\n",
|
|
"# The `tools_condition` function returns \"tools\" if the chatbot asks to use a tool, and \"__end__\" if\n",
|
|
"# it is fine directly responding. This conditional routing defines the main agent loop.\n",
|
|
"graph_builder.add_conditional_edges(\n",
|
|
" \"chatbot\",\n",
|
|
" route_tools,\n",
|
|
" # The following dictionary lets you tell the graph to interpret the condition's outputs as a specific node\n",
|
|
" # It defaults to the identity function, but if you\n",
|
|
" # want to use a node named something else apart from \"tools\",\n",
|
|
" # You can update the value of the dictionary to something else\n",
|
|
" # e.g., \"tools\": \"my_tools\"\n",
|
|
" {\"tools\": \"tools\", \"__end__\": \"__end__\"},\n",
|
|
")\n",
|
|
"# Any time a tool is called, we return to the chatbot to decide the next step\n",
|
|
"graph_builder.add_edge(\"tools\", \"chatbot\")\n",
|
|
"graph_builder.add_edge(START, \"chatbot\")\n",
|
|
"graph = graph_builder.compile()"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"id": "a2aa67c2-dd1b-4bf2-8c64-eea44296d15f",
|
|
"metadata": {},
|
|
"source": [
|
|
"**Notice** that conditional edges start from a single node. This tells the graph \"any time the '`chatbot`' node runs, either go to 'tools' if it calls a tool, or end the loop if it responds directly. \n",
|
|
"\n",
|
|
"Like the prebuilt `tools_condition`, our function returns the \"`__end__`\" string if no tool calls are made. When the graph transitions to `__end__`, it has no more tasks to complete and ceases execution. Because the condition can return `__end__`, we don't need to explicitly set a `finish_point` this time. Our graph already has a way to finish!\n",
|
|
"\n",
|
|
"Let's visualize the graph we've built. The following function has some additional dependencies to run that are unimportant for this tutorial."
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 14,
|
|
"id": "8b49509c-9d97-457c-a76a-c495fb30ccbc",
|
|
"metadata": {},
|
|
"outputs": [
|
|
{
|
|
"data": {
|
|
"image/jpeg": "/9j/4AAQSkZJRgABAQAAAQABAAD/4gHYSUNDX1BST0ZJTEUAAQEAAAHIAAAAAAQwAABtbnRyUkdCIFhZWiAH4AABAAEAAAAAAABhY3NwAAAAAAAAAAAAAAAAAAAAAAAAAAAAA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UviV1yrDLI9a4k65fE19iXWXAtchTEuTHb5w4llaVJIcHOFp0oElA0d6ref7PvDLf8AMb/7Wz/61vcV4b4rgz772O45a7G7ISEOrt8RDJcSDsBRSBsCucmou6OZCUaclOLd15f6c95lhNtyXhZndzxzGc6XfXocW3oXkypz8mS0JKHS2y0+ta9IIJJ5QOp1vrUo414Df804g5BGs8WQj4w4e3C2tTeRSWDIVJaKGVOa5QpQ5uhO9FR7t1f8ASpYrRYtJkmmt19ufD+jnSyXubmHETg6I+EZHj0ewtTmp3xhanGI8QmEW0oDmuVSeYaSoeienXZ1XRdY1xt0W8W+TBnR2pkKS2pl+O+gLQ6hQ0pKknoQQSCDUJHk/8MwQRgGOAjuItjP/AK1FyUtuRCc4VLXyt897fHzJ/Wizn+CVz/5X+orQRuA3DeHIafYwTHWX2lBbbiLYyFJUDsEHl6EGt/nP8Ern/wAr/UVsaJbvNO3MvUzQUcaGq969fiXLSlK7h9GFKUoCL3PhvYbnJckiM7BkuHa3bfIcjlZ3slQQQFHfrIJrA+SiB4vevbfuqb0q9V6i/UWKrOOSkyEfJRA8XvXtv3U+SiB4vevbfuqb0rOPU4+hLGqczIczwqsYUDKXcLkkEHs5c5xTZ19KAQk/mIIqVxIjECM3HjMtx47SQlDTSAlCAO4ADoBXupVcqk55SZXKUpfidxSlKrIilKUApSlARzJcGg5PPjTX5M2LJjtKZSuG/wBntKiCQeh31SK1nyVQfGL37b91TalWYkrJfwiuVOEneUU/kQn5KoPjF79t+6nyVQfGL37b91TalMR+XREcGlyLoiE/JVB8Yvftv3U+SqD4xe/bfuqbUpiPy6IYNLkXREJ+SqD4xe/bfup8lUHxi9+2/dU2pTEfl0QwaXIuiIT8lUHxi9+2/dXrkcIbXLaU1Iud4fZV85tczaVD6D0qdUrKqyTuvRGVRpJ3UV0QpSlVFp//2Q==",
|
|
"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(graph.get_graph().draw_mermaid_png()))\n",
|
|
"except Exception:\n",
|
|
" # This requires some extra dependencies and is optional\n",
|
|
" pass"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"id": "c59593ef-5073-4279-931e-828dae971f23",
|
|
"metadata": {},
|
|
"source": [
|
|
"Now we can ask the bot questions outside its training data."
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 15,
|
|
"id": "051dc374-67cc-4371-9dd1-221e07593148",
|
|
"metadata": {},
|
|
"outputs": [
|
|
{
|
|
"name": "stdout",
|
|
"output_type": "stream",
|
|
"text": [
|
|
"User: what's langgraph all about?\n"
|
|
]
|
|
},
|
|
{
|
|
"name": "stdout",
|
|
"output_type": "stream",
|
|
"text": [
|
|
"Assistant: [{'id': 'toolu_01L1TABSBXsHPsebWiMPNqf1', 'input': {'query': 'langgraph'}, 'name': 'tavily_search_results_json', 'type': 'tool_use'}]\n",
|
|
"Assistant: [{\"url\": \"https://langchain-ai.github.io/langgraph/\", \"content\": \"LangGraph is framework agnostic (each node is a regular python function). It extends the core Runnable API (shared interface for streaming, async, and batch calls) to make it easy to: Seamless state management across multiple turns of conversation or tool usage. The ability to flexibly route between nodes based on dynamic criteria.\"}, {\"url\": \"https://blog.langchain.dev/langgraph-multi-agent-workflows/\", \"content\": \"As a part of the launch, we highlighted two simple runtimes: one that is the equivalent of the AgentExecutor in langchain, and a second that was a version of that aimed at message passing and chat models.\\n It's important to note that these three examples are only a few of the possible examples we could highlight - there are almost assuredly other examples out there and we look forward to seeing what the community comes up with!\\n LangGraph: Multi-Agent Workflows\\nLinks\\nLast week we highlighted LangGraph - a new package (available in both Python and JS) to better enable creation of LLM workflows containing cycles, which are a critical component of most agent runtimes. \\\"\\nAnother key difference between Autogen and LangGraph is that LangGraph is fully integrated into the LangChain ecosystem, meaning you take fully advantage of all the LangChain integrations and LangSmith observability.\\n As part of this launch, we're also excited to highlight a few applications built on top of LangGraph that utilize the concept of multiple agents.\\n\"}]\n",
|
|
"Assistant: Based on the search results, LangGraph is a framework-agnostic Python and JavaScript library that extends the core Runnable API from the LangChain project to enable the creation of more complex workflows involving multiple agents or components. Some key things about LangGraph:\n",
|
|
"\n",
|
|
"- It makes it easier to manage state across multiple turns of conversation or tool usage, and to dynamically route between different nodes/components based on criteria.\n",
|
|
"\n",
|
|
"- It is integrated with the LangChain ecosystem, allowing you to take advantage of LangChain integrations and observability features.\n",
|
|
"\n",
|
|
"- It enables the creation of multi-agent workflows, where different components or agents can be chained together in more flexible and complex ways than the standard LangChain AgentExecutor.\n",
|
|
"\n",
|
|
"- The core idea is to provide a more powerful and flexible framework for building LLM-powered applications and workflows, beyond what is possible with just the core LangChain tools.\n",
|
|
"\n",
|
|
"Overall, LangGraph seems to be a useful addition to the LangChain toolkit, focused on enabling more advanced, multi-agent style applications and workflows powered by large language models.\n"
|
|
]
|
|
},
|
|
{
|
|
"name": "stdout",
|
|
"output_type": "stream",
|
|
"text": [
|
|
"User: neat!\n"
|
|
]
|
|
},
|
|
{
|
|
"name": "stdout",
|
|
"output_type": "stream",
|
|
"text": [
|
|
"Assistant: I'm afraid I don't have enough context to provide a substantive response to \"neat!\". As an AI assistant, I'm designed to have conversations and provide information to users, but I need more details or a specific question from you in order to give a helpful reply. Could you please rephrase your request or provide some additional context? I'd be happy to assist further once I understand what you're looking for.\n"
|
|
]
|
|
},
|
|
{
|
|
"name": "stdout",
|
|
"output_type": "stream",
|
|
"text": [
|
|
"User: what?\n"
|
|
]
|
|
},
|
|
{
|
|
"name": "stdout",
|
|
"output_type": "stream",
|
|
"text": [
|
|
"Assistant: I'm afraid I don't have enough context to provide a meaningful response to \"what?\". Could you please rephrase your request or provide more details about what you are asking? I'd be happy to try to assist you further once I have a clearer understanding of your query.\n"
|
|
]
|
|
},
|
|
{
|
|
"name": "stdout",
|
|
"output_type": "stream",
|
|
"text": [
|
|
"User: q\n"
|
|
]
|
|
},
|
|
{
|
|
"name": "stdout",
|
|
"output_type": "stream",
|
|
"text": [
|
|
"Goodbye!\n"
|
|
]
|
|
}
|
|
],
|
|
"source": [
|
|
"from langchain_core.messages import BaseMessage\n",
|
|
"\n",
|
|
"while True:\n",
|
|
" user_input = input(\"User: \")\n",
|
|
" if user_input.lower() in [\"quit\", \"exit\", \"q\"]:\n",
|
|
" print(\"Goodbye!\")\n",
|
|
" break\n",
|
|
" for event in graph.stream({\"messages\": [(\"user\", user_input)]}):\n",
|
|
" for value in event.values():\n",
|
|
" if isinstance(value[\"messages\"][-1], BaseMessage):\n",
|
|
" print(\"Assistant:\", value[\"messages\"][-1].content)"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"id": "89da9e85-2e5d-49c2-8cbd-572cbdb89135",
|
|
"metadata": {},
|
|
"source": [
|
|
"**Congrats!** You've created a conversational agent in langgraph that can use a search engine to retrieve updated information when needed. Now it can handle a wider range of user queries. To inspect all the steps your agent just took, check out this [LangSmith trace](https://smith.langchain.com/public/24b94adc-3356-4d9f-8f94-813f8004fdbe/r).\n",
|
|
"\n",
|
|
"Our chatbot still can't remember past interactions on its own, limiting its ability to have coherent, multi-turn conversations. In the next part, we'll add **memory** to address this.\n",
|
|
"\n",
|
|
"\n",
|
|
"The full code for the graph we've created in this section is reproduced below, replacing our `BasicToolNode` for the prebuilt [ToolNode](https://langchain-ai.github.io/langgraph/reference/prebuilt/#toolnode), and our `route_tools` condition with the prebuilt [tools_condition](https://langchain-ai.github.io/langgraph/reference/prebuilt/#tools_condition)\n",
|
|
"\n",
|
|
"<details>\n",
|
|
"<summary>Full Code</summary>\n",
|
|
" <pre>\n",
|
|
"\n",
|
|
"```python\n",
|
|
"from typing import Annotated\n",
|
|
"\n",
|
|
"from langchain_anthropic import ChatAnthropic\n",
|
|
"from langchain_community.tools.tavily_search import TavilySearchResults\n",
|
|
"from langchain_core.messages import BaseMessage\n",
|
|
"from typing_extensions import TypedDict\n",
|
|
"\n",
|
|
"from langgraph.graph import StateGraph\n",
|
|
"from langgraph.graph.message import add_messages\n",
|
|
"from langgraph.prebuilt import ToolNode, tools_condition\n",
|
|
"\n",
|
|
"\n",
|
|
"class State(TypedDict):\n",
|
|
" messages: Annotated[list, add_messages]\n",
|
|
"\n",
|
|
"\n",
|
|
"graph_builder = StateGraph(State)\n",
|
|
"\n",
|
|
"\n",
|
|
"tool = TavilySearchResults(max_results=2)\n",
|
|
"tools = [tool]\n",
|
|
"llm = ChatAnthropic(model=\"claude-3-haiku-20240307\")\n",
|
|
"llm_with_tools = llm.bind_tools(tools)\n",
|
|
"\n",
|
|
"\n",
|
|
"def chatbot(state: State):\n",
|
|
" return {\"messages\": [llm_with_tools.invoke(state[\"messages\"])]}\n",
|
|
"\n",
|
|
"\n",
|
|
"graph_builder.add_node(\"chatbot\", chatbot)\n",
|
|
"\n",
|
|
"tool_node = ToolNode(tools=[tool])\n",
|
|
"graph_builder.add_node(\"tools\", tool_node)\n",
|
|
"\n",
|
|
"graph_builder.add_conditional_edges(\n",
|
|
" \"chatbot\",\n",
|
|
" tools_condition,\n",
|
|
")\n",
|
|
"# Any time a tool is called, we return to the chatbot to decide the next step\n",
|
|
"graph_builder.add_edge(\"tools\", \"chatbot\")\n",
|
|
"graph_builder.set_entry_point(\"chatbot\")\n",
|
|
"graph = graph_builder.compile()\n",
|
|
"```\n",
|
|
"\n",
|
|
"</pre>\n",
|
|
"</details>"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"id": "ae45f2aa-396f-4f3f-848b-7750611617f8",
|
|
"metadata": {},
|
|
"source": [
|
|
"## Part 3: Adding Memory to the Chatbot\n",
|
|
"\n",
|
|
"Our chatbot can now use tools to answer user questions, but it doesn't remember the context of previous interactions. This limits its ability to have coherent, multi-turn conversations.\n",
|
|
"\n",
|
|
"LangGraph solves this problem through **persistent checkpointing**. If you provide a `checkpointer` when compiling the graph and a `thread_id` when calling your graph, LangGraph automatically saves the state after each step. When you invoke the graph again using the same `thread_id`, the graph loads its saved state, allowing the chatbot to pick up where it left off. \n",
|
|
"\n",
|
|
"We will see later that **checkpointing** is _much_ more powerful than simple chat memory - it lets you save and resume complex state at any time for error recovery, human-in-the-loop workflows, time travel interactions, and more. But before we get too ahead of ourselves, let's add checkpointing to enable multi-turn conversations.\n",
|
|
"\n",
|
|
"To get started, create a `SqliteSaver` checkpointer."
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 1,
|
|
"id": "6baafdf6-6803-4305-9381-9dc970468a4d",
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"from langgraph.checkpoint.sqlite import SqliteSaver\n",
|
|
"\n",
|
|
"memory = SqliteSaver.from_conn_string(\":memory:\")"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"id": "08d3d11a-1b42-4cbb-8e11-2a4294263d90",
|
|
"metadata": {},
|
|
"source": [
|
|
"**Notice** that we've specified `:memory` as the Sqlite DB path. This is convenient for our tutorial (it saves it all in-memory). In a production application, you would likely change this to connect to your own DB and/or use one of the other checkpointer classes.\n",
|
|
"\n",
|
|
"Next define the graph. Now that you've already built your own `BasicToolNode`, we'll replace it with LangGraph's prebuilt `ToolNode` and `tools_condition`, since these do some nice things like parallel API execution. Apart from that, the following is all copied from Part 2."
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 2,
|
|
"id": "e6a51f1e-00de-4701-8931-de8cf19294ae",
|
|
"metadata": {},
|
|
"outputs": [
|
|
{
|
|
"name": "stderr",
|
|
"output_type": "stream",
|
|
"text": [
|
|
"/Users/wfh/code/lc/langchain/libs/core/langchain_core/_api/beta_decorator.py:87: LangChainBetaWarning: The method `ChatAnthropic.bind_tools` is in beta. It is actively being worked on, so the API may change.\n",
|
|
" warn_beta(\n"
|
|
]
|
|
}
|
|
],
|
|
"source": [
|
|
"from typing import Annotated\n",
|
|
"\n",
|
|
"from langchain_anthropic import ChatAnthropic\n",
|
|
"from langchain_community.tools.tavily_search import TavilySearchResults\n",
|
|
"from langchain_core.messages import BaseMessage\n",
|
|
"from typing_extensions import TypedDict\n",
|
|
"\n",
|
|
"from langgraph.graph import StateGraph, START, END\n",
|
|
"from langgraph.graph.message import add_messages\n",
|
|
"from langgraph.prebuilt import ToolNode, tools_condition\n",
|
|
"\n",
|
|
"\n",
|
|
"class State(TypedDict):\n",
|
|
" messages: Annotated[list, add_messages]\n",
|
|
"\n",
|
|
"\n",
|
|
"graph_builder = StateGraph(State)\n",
|
|
"\n",
|
|
"\n",
|
|
"tool = TavilySearchResults(max_results=2)\n",
|
|
"tools = [tool]\n",
|
|
"llm = ChatAnthropic(model=\"claude-3-haiku-20240307\")\n",
|
|
"llm_with_tools = llm.bind_tools(tools)\n",
|
|
"\n",
|
|
"\n",
|
|
"def chatbot(state: State):\n",
|
|
" return {\"messages\": [llm_with_tools.invoke(state[\"messages\"])]}\n",
|
|
"\n",
|
|
"\n",
|
|
"graph_builder.add_node(\"chatbot\", chatbot)\n",
|
|
"\n",
|
|
"tool_node = ToolNode(tools=[tool])\n",
|
|
"graph_builder.add_node(\"tools\", tool_node)\n",
|
|
"\n",
|
|
"graph_builder.add_conditional_edges(\n",
|
|
" \"chatbot\",\n",
|
|
" tools_condition,\n",
|
|
")\n",
|
|
"# Any time a tool is called, we return to the chatbot to decide the next step\n",
|
|
"graph_builder.add_edge(\"tools\", \"chatbot\")\n",
|
|
"graph_builder.add_edge(START, \"chatbot\")"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"id": "8a292dfe-764f-4561-90aa-71317d679d3e",
|
|
"metadata": {},
|
|
"source": [
|
|
"Finally, compile the graph with the provided checkpointer."
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 3,
|
|
"id": "a06548bf-81fa-4436-b4c1-f68601fb4187",
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"graph = graph_builder.compile(checkpointer=memory)"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"id": "df01805c-4458-4474-b13b-59ecfe228f12",
|
|
"metadata": {},
|
|
"source": [
|
|
"Notice the connectivity of the graph hasn't changed since Part 2. All we are doing is checkpointing the `State` as the graph works through each node."
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 6,
|
|
"id": "761d15fb-d5e2-4d50-a630-126d77e77294",
|
|
"metadata": {},
|
|
"outputs": [
|
|
{
|
|
"data": {
|
|
"image/jpeg": "/9j/4AAQSkZJRgABAQAAAQABAAD/4gHYSUNDX1BST0ZJTEUAAQEAAAHIAAAAAAQwAABtbnRyUkdCIFhZWiAH4AABAAEAAAAAAABhY3NwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAA9tYAAQAAAADTLQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAlkZXNjAAAA8AAAACRyWFlaAAABFAAAABRnWFlaAAABKAAAABRiWFlaAAABPAAAABR3dHB0AAABUAAAABRyVFJDAAABZAAAAChnVFJDAAABZAAAAChiVFJDAAABZAAAAChjcHJ0AAABjAAAADxtbHVjAAAAAAAAAAEAAAAMZW5VUwAAAAgAAAAcAHMAUgBHAEJYWVogAAAAAAAAb6IAADj1AAADkFhZWiAAAAAAAABimQAAt4UAABjaWFlaIAAAAAAAACSgAAAPhAAAts9YWVogAAAAAAAA9tYAAQAAAADTLXBhcmEAAAAAAAQAAAACZmYAAPKnAAANWQAAE9AAAApbAAAAAAAAAABtbHVjAAAAAAAAAAEAAAAMZW5VUwAAACAAAAAcAEcAbwBvAGcAbABlACAASQBuAGMALgAgADIAMAAxADb/2wBDAAMCAgMCAgMDAwMEAwMEBQgFBQQEBQoHBwYIDAoMDAsKCwsNDhIQDQ4RDgsLEBYQERMUFRUVDA8XGBYUGBIUFRT/2wBDAQMEBAUEBQkFBQkUDQsNFBQ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kEHs5c5xTZ19KAQk/mIIqVxIjECM3HjMtx47SQlDTSAlCAO4ADoBXupVcqk55SZXKUpfidxSlKrIilKUApSlARzJcGg5PPjTX5M2LJjtKZSuG/wBntKiCQeh31SK1nyVQfGL37b91TalWYkrJfwiuVOEneUU/kQn5KoPjF79t+6nyVQfGL37b91TalMR+XREcGlyLoiE/JVB8Yvftv3U+SqD4xe/bfuqbUpiPy6IYNLkXREJ+SqD4xe/bfup8lUHxi9+2/dU2pTEfl0QwaXIuiIT8lUHxi9+2/dXrkcIbXLaU1Iud4fZV85tczaVD6D0qdUrKqyTuvRGVRpJ3UV0QpSlVFp//2Q==",
|
|
"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(graph.get_graph().draw_mermaid_png()))\n",
|
|
"except Exception:\n",
|
|
" # This requires some extra dependencies and is optional\n",
|
|
" pass"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"id": "2c8265ef-e5b4-4c32-9856-5572b5652142",
|
|
"metadata": {},
|
|
"source": [
|
|
"Now you can interact with your bot! First, pick a thread to use as the key for this conversation."
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 5,
|
|
"id": "be7b5abb-04ef-4d53-83d1-d4d3139cc43a",
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"config = {\"configurable\": {\"thread_id\": \"1\"}}"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"id": "d0b1a5ee-7fa2-475c-a9db-749694b90ba9",
|
|
"metadata": {},
|
|
"source": [
|
|
"Next, call your chat bot."
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 6,
|
|
"id": "dba1b168-f8e0-496d-9bd6-37198fb4776e",
|
|
"metadata": {},
|
|
"outputs": [
|
|
{
|
|
"name": "stdout",
|
|
"output_type": "stream",
|
|
"text": [
|
|
"================================\u001b[1m Human Message \u001b[0m=================================\n",
|
|
"\n",
|
|
"Hi there! My name is Will.\n",
|
|
"==================================\u001b[1m Ai Message \u001b[0m==================================\n",
|
|
"\n",
|
|
"It's nice to meet you, Will! I'm an AI assistant created by Anthropic. I'm here to help you with any questions or tasks you may have. Please let me know how I can assist you today.\n"
|
|
]
|
|
}
|
|
],
|
|
"source": [
|
|
"user_input = \"Hi there! My name is Will.\"\n",
|
|
"\n",
|
|
"# The config is the **second positional argument** to stream() or invoke()!\n",
|
|
"events = graph.stream(\n",
|
|
" {\"messages\": [(\"user\", user_input)]}, config, stream_mode=\"values\"\n",
|
|
")\n",
|
|
"for event in events:\n",
|
|
" event[\"messages\"][-1].pretty_print()"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"id": "33c6b470-5082-4c3e-b732-34de47c88735",
|
|
"metadata": {},
|
|
"source": [
|
|
"**Note:** The config was provided as the **second positional argument** when calling our graph. It importantly is _not_ nested within the graph inputs (`{'messages': []}`).\n",
|
|
"\n",
|
|
"Let's ask a followup: see if it remembers your name."
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 8,
|
|
"id": "f5447778-53d7-47f3-801b-f47bcf2185a0",
|
|
"metadata": {},
|
|
"outputs": [
|
|
{
|
|
"name": "stdout",
|
|
"output_type": "stream",
|
|
"text": [
|
|
"================================\u001b[1m Human Message \u001b[0m=================================\n",
|
|
"\n",
|
|
"Remember my name?\n",
|
|
"==================================\u001b[1m Ai Message \u001b[0m==================================\n",
|
|
"\n",
|
|
"Of course, your name is Will. It's nice to meet you again!\n"
|
|
]
|
|
}
|
|
],
|
|
"source": [
|
|
"user_input = \"Remember my name?\"\n",
|
|
"\n",
|
|
"# The config is the **second positional argument** to stream() or invoke()!\n",
|
|
"events = graph.stream(\n",
|
|
" {\"messages\": [(\"user\", user_input)]}, config, stream_mode=\"values\"\n",
|
|
")\n",
|
|
"for event in events:\n",
|
|
" event[\"messages\"][-1].pretty_print()"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"id": "33be4cd8-f96f-4949-9d1f-48054502e5d0",
|
|
"metadata": {},
|
|
"source": [
|
|
"**Notice** that we aren't using an external list for memory: it's all handled by the checkpointer! You can inspect the full execution in this [LangSmith trace](https://smith.langchain.com/public/48387889-c002-47a8-9f6a-1f6b298db64b/r) to see what's going on.\n",
|
|
"\n",
|
|
"Don't believe me? Try this using a different config."
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 9,
|
|
"id": "4527cf9a-b191-4bde-858a-e33a74a48c55",
|
|
"metadata": {},
|
|
"outputs": [
|
|
{
|
|
"name": "stdout",
|
|
"output_type": "stream",
|
|
"text": [
|
|
"================================\u001b[1m Human Message \u001b[0m=================================\n",
|
|
"\n",
|
|
"Remember my name?\n",
|
|
"==================================\u001b[1m Ai Message \u001b[0m==================================\n",
|
|
"\n",
|
|
"I'm afraid I don't actually have the capability to remember your name. As an AI assistant, I don't have a persistent memory of our previous conversations or interactions. I respond based on the current context provided to me. Could you please restate your name or provide more information so I can try to assist you?\n"
|
|
]
|
|
}
|
|
],
|
|
"source": [
|
|
"# The only difference is we change the `thread_id` here to \"2\" instead of \"1\"\n",
|
|
"events = graph.stream(\n",
|
|
" {\"messages\": [(\"user\", user_input)]},\n",
|
|
" {\"configurable\": {\"thread_id\": \"2\"}},\n",
|
|
" stream_mode=\"values\",\n",
|
|
")\n",
|
|
"for event in events:\n",
|
|
" event[\"messages\"][-1].pretty_print()"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"id": "5eeccbf0-ed74-4838-a7e9-31910d82b0b2",
|
|
"metadata": {},
|
|
"source": [
|
|
"**Notice** that the **only** change we've made is to modify the `thread_id` in the config. See this call's [LangSmith trace](https://smith.langchain.com/public/4647adf6-3835-4ce3-ba39-26ed4f167411/r) for comparison. \n",
|
|
"\n",
|
|
"By now, we have made a few checkpoints across two different threads. But what goes into a checkpoint? To inspect a graph's `state` for a given config at any time, call `get_state(config)`."
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 10,
|
|
"id": "0be77c25-1423-4f2d-9b2d-28530cc761a4",
|
|
"metadata": {},
|
|
"outputs": [
|
|
{
|
|
"data": {
|
|
"text/plain": [
|
|
"StateSnapshot(values={'messages': [HumanMessage(content='Hi there! My name is Will.', id='aad97d7f-8845-4f9e-b723-2af3b7c97590'), AIMessage(content=\"It's nice to meet you, Will! I'm an AI assistant created by Anthropic. I'm here to help you with any questions or tasks you may have. Please let me know how I can assist you today.\", response_metadata={'id': 'msg_01VCz7Y5jVmMZXibBtnECyvJ', 'model': 'claude-3-haiku-20240307', 'stop_reason': 'end_turn', 'stop_sequence': None, 'usage': {'input_tokens': 375, 'output_tokens': 49}}, id='run-66cf1695-5ba8-4fd8-a79d-ded9ee3c3b33-0'), HumanMessage(content='Remember my name?', id='ac1e9971-dbee-4622-9e63-5015dee05c20'), AIMessage(content=\"Of course, your name is Will. It's nice to meet you again!\", response_metadata={'id': 'msg_01RsJ6GaQth7r9soxbF7TSpQ', 'model': 'claude-3-haiku-20240307', 'stop_reason': 'end_turn', 'stop_sequence': None, 'usage': {'input_tokens': 431, 'output_tokens': 19}}, id='run-890149d3-214f-44e8-9717-57ec4ef68224-0')]}, next=(), config={'configurable': {'thread_id': '1', 'thread_ts': '2024-05-06T22:23:20.430350+00:00'}}, parent_config=None)"
|
|
]
|
|
},
|
|
"execution_count": 10,
|
|
"metadata": {},
|
|
"output_type": "execute_result"
|
|
}
|
|
],
|
|
"source": [
|
|
"snapshot = graph.get_state(config)\n",
|
|
"snapshot"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 11,
|
|
"id": "c106bd09-f155-4e15-9120-c60c834106e5",
|
|
"metadata": {},
|
|
"outputs": [
|
|
{
|
|
"data": {
|
|
"text/plain": [
|
|
"()"
|
|
]
|
|
},
|
|
"execution_count": 11,
|
|
"metadata": {},
|
|
"output_type": "execute_result"
|
|
}
|
|
],
|
|
"source": [
|
|
"snapshot.next # (since the graph ended this turn, `next` is empty. If you fetch a state from within a graph invocation, next tells which node will execute next)"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"id": "627f4998-6780-4cce-8f3c-9a5580888e3a",
|
|
"metadata": {},
|
|
"source": [
|
|
"The snapshot above contains the current state values, corresponding config, and the `next` node to process. In our case, the graph has reached an `__end__` state, so `next` is empty.\n",
|
|
"\n",
|
|
"**Congratulations!** Your chatbot can now maintain conversation state across sessions thanks to LangGraph's checkpointing system. This opens up exciting possibilities for more natural, contextual interactions. LangGraph's checkpointing even handles **arbitrarily complex graph states**, which is much more expressive and powerful than simple chat memory.\n",
|
|
"\n",
|
|
"In the next part, we'll introduce human oversight to our bot to handle situations where it may need guidance or verification before proceeding.\n",
|
|
" \n",
|
|
"Check out the code snippet below to review our graph from this section.\n",
|
|
"\n",
|
|
"<details>\n",
|
|
"<summary>Full Code</summary>\n",
|
|
" <pre>\n",
|
|
"\n",
|
|
"```python\n",
|
|
"from typing import Annotated\n",
|
|
"\n",
|
|
"from langchain_anthropic import ChatAnthropic\n",
|
|
"from langchain_community.tools.tavily_search import TavilySearchResults\n",
|
|
"from langchain_core.messages import BaseMessage\n",
|
|
"from typing_extensions import TypedDict\n",
|
|
"\n",
|
|
"from langgraph.checkpoint.sqlite import SqliteSaver\n",
|
|
"from langgraph.graph import StateGraph\n",
|
|
"from langgraph.graph.message import add_messages\n",
|
|
"from langgraph.prebuilt import ToolNode\n",
|
|
"\n",
|
|
"\n",
|
|
"class State(TypedDict):\n",
|
|
" messages: Annotated[list, add_messages]\n",
|
|
"\n",
|
|
"\n",
|
|
"graph_builder = StateGraph(State)\n",
|
|
"\n",
|
|
"\n",
|
|
"tool = TavilySearchResults(max_results=2)\n",
|
|
"tools = [tool]\n",
|
|
"llm = ChatAnthropic(model=\"claude-3-haiku-20240307\")\n",
|
|
"llm_with_tools = llm.bind_tools(tools)\n",
|
|
"\n",
|
|
"\n",
|
|
"def chatbot(state: State):\n",
|
|
" return {\"messages\": [llm_with_tools.invoke(state[\"messages\"])]}\n",
|
|
"\n",
|
|
"\n",
|
|
"graph_builder.add_node(\"chatbot\", chatbot)\n",
|
|
"\n",
|
|
"tool_node = ToolNode(tools=[tool])\n",
|
|
"graph_builder.add_node(\"tools\", tool_node)\n",
|
|
"\n",
|
|
"graph_builder.add_conditional_edges(\n",
|
|
" \"chatbot\",\n",
|
|
" tools_condition,\n",
|
|
")\n",
|
|
"graph_builder.add_edge(\"tools\", \"chatbot\")\n",
|
|
"graph_builder.set_entry_point(\"chatbot\")\n",
|
|
"graph = graph_builder.compile(checkpointer=memory)\n",
|
|
"```\n",
|
|
"</pre>\n",
|
|
"</pre>\n",
|
|
"</details>"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"id": "6f1da240-ec9b-441f-9d47-44c6dc85d540",
|
|
"metadata": {},
|
|
"source": [
|
|
"## Part 4: Human-in-the-loop\n",
|
|
"\n",
|
|
"Agents can be unreliable and may need human input to successfully accomplish tasks. Similarly, for some actions, you may want to require human approval before running to ensure that everything is running as intended.\n",
|
|
"\n",
|
|
"LangGraph supports `human-in-the-loop` workflows in a number of ways. In this section, we will use LangGraph's `interrupt_before` functionality to always break the tool node.\n",
|
|
"\n",
|
|
"First, start from our existing code. The following is copied from Part 3."
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 1,
|
|
"id": "5a81608a-373a-4339-b1c6-65b73a92b983",
|
|
"metadata": {},
|
|
"outputs": [
|
|
{
|
|
"name": "stderr",
|
|
"output_type": "stream",
|
|
"text": [
|
|
"/Users/wfh/code/lc/langchain/libs/core/langchain_core/_api/beta_decorator.py:87: LangChainBetaWarning: The method `ChatAnthropic.bind_tools` is in beta. It is actively being worked on, so the API may change.\n",
|
|
" warn_beta(\n"
|
|
]
|
|
}
|
|
],
|
|
"source": [
|
|
"from typing import Annotated\n",
|
|
"\n",
|
|
"from langchain_anthropic import ChatAnthropic\n",
|
|
"from langchain_community.tools.tavily_search import TavilySearchResults\n",
|
|
"from langchain_core.messages import BaseMessage\n",
|
|
"from typing_extensions import TypedDict\n",
|
|
"\n",
|
|
"from langgraph.checkpoint.sqlite import SqliteSaver\n",
|
|
"from langgraph.graph import StateGraph, START\n",
|
|
"from langgraph.graph.message import add_messages\n",
|
|
"from langgraph.prebuilt import ToolNode, tools_condition\n",
|
|
"\n",
|
|
"memory = SqliteSaver.from_conn_string(\":memory:\")\n",
|
|
"\n",
|
|
"\n",
|
|
"class State(TypedDict):\n",
|
|
" messages: Annotated[list, add_messages]\n",
|
|
"\n",
|
|
"\n",
|
|
"graph_builder = StateGraph(State)\n",
|
|
"\n",
|
|
"\n",
|
|
"tool = TavilySearchResults(max_results=2)\n",
|
|
"tools = [tool]\n",
|
|
"llm = ChatAnthropic(model=\"claude-3-haiku-20240307\")\n",
|
|
"llm_with_tools = llm.bind_tools(tools)\n",
|
|
"\n",
|
|
"\n",
|
|
"def chatbot(state: State):\n",
|
|
" return {\"messages\": [llm_with_tools.invoke(state[\"messages\"])]}\n",
|
|
"\n",
|
|
"\n",
|
|
"graph_builder.add_node(\"chatbot\", chatbot)\n",
|
|
"\n",
|
|
"tool_node = ToolNode(tools=[tool])\n",
|
|
"graph_builder.add_node(\"tools\", tool_node)\n",
|
|
"\n",
|
|
"graph_builder.add_conditional_edges(\n",
|
|
" \"chatbot\",\n",
|
|
" tools_condition,\n",
|
|
")\n",
|
|
"graph_builder.add_edge(\"tools\", \"chatbot\")\n",
|
|
"graph_builder.add_edge(START, \"chatbot\")"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"id": "813505b2-18c1-46e9-b891-20a34232808b",
|
|
"metadata": {},
|
|
"source": [
|
|
"Now, compile the graph, specifying to `interrupt_before` the `action` node."
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 2,
|
|
"id": "b0883e32-1a39-4ce9-ae32-bbd66708fd84",
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"graph = graph_builder.compile(\n",
|
|
" checkpointer=memory,\n",
|
|
" # This is new!\n",
|
|
" interrupt_before=[\"tools\"],\n",
|
|
" # Note: can also interrupt __after__ actions, if desired.\n",
|
|
" # interrupt_after=[\"tools\"]\n",
|
|
")"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 3,
|
|
"id": "9f318020-ab7e-415b-a5e2-eddec6d9f3a6",
|
|
"metadata": {},
|
|
"outputs": [
|
|
{
|
|
"name": "stdout",
|
|
"output_type": "stream",
|
|
"text": [
|
|
"================================\u001b[1m Human Message \u001b[0m=================================\n",
|
|
"\n",
|
|
"I'm learning LangGraph. Could you do some research on it for me?\n",
|
|
"==================================\u001b[1m Ai Message \u001b[0m==================================\n",
|
|
"\n",
|
|
"[{'text': \"Okay, let's do some research on LangGraph:\", 'type': 'text'}, {'id': 'toolu_01Be7aRgMEv9cg6ezaFjiCry', 'input': {'query': 'LangGraph'}, 'name': 'tavily_search_results_json', 'type': 'tool_use'}]\n",
|
|
"Tool Calls:\n",
|
|
" tavily_search_results_json (toolu_01Be7aRgMEv9cg6ezaFjiCry)\n",
|
|
" Call ID: toolu_01Be7aRgMEv9cg6ezaFjiCry\n",
|
|
" Args:\n",
|
|
" query: LangGraph\n"
|
|
]
|
|
}
|
|
],
|
|
"source": [
|
|
"user_input = \"I'm learning LangGraph. Could you do some research on it for me?\"\n",
|
|
"config = {\"configurable\": {\"thread_id\": \"1\"}}\n",
|
|
"# The config is the **second positional argument** to stream() or invoke()!\n",
|
|
"events = graph.stream(\n",
|
|
" {\"messages\": [(\"user\", user_input)]}, config, stream_mode=\"values\"\n",
|
|
")\n",
|
|
"for event in events:\n",
|
|
" if \"messages\" in event:\n",
|
|
" event[\"messages\"][-1].pretty_print()"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"id": "39405637-13b1-40b1-a51e-6d60bf675ff1",
|
|
"metadata": {},
|
|
"source": [
|
|
"Let's inspect the graph state to confirm it worked."
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 4,
|
|
"id": "9bb7af46-9b4f-4bb1-b8b9-e9ddf7dbc82c",
|
|
"metadata": {},
|
|
"outputs": [
|
|
{
|
|
"data": {
|
|
"text/plain": [
|
|
"('action',)"
|
|
]
|
|
},
|
|
"execution_count": 4,
|
|
"metadata": {},
|
|
"output_type": "execute_result"
|
|
}
|
|
],
|
|
"source": [
|
|
"snapshot = graph.get_state(config)\n",
|
|
"snapshot.next"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"id": "89326046-2b11-4812-8b6d-8780306ec275",
|
|
"metadata": {},
|
|
"source": [
|
|
"**Notice** that unlike last time, the \"next\" node is set to **'action'**. We've interrupted here! Let's check the tool invocation."
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 5,
|
|
"id": "3facda0a-e6ad-4b28-b627-753ad8c90c15",
|
|
"metadata": {},
|
|
"outputs": [
|
|
{
|
|
"data": {
|
|
"text/plain": [
|
|
"[{'name': 'tavily_search_results_json',\n",
|
|
" 'args': {'query': 'LangGraph'},\n",
|
|
" 'id': 'toolu_01Be7aRgMEv9cg6ezaFjiCry'}]"
|
|
]
|
|
},
|
|
"execution_count": 5,
|
|
"metadata": {},
|
|
"output_type": "execute_result"
|
|
}
|
|
],
|
|
"source": [
|
|
"existing_message = snapshot.values[\"messages\"][-1]\n",
|
|
"existing_message.tool_calls"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"id": "a55a4c70-7226-4be0-8562-391f72bc1f2b",
|
|
"metadata": {},
|
|
"source": [
|
|
"This query seems reasonable. Nothing to filter here. The simplest thing the human can do is just let the graph continue executing. Let's do that below.\n",
|
|
"\n",
|
|
"Next, continue the graph! Passing in `None` will just let the graph continue where it left off, without adding anything new to the state."
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 6,
|
|
"id": "effb95d9-b7d5-40c5-9253-253d193b23b2",
|
|
"metadata": {},
|
|
"outputs": [
|
|
{
|
|
"name": "stdout",
|
|
"output_type": "stream",
|
|
"text": [
|
|
"=================================\u001b[1m Tool Message \u001b[0m=================================\n",
|
|
"Name: tavily_search_results_json\n",
|
|
"\n",
|
|
"[{\"url\": \"https://github.com/langchain-ai/langgraph\", \"content\": \"LangGraph is a Python package that extends LangChain Expression Language with the ability to coordinate multiple chains across multiple steps of computation in a cyclic manner. It is inspired by Pregel and Apache Beam and can be used for agent-like behaviors, such as chatbots, with LLMs.\"}, {\"url\": \"https://langchain-ai.github.io/langgraph//\", \"content\": \"LangGraph is a library for building stateful, multi-actor applications with LLMs, built on top of (and intended to be used with) LangChain . It extends the LangChain Expression Language with the ability to coordinate multiple chains (or actors) across multiple steps of computation in a cyclic manner. It is inspired by Pregel and Apache Beam .\"}]\n",
|
|
"==================================\u001b[1m Ai Message \u001b[0m==================================\n",
|
|
"\n",
|
|
"Based on the search results, LangGraph seems to be a Python library that extends the LangChain library to enable more complex, multi-step interactions with large language models (LLMs). Some key points:\n",
|
|
"\n",
|
|
"- LangGraph allows coordinating multiple \"chains\" (or actors) over multiple steps of computation, in a cyclic manner. This enables more advanced agent-like behaviors like chatbots.\n",
|
|
"- It is inspired by distributed graph processing frameworks like Pregel and Apache Beam.\n",
|
|
"- LangGraph is built on top of the LangChain library, which provides a framework for building applications with LLMs.\n",
|
|
"\n",
|
|
"So in summary, LangGraph appears to be a powerful tool for building more sophisticated applications and agents using large language models, by allowing you to coordinate multiple steps and actors in a flexible, graph-like manner. It extends the capabilities of the base LangChain library.\n",
|
|
"\n",
|
|
"Let me know if you need any clarification or have additional questions!\n"
|
|
]
|
|
}
|
|
],
|
|
"source": [
|
|
"# `None` will append nothing new to the current state, letting it resume as if it had never been interrupted\n",
|
|
"events = graph.stream(None, config, stream_mode=\"values\")\n",
|
|
"for event in events:\n",
|
|
" if \"messages\" in event:\n",
|
|
" event[\"messages\"][-1].pretty_print()"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"id": "21e78a97-474f-4709-b51d-9d5e8323e14c",
|
|
"metadata": {},
|
|
"source": [
|
|
"Review this call's [LangSmith trace](https://smith.langchain.com/public/6a9012c0-bfa2-4fba-8dce-961d233f9512/r) to see the exact work that was done in the above call. Notice that the state is loaded in the first step so that your chatbot can continue where it left off.\n",
|
|
"\n",
|
|
"**Congrats!** You've used an `interrupt` to add human-in-the-loop execution to your chatbot, allowing for human oversight and intervention when needed. This opens up the potential UIs you can create with your AI systems. Since we have already added a **checkpointer**, the graph can be paused **indefinitely** and resumed at any time as if nothing had happened.\n",
|
|
"\n",
|
|
"Next, we'll explore how to further customize the bot's behavior using custom state updates.\n",
|
|
"\n",
|
|
"Below is a copy of the code you used in this section. The only difference between this and the previous parts is the addition of the `interrupt_before` argument.\n",
|
|
"\n",
|
|
"<details>\n",
|
|
"<summary>Full Code</summary>\n",
|
|
" <pre>\n",
|
|
"\n",
|
|
"```python\n",
|
|
"from typing import Annotated\n",
|
|
"\n",
|
|
"from langchain_anthropic import ChatAnthropic\n",
|
|
"from langchain_community.tools.tavily_search import TavilySearchResults\n",
|
|
"from langchain_core.messages import BaseMessage\n",
|
|
"from typing_extensions import TypedDict\n",
|
|
"\n",
|
|
"from langgraph.checkpoint.sqlite import SqliteSaver\n",
|
|
"from langgraph.graph import StateGraph\n",
|
|
"from langgraph.graph.message import add_messages\n",
|
|
"from langgraph.prebuilt import ToolNode\n",
|
|
"\n",
|
|
"\n",
|
|
"class State(TypedDict):\n",
|
|
" messages: Annotated[list, add_messages]\n",
|
|
"\n",
|
|
"\n",
|
|
"graph_builder = StateGraph(State)\n",
|
|
"\n",
|
|
"\n",
|
|
"tool = TavilySearchResults(max_results=2)\n",
|
|
"tools = [tool]\n",
|
|
"llm = ChatAnthropic(model=\"claude-3-haiku-20240307\")\n",
|
|
"llm_with_tools = llm.bind_tools(tools)\n",
|
|
"\n",
|
|
"\n",
|
|
"def chatbot(state: State):\n",
|
|
" return {\"messages\": [llm_with_tools.invoke(state[\"messages\"])]}\n",
|
|
"\n",
|
|
"\n",
|
|
"graph_builder.add_node(\"chatbot\", chatbot)\n",
|
|
"\n",
|
|
"tool_node = ToolNode(tools=[tool])\n",
|
|
"graph_builder.add_node(\"tools\", tool_node)\n",
|
|
"\n",
|
|
"graph_builder.add_conditional_edges(\n",
|
|
" \"chatbot\",\n",
|
|
" tools_condition,\n",
|
|
")\n",
|
|
"graph_builder.add_edge(\"tools\", \"chatbot\")\n",
|
|
"graph_builder.set_entry_point(\"chatbot\")\n",
|
|
"\n",
|
|
"memory = SqliteSaver.from_conn_string(\":memory:\")\n",
|
|
"graph = graph_builder.compile(\n",
|
|
" checkpointer=memory,\n",
|
|
" # This is new!\n",
|
|
" interrupt_before=[\"tools\"],\n",
|
|
" # Note: can also interrupt __after__ actions, if desired.\n",
|
|
" # interrupt_after=[\"tools\"]\n",
|
|
")\n",
|
|
"```\n",
|
|
"</pre>\n",
|
|
"</details>"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"id": "6df38bc4-c177-4ccd-9ec2-83d32bf66722",
|
|
"metadata": {},
|
|
"source": [
|
|
"## Part 5: Manually Updating the State\n",
|
|
"\n",
|
|
"In the previous section, we showed how to interrupt a graph so that a human could inspect its actions. This lets the human `read` the state, but if they want to change they agent's course, they'll need to have `write` access.\n",
|
|
"\n",
|
|
"Thankfully, LangGraph lets you **manually update state**! Updating the state lets you control the agent's trajectory by modifying its actions (even modifying the past!). This capability is particularly useful when you want to correct the agent's mistakes, explore alternative paths, or guide the agent towards a specific goal.\n",
|
|
"\n",
|
|
"We'll show how to update a checkpointed state below. As before, first, define your graph. We'll reuse the exact same graph as before."
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 2,
|
|
"id": "faa345c6-38a2-42e8-9035-9cf56f7bb5b1",
|
|
"metadata": {},
|
|
"outputs": [
|
|
{
|
|
"name": "stderr",
|
|
"output_type": "stream",
|
|
"text": [
|
|
"/Users/wfh/code/lc/langchain/libs/core/langchain_core/_api/beta_decorator.py:87: LangChainBetaWarning: The method `ChatAnthropic.bind_tools` is in beta. It is actively being worked on, so the API may change.\n",
|
|
" warn_beta(\n"
|
|
]
|
|
}
|
|
],
|
|
"source": [
|
|
"from typing import Annotated\n",
|
|
"\n",
|
|
"from langchain_anthropic import ChatAnthropic\n",
|
|
"from langchain_community.tools.tavily_search import TavilySearchResults\n",
|
|
"from langchain_core.messages import BaseMessage\n",
|
|
"from typing_extensions import TypedDict\n",
|
|
"\n",
|
|
"from langgraph.checkpoint.sqlite import SqliteSaver\n",
|
|
"from langgraph.graph import StateGraph, START\n",
|
|
"from langgraph.graph.message import add_messages\n",
|
|
"from langgraph.prebuilt import ToolNode, tools_condition\n",
|
|
"\n",
|
|
"\n",
|
|
"class State(TypedDict):\n",
|
|
" messages: Annotated[list, add_messages]\n",
|
|
"\n",
|
|
"\n",
|
|
"graph_builder = StateGraph(State)\n",
|
|
"\n",
|
|
"\n",
|
|
"tool = TavilySearchResults(max_results=2)\n",
|
|
"tools = [tool]\n",
|
|
"llm = ChatAnthropic(model=\"claude-3-haiku-20240307\")\n",
|
|
"llm_with_tools = llm.bind_tools(tools)\n",
|
|
"\n",
|
|
"\n",
|
|
"def chatbot(state: State):\n",
|
|
" return {\"messages\": [llm_with_tools.invoke(state[\"messages\"])]}\n",
|
|
"\n",
|
|
"\n",
|
|
"graph_builder.add_node(\"chatbot\", chatbot)\n",
|
|
"\n",
|
|
"tool_node = ToolNode(tools=[tool])\n",
|
|
"graph_builder.add_node(\"tools\", tool_node)\n",
|
|
"\n",
|
|
"graph_builder.add_conditional_edges(\n",
|
|
" \"chatbot\",\n",
|
|
" tools_condition,\n",
|
|
")\n",
|
|
"graph_builder.add_edge(\"tools\", \"chatbot\")\n",
|
|
"graph_builder.add_edge(START, \"chatbot\")\n",
|
|
"memory = SqliteSaver.from_conn_string(\":memory:\")\n",
|
|
"graph = graph_builder.compile(\n",
|
|
" checkpointer=memory,\n",
|
|
" # This is new!\n",
|
|
" interrupt_before=[\"tools\"],\n",
|
|
" # Note: can also interrupt **after** actions, if desired.\n",
|
|
" # interrupt_after=[\"tools\"]\n",
|
|
")\n",
|
|
"\n",
|
|
"user_input = \"I'm learning LangGraph. Could you do some research on it for me?\"\n",
|
|
"config = {\"configurable\": {\"thread_id\": \"1\"}}\n",
|
|
"# The config is the **second positional argument** to stream() or invoke()!\n",
|
|
"events = graph.stream({\"messages\": [(\"user\", user_input)]}, config)\n",
|
|
"for event in events:\n",
|
|
" if \"messages\" in event:\n",
|
|
" event[\"messages\"][-1].pretty_print()"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 3,
|
|
"id": "a6b3bcae-dd04-49da-a4ef-e05634657faf",
|
|
"metadata": {},
|
|
"outputs": [
|
|
{
|
|
"name": "stdout",
|
|
"output_type": "stream",
|
|
"text": [
|
|
"==================================\u001b[1m Ai Message \u001b[0m==================================\n",
|
|
"\n",
|
|
"[{'id': 'toolu_01DTyDpJ1kKdNps5yxv3AGJd', 'input': {'query': 'LangGraph'}, 'name': 'tavily_search_results_json', 'type': 'tool_use'}]\n",
|
|
"Tool Calls:\n",
|
|
" tavily_search_results_json (toolu_01DTyDpJ1kKdNps5yxv3AGJd)\n",
|
|
" Call ID: toolu_01DTyDpJ1kKdNps5yxv3AGJd\n",
|
|
" Args:\n",
|
|
" query: LangGraph\n"
|
|
]
|
|
}
|
|
],
|
|
"source": [
|
|
"snapshot = graph.get_state(config)\n",
|
|
"existing_message = snapshot.values[\"messages\"][-1]\n",
|
|
"existing_message.pretty_print()"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"id": "3bf55a26-8c12-477a-9e83-5011d36ac4ee",
|
|
"metadata": {},
|
|
"source": [
|
|
"So far, all of this is an _exact repeat_ of the previous section. The LLM just requested to use the search engine tool and our graph was interrupted. If we proceed as before, the tool will be called to search the web.\n",
|
|
"\n",
|
|
"But what if the user wants to intercede? What if we think the chat bot doesn't need to use the tool? \n",
|
|
"\n",
|
|
"Let's directly provide the correct response!"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 4,
|
|
"id": "6a44bedc-ea91-4c22-976c-98b3d5a5e4a7",
|
|
"metadata": {},
|
|
"outputs": [
|
|
{
|
|
"name": "stdout",
|
|
"output_type": "stream",
|
|
"text": [
|
|
"==================================\u001b[1m Ai Message \u001b[0m==================================\n",
|
|
"\n",
|
|
"LangGraph is a library for building stateful, multi-actor applications with LLMs.\n",
|
|
"\n",
|
|
"\n",
|
|
"Last 2 messages;\n",
|
|
"[ToolMessage(content='LangGraph is a library for building stateful, multi-actor applications with LLMs.', id='14589ef1-15db-4a75-82a6-d57c40a216d0', tool_call_id='toolu_01DTyDpJ1kKdNps5yxv3AGJd'), AIMessage(content='LangGraph is a library for building stateful, multi-actor applications with LLMs.', id='1c657bfb-7690-44c7-a26d-d0d22453013d')]\n"
|
|
]
|
|
}
|
|
],
|
|
"source": [
|
|
"from langchain_core.messages import AIMessage\n",
|
|
"\n",
|
|
"answer = (\n",
|
|
" \"LangGraph is a library for building stateful, multi-actor applications with LLMs.\"\n",
|
|
")\n",
|
|
"new_messages = [\n",
|
|
" # The LLM API expects some ToolMessage to match its tool call. We'll satisfy that here.\n",
|
|
" ToolMessage(content=answer, tool_call_id=existing_message.tool_calls[0][\"id\"]),\n",
|
|
" # And then directly \"put words in the LLM's mouth\" by populating its response.\n",
|
|
" AIMessage(content=answer),\n",
|
|
"]\n",
|
|
"\n",
|
|
"new_messages[-1].pretty_print()\n",
|
|
"graph.update_state(\n",
|
|
" # Which state to update\n",
|
|
" config,\n",
|
|
" # The updated values to provide. The messages in our `State` are \"append-only\", meaning this will be appended\n",
|
|
" # to the existing state. We will review how to update existing messages in the next section!\n",
|
|
" {\"messages\": new_messages},\n",
|
|
")\n",
|
|
"\n",
|
|
"print(\"\\n\\nLast 2 messages;\")\n",
|
|
"print(graph.get_state(config).values[\"messages\"][-2:])"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"id": "584de971-6b10-4931-986e-cc35f7adbb3d",
|
|
"metadata": {},
|
|
"source": [
|
|
"Now the graph is complete, since we've provided the final response message! Since state updates simulate a graph step, they even generate corresponding traces. Inspec the [LangSmith trace](https://smith.langchain.com/public/c45207bb-bd26-4c9a-b631-928bbeebfbcb/r) of the `update_state` call above to see what's going on.\n",
|
|
"\n",
|
|
"**Notice** that our new messages are _appended_ to the messages already in the state. Remember how we defined the `State` type?\n",
|
|
"\n",
|
|
"```python\n",
|
|
"class State(TypedDict):\n",
|
|
" messages: Annotated[list, add_messages]\n",
|
|
"```\n",
|
|
"\n",
|
|
"We annotated `messages` with the pre-built `add_messages` function. This instructs the graph to always append values to the existing list, rather than overwriting the list directly. The same logic is applied here, so the messages we passed to `update_state` were appended in the same way!\n",
|
|
"\n",
|
|
"The `update_state` function operates as if it were one of the nodes in your graph! By default, the update operation uses the node that was last executed, but you can manually specify it below. Let's add an update and tell the graph to treat it as if it came from the \"chatbot\"."
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 5,
|
|
"id": "d16d95c3-b465-42ac-8015-26b669d45d1f",
|
|
"metadata": {},
|
|
"outputs": [
|
|
{
|
|
"data": {
|
|
"text/plain": [
|
|
"{'configurable': {'thread_id': '1',\n",
|
|
" 'thread_ts': '2024-05-06T22:27:57.350721+00:00'}}"
|
|
]
|
|
},
|
|
"execution_count": 5,
|
|
"metadata": {},
|
|
"output_type": "execute_result"
|
|
}
|
|
],
|
|
"source": [
|
|
"graph.update_state(\n",
|
|
" config,\n",
|
|
" {\"messages\": [AIMessage(content=\"I'm an AI expert!\")]},\n",
|
|
" # Which node for this function to act as. It will automatically continue\n",
|
|
" # processing as if this node just ran.\n",
|
|
" as_node=\"chatbot\",\n",
|
|
")"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"id": "5a1f0056-6b6f-425f-ac1a-0d4b0e9b85cc",
|
|
"metadata": {},
|
|
"source": [
|
|
"Check out the [LangSmith trace](https://smith.langchain.com/public/ce83989f-6e49-4bdd-bcd5-f54ca55c8d00/r/30b1406a-ae5b-4e9e-9fe5-032be6efb92e) for this update call at the provided link. **Notice** from the trace that the graph continues into the `tools_condition` edge. We just told the graph to treat the update `as_node=\"chatbot\"`. If we follow the diagram below and start from the `chatbot` node, we naturally end up in the `tools_condition` edge and then `__end__` since our updated message lacks tool calls."
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 6,
|
|
"id": "f4009ba6-dc0b-4216-ab0c-fbb104616f73",
|
|
"metadata": {},
|
|
"outputs": [
|
|
{
|
|
"data": {
|
|
"image/jpeg": "/9j/4AAQSkZJRgABAQAAAQABAAD/4gHYSUNDX1BST0ZJTEUAAQEAAAHIAAAAAAQwAABtbnRyUkdCIFhZWiAH4AABAAEAAAAAAABhY3NwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAA9tYAAQAAAADTLQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAlkZXNjAAAA8AAAACRyWFlaAAABFAAAABRnWFlaAAABKAAAABRiWFlaAAABPAAAABR3dHB0AAABUAAAABRyVFJDAAABZAAAAChnVFJDAAABZAAAAChiVFJDAAABZAAAAChjcHJ0AAABjAAAADxtbHVjAAAAAAAAAAEAAAAMZW5VUwAAAAgAAAAcAHMAUgBHAEJYWVogAAAAAAAAb6IAADj1AAADkFhZWiAAAAAAAABimQAAt4UAABjaWFlaIAAAAAAAACSgAAAPhAAAts9YWVogAAAAAAAA9tYAAQAAAADTLXBhcmEAAAAAAAQAAAACZmYAAPKnAAANWQAAE9AAAApbAAAAAAAAA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YwTHWX2lBbbiLYyFJUDsEHl6EGt/nP8Ern/wAr/UVsaJbvNO3MvUzQUcaGq969fiXLSlK7h9GFKUoCL3PhvYbnJckiM7BkuHa3bfIcjlZ3slQQQFHfrIJrA+SiB4vevbfuqb0q9V6i/UWKrOOSkyEfJRA8XvXtv3U+SiB4vevbfuqb0rOPU4+hLGqczIczwqsYUDKXcLkkEHs5c5xTZ19KAQk/mIIqVxIjECM3HjMtx47SQlDTSAlCAO4ADoBXupVcqk55SZXKUpfidxSlKrIilKUApSlARzJcGg5PPjTX5M2LJjtKZSuG/wBntKiCQeh31SK1nyVQfGL37b91TalWYkrJfwiuVOEneUU/kQn5KoPjF79t+6nyVQfGL37b91TalMR+XREcGlyLoiE/JVB8Yvftv3U+SqD4xe/bfuqbUpiPy6IYNLkXREJ+SqD4xe/bfup8lUHxi9+2/dU2pTEfl0QwaXIuiIT8lUHxi9+2/dXrkcIbXLaU1Iud4fZV85tczaVD6D0qdUrKqyTuvRGVRpJ3UV0QpSlVFp//2Q==",
|
|
"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(graph.get_graph().draw_mermaid_png()))\n",
|
|
"except Exception:\n",
|
|
" # This requires some extra dependencies and is optional\n",
|
|
" pass"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"id": "96cd4ffa-8fb2-4bd6-bef9-564cbfe7e3ab",
|
|
"metadata": {},
|
|
"source": [
|
|
"Inspect the current state as before to confirm the checkpoint reflects our manual updates."
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 7,
|
|
"id": "d420e813-a8c7-415d-ab31-5298d42491e4",
|
|
"metadata": {},
|
|
"outputs": [
|
|
{
|
|
"name": "stdout",
|
|
"output_type": "stream",
|
|
"text": [
|
|
"[ToolMessage(content='LangGraph is a library for building stateful, multi-actor applications with LLMs.', id='14589ef1-15db-4a75-82a6-d57c40a216d0', tool_call_id='toolu_01DTyDpJ1kKdNps5yxv3AGJd'), AIMessage(content='LangGraph is a library for building stateful, multi-actor applications with LLMs.', id='1c657bfb-7690-44c7-a26d-d0d22453013d'), AIMessage(content=\"I'm an AI expert!\", id='acd668e3-ba31-42c0-843c-00d0994d5885')]\n",
|
|
"()\n"
|
|
]
|
|
}
|
|
],
|
|
"source": [
|
|
"snapshot = graph.get_state(config)\n",
|
|
"print(snapshot.values[\"messages\"][-3:])\n",
|
|
"print(snapshot.next)"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"id": "380222f4-65fa-4962-afe6-6a715fadb2de",
|
|
"metadata": {},
|
|
"source": [
|
|
"**Notice**: that we've continued to add AI messages to the state. Since we are acting as the `chatbot` and responding with an AIMessage that doesn't contain `tool_calls`, the graph knows that it has entered a finished state (`next` is empty).\n",
|
|
"\n",
|
|
"#### What if you want to **overwrite** existing messages? \n",
|
|
"\n",
|
|
"The [`add_messages`](https://langchain-ai.github.io/langgraph/reference/graphs/?h=add+messages#add_messages) function we used to annotate our graph's `State` above controls how updates are made to the `messages` key. This function looks at any message IDs in the new `messages` list. If the ID matches a message in the existing state, [`add_messages`](https://langchain-ai.github.io/langgraph/reference/graphs/?h=add+messages#add_messages) overwrites the existing message with the new content. \n",
|
|
"\n",
|
|
"As an example, let's update the tool invocation to make sure we get good results from our search engine! First, start a new thread:"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 8,
|
|
"id": "9fc99c7e-b61d-4aec-9c62-042798185ec3",
|
|
"metadata": {},
|
|
"outputs": [
|
|
{
|
|
"name": "stdout",
|
|
"output_type": "stream",
|
|
"text": [
|
|
"================================\u001b[1m Human Message \u001b[0m=================================\n",
|
|
"\n",
|
|
"I'm learning LangGraph. Could you do some research on it for me?\n",
|
|
"==================================\u001b[1m Ai Message \u001b[0m==================================\n",
|
|
"\n",
|
|
"[{'id': 'toolu_013MvjoDHnv476ZGzyPFZhrR', 'input': {'query': 'LangGraph'}, 'name': 'tavily_search_results_json', 'type': 'tool_use'}]\n",
|
|
"Tool Calls:\n",
|
|
" tavily_search_results_json (toolu_013MvjoDHnv476ZGzyPFZhrR)\n",
|
|
" Call ID: toolu_013MvjoDHnv476ZGzyPFZhrR\n",
|
|
" Args:\n",
|
|
" query: LangGraph\n"
|
|
]
|
|
}
|
|
],
|
|
"source": [
|
|
"user_input = \"I'm learning LangGraph. Could you do some research on it for me?\"\n",
|
|
"config = {\"configurable\": {\"thread_id\": \"2\"}} # we'll use thread_id = 2 here\n",
|
|
"events = graph.stream(\n",
|
|
" {\"messages\": [(\"user\", user_input)]}, config, stream_mode=\"values\"\n",
|
|
")\n",
|
|
"for event in events:\n",
|
|
" if \"messages\" in event:\n",
|
|
" event[\"messages\"][-1].pretty_print()"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"id": "8b019fc6-7826-4291-9178-6cecb5d7b3d0",
|
|
"metadata": {},
|
|
"source": [
|
|
"**Next,** let's update the tool invocation for our agent. Maybe we want to search for human-in-the-loop workflows in particular."
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 9,
|
|
"id": "7215533a-b7e2-4b2d-bc1d-5122b1d06b8b",
|
|
"metadata": {},
|
|
"outputs": [
|
|
{
|
|
"name": "stdout",
|
|
"output_type": "stream",
|
|
"text": [
|
|
"Original\n",
|
|
"Message ID run-59283969-1076-45fe-bee8-ebfccab163c3-0\n",
|
|
"{'name': 'tavily_search_results_json', 'args': {'query': 'LangGraph'}, 'id': 'toolu_013MvjoDHnv476ZGzyPFZhrR'}\n",
|
|
"Updated\n",
|
|
"{'name': 'tavily_search_results_json', 'args': {'query': 'LangGraph human-in-the-loop workflow'}, 'id': 'toolu_013MvjoDHnv476ZGzyPFZhrR'}\n",
|
|
"Message ID run-59283969-1076-45fe-bee8-ebfccab163c3-0\n",
|
|
"\n",
|
|
"\n",
|
|
"Tool calls\n"
|
|
]
|
|
},
|
|
{
|
|
"data": {
|
|
"text/plain": [
|
|
"[{'name': 'tavily_search_results_json',\n",
|
|
" 'args': {'query': 'LangGraph human-in-the-loop workflow'},\n",
|
|
" 'id': 'toolu_013MvjoDHnv476ZGzyPFZhrR'}]"
|
|
]
|
|
},
|
|
"execution_count": 9,
|
|
"metadata": {},
|
|
"output_type": "execute_result"
|
|
}
|
|
],
|
|
"source": [
|
|
"from langchain_core.messages import AIMessage\n",
|
|
"\n",
|
|
"snapshot = graph.get_state(config)\n",
|
|
"existing_message = snapshot.values[\"messages\"][-1]\n",
|
|
"print(\"Original\")\n",
|
|
"print(\"Message ID\", existing_message.id)\n",
|
|
"print(existing_message.tool_calls[0])\n",
|
|
"new_tool_call = existing_message.tool_calls[0].copy()\n",
|
|
"new_tool_call[\"args\"][\"query\"] = \"LangGraph human-in-the-loop workflow\"\n",
|
|
"new_message = AIMessage(\n",
|
|
" content=existing_message.content,\n",
|
|
" tool_calls=[new_tool_call],\n",
|
|
" # Important! The ID is how LangGraph knows to REPLACE the message in the state rather than APPEND this messages\n",
|
|
" id=existing_message.id,\n",
|
|
")\n",
|
|
"\n",
|
|
"print(\"Updated\")\n",
|
|
"print(new_message.tool_calls[0])\n",
|
|
"print(\"Message ID\", new_message.id)\n",
|
|
"graph.update_state(config, {\"messages\": [new_message]})\n",
|
|
"\n",
|
|
"print(\"\\n\\nTool calls\")\n",
|
|
"graph.get_state(config).values[\"messages\"][-1].tool_calls"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"id": "680f0ebd-ebce-4de6-8a9b-37d3d4ef0234",
|
|
"metadata": {},
|
|
"source": [
|
|
"**Notice** that we've modified the AI's tool invocation to search for \"LangGraph human-in-the-loop workflow\" instead of the simple \"LangGraph\".\n",
|
|
"\n",
|
|
"Check out the [LangSmith trace](https://smith.langchain.com/public/cd7c09a6-758d-41d4-8de1-64ab838b2338/r) to see the state update call - you can see our new message has successfully updated the previous AI message.\n",
|
|
"\n",
|
|
"Resume the graph by streaming with an input of `None` and the existing config."
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 10,
|
|
"id": "03a09bfc-3d90-4e54-878f-22e3cb28a418",
|
|
"metadata": {},
|
|
"outputs": [
|
|
{
|
|
"name": "stdout",
|
|
"output_type": "stream",
|
|
"text": [
|
|
"=================================\u001b[1m Tool Message \u001b[0m=================================\n",
|
|
"Name: tavily_search_results_json\n",
|
|
"\n",
|
|
"[{\"url\": \"https://langchain-ai.github.io/langgraph/how-tos/human-in-the-loop/\", \"content\": \"Human-in-the-loop\\u00b6 When creating LangGraph agents, it is often nice to add a human in the loop component. This can be helpful when giving them access to tools. ... from langgraph.graph import MessageGraph, END # Define a new graph workflow = MessageGraph # Define the two nodes we will cycle between workflow. add_node (\\\"agent\\\", call_model) ...\"}, {\"url\": \"https://langchain-ai.github.io/langgraph/how-tos/chat_agent_executor_with_function_calling/human-in-the-loop/\", \"content\": \"Human-in-the-loop. In this example we will build a ReAct Agent that has a human in the loop. We will use the human to approve specific actions. This examples builds off the base chat executor. It is highly recommended you learn about that executor before going through this notebook. You can find documentation for that example here.\"}]\n",
|
|
"==================================\u001b[1m Ai Message \u001b[0m==================================\n",
|
|
"\n",
|
|
"Based on the search results, LangGraph appears to be a framework for building AI agents that can interact with humans in a conversational way. The key points I gathered are:\n",
|
|
"\n",
|
|
"- LangGraph allows for \"human-in-the-loop\" workflows, where a human can be involved in approving or reviewing actions taken by the AI agent.\n",
|
|
"- This can be useful for giving the AI agent access to various tools and capabilities, with the human able to provide oversight and guidance.\n",
|
|
"- The framework includes components like \"MessageGraph\" for defining the conversational flow between the agent and human.\n",
|
|
"\n",
|
|
"Overall, LangGraph seems to be a way to create conversational AI agents that can leverage human input and guidance, rather than operating in a fully autonomous way. Let me know if you need any clarification or have additional questions!\n"
|
|
]
|
|
}
|
|
],
|
|
"source": [
|
|
"events = graph.stream(None, config, stream_mode=\"values\")\n",
|
|
"for event in events:\n",
|
|
" if \"messages\" in event:\n",
|
|
" event[\"messages\"][-1].pretty_print()"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"id": "090b680b-f53f-4af2-a432-45f8c5a10779",
|
|
"metadata": {},
|
|
"source": [
|
|
"Check out the [trace](https://smith.langchain.com/public/2d633326-14ad-4248-a391-2757d01851c4/r/6464f2f2-edb4-4ef3-8f48-ee4e249f2ad0) to see the tool call and later LLM response. **Notice** that now the graph queries the search engine using our updated query term - we were able to manually override the LLM's search here!\n",
|
|
"\n",
|
|
"All of this is reflected in the graph's checkpointed memory, meaning if we continue the conversation, it will recall all the _modified_ state."
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 15,
|
|
"id": "11d5b934-6d8b-4f52-a3bc-b3daa7207e00",
|
|
"metadata": {},
|
|
"outputs": [
|
|
{
|
|
"name": "stdout",
|
|
"output_type": "stream",
|
|
"text": [
|
|
"================================\u001b[1m Human Message \u001b[0m=================================\n",
|
|
"\n",
|
|
"Remember what I'm learning about?\n",
|
|
"==================================\u001b[1m Ai Message \u001b[0m==================================\n",
|
|
"\n",
|
|
"Ah yes, now I remember - you mentioned earlier that you are learning about LangGraph.\n",
|
|
"\n",
|
|
"LangGraph is the framework I researched in my previous response, which is for building conversational AI agents that can incorporate human input and oversight.\n",
|
|
"\n",
|
|
"So based on our earlier discussion, it seems you are currently learning about and exploring the LangGraph system for creating human-in-the-loop AI agents. Please let me know if I have the right understanding now.\n"
|
|
]
|
|
}
|
|
],
|
|
"source": [
|
|
"events = graph.stream(\n",
|
|
" {\n",
|
|
" \"messages\": (\n",
|
|
" \"user\",\n",
|
|
" \"Remember what I'm learning about?\",\n",
|
|
" )\n",
|
|
" },\n",
|
|
" config,\n",
|
|
" stream_mode=\"values\",\n",
|
|
")\n",
|
|
"for event in events:\n",
|
|
" if \"messages\" in event:\n",
|
|
" event[\"messages\"][-1].pretty_print()"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"id": "a5166e1b-96a6-4ac0-88a1-bf32a422134a",
|
|
"metadata": {},
|
|
"source": [
|
|
"**Congratulations!** You've used `interrupt_before` and `update_state` to manually modify the state as a part of a human-in-the-loop workflow. Interruptions and state modifications let you control how the agent behaves. Combined with persistent checkpointing, it means you can `pause` an action and `resume` at any point. Your user doesn't have to be available when the graph interrupts!\n",
|
|
"\n",
|
|
"The graph code for this section is identical to previous ones. The key snippets to remember are to add `.compile(..., interrupt_before=[...])` (or `interrupt_after`) if you want to explicitly pause the graph whenever it reaches a node. Then you can use `update_state` to modify the checkpoint and control how the graph should proceed."
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"id": "d88d4c9e-65c8-4093-a6c2-c261475f7c07",
|
|
"metadata": {},
|
|
"source": [
|
|
"## Part 6: Customizing State\n",
|
|
"\n",
|
|
"So far, we've relied on a simple state (it's just a list of messages!). You can go far with this simple state, but if you want to define complex behavior without relying on the message list, you can add additional fields to the state. In this section, we will extend our chat bot with a new node to illustrate this.\n",
|
|
"\n",
|
|
"In the examples above, we involved a human deterministically: the graph __always__ interrupted whenever an tool was invoked. Suppose we wanted our chat bot to have the choice of relying on a human.\n",
|
|
"\n",
|
|
"One way to do this is to create a passthrough \"human\" node, before which the graph will always stop. We will only execute this node if the LLM invokes a \"human\" tool. For our convenience, we will include an \"ask_human\" flag in our graph state that we will flip if the LLM calls this tool.\n",
|
|
"\n",
|
|
"Below, define this new graph, with an updated `State`"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 1,
|
|
"id": "3cf7e042-1718-4625-ae30-a9917f595449",
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"from typing import Annotated\n",
|
|
"\n",
|
|
"from langchain_anthropic import ChatAnthropic\n",
|
|
"from langchain_community.tools.tavily_search import TavilySearchResults\n",
|
|
"from langchain_core.messages import BaseMessage\n",
|
|
"from typing_extensions import TypedDict\n",
|
|
"\n",
|
|
"from langgraph.checkpoint.sqlite import SqliteSaver\n",
|
|
"from langgraph.graph import StateGraph, START\n",
|
|
"from langgraph.graph.message import add_messages\n",
|
|
"from langgraph.prebuilt import ToolNode, tools_condition\n",
|
|
"\n",
|
|
"\n",
|
|
"class State(TypedDict):\n",
|
|
" messages: Annotated[list, add_messages]\n",
|
|
" # This flag is new\n",
|
|
" ask_human: bool"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"id": "e87f2cb8-c066-4b54-acc4-e8c7399c5f3d",
|
|
"metadata": {},
|
|
"source": [
|
|
"Next, define a schema to show the model to let it decide to request assistance."
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 2,
|
|
"id": "e5192e54-6a28-42fe-a8a7-62d45d61f994",
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"from langchain_core.pydantic_v1 import BaseModel\n",
|
|
"\n",
|
|
"\n",
|
|
"class RequestAssistance(BaseModel):\n",
|
|
" \"\"\"Escalate the conversation to an expert. Use this if you are unable to assist directly or if the user requires support beyond your permissions.\n",
|
|
"\n",
|
|
" To use this function, relay the user's 'request' so the expert can provide the right guidance.\n",
|
|
" \"\"\"\n",
|
|
"\n",
|
|
" request: str"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"id": "2b19c61b-2087-463b-adf8-96dbc193f41c",
|
|
"metadata": {},
|
|
"source": [
|
|
"Next, define the chatbot node. The primary modification here is flip the `ask_human` flag if we see that the chat bot has invoked the `RequestAssistance` flag."
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 3,
|
|
"id": "fa59b266-14e5-4c75-8b3d-54fac28e8290",
|
|
"metadata": {},
|
|
"outputs": [
|
|
{
|
|
"name": "stderr",
|
|
"output_type": "stream",
|
|
"text": [
|
|
"/Users/wfh/code/lc/langchain/libs/core/langchain_core/_api/beta_decorator.py:87: LangChainBetaWarning: The method `ChatAnthropic.bind_tools` is in beta. It is actively being worked on, so the API may change.\n",
|
|
" warn_beta(\n"
|
|
]
|
|
}
|
|
],
|
|
"source": [
|
|
"tool = TavilySearchResults(max_results=2)\n",
|
|
"tools = [tool]\n",
|
|
"llm = ChatAnthropic(model=\"claude-3-haiku-20240307\")\n",
|
|
"# We can bind the llm to a tool definition, a pydantic model, or a json schema\n",
|
|
"llm_with_tools = llm.bind_tools(tools + [RequestAssistance])\n",
|
|
"\n",
|
|
"\n",
|
|
"def chatbot(state: State):\n",
|
|
" response = llm_with_tools.invoke(state[\"messages\"])\n",
|
|
" ask_human = False\n",
|
|
" if (\n",
|
|
" response.tool_calls\n",
|
|
" and response.tool_calls[0][\"name\"] == RequestAssistance.__name__\n",
|
|
" ):\n",
|
|
" ask_human = True\n",
|
|
" return {\"messages\": [response], \"ask_human\": ask_human}"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"id": "04ca0f57-2519-49c2-9499-888b5a884897",
|
|
"metadata": {},
|
|
"source": [
|
|
"Next, create the graph builder and add the chatbot and tools nodes to the graph, same as before."
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 4,
|
|
"id": "3f4464d2-288b-4689-aaf0-329a55dcb85c",
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"graph_builder = StateGraph(State)\n",
|
|
"\n",
|
|
"graph_builder.add_node(\"chatbot\", chatbot)\n",
|
|
"graph_builder.add_node(\"tools\", ToolNode(tools=[tool]))"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"id": "7f7a0ff3-b671-45c8-8157-ce5db411d370",
|
|
"metadata": {},
|
|
"source": [
|
|
"Next, create the \"human\" `node`. This `node` function is mostly a placeholder in our graph that will trigger an interrupt. If the human does __not__ manually update the state during the `interrupt`, it inserts a tool message so the LLM knows the user was requested but didn't respond. This node also unsets the `ask_human` flag so the graph knows not to revisit the node unless further requests are made."
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 5,
|
|
"id": "1d70b5a4-ce50-47dc-aa43-ffb5c48c46fc",
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"from langchain_core.messages import AIMessage, ToolMessage\n",
|
|
"\n",
|
|
"\n",
|
|
"def create_response(response: str, ai_message: AIMessage):\n",
|
|
" return ToolMessage(\n",
|
|
" content=response,\n",
|
|
" tool_call_id=ai_message.tool_calls[0][\"id\"],\n",
|
|
" )\n",
|
|
"\n",
|
|
"\n",
|
|
"def human_node(state: State):\n",
|
|
" new_messages = []\n",
|
|
" if not isinstance(state[\"messages\"][-1], ToolMessage):\n",
|
|
" # Typically, the user will have updated the state during the interrupt.\n",
|
|
" # If they choose not to, we will include a placeholder ToolMessage to\n",
|
|
" # let the LLM continue.\n",
|
|
" new_messages.append(\n",
|
|
" create_response(\"No response from human.\", state[\"messages\"][-1])\n",
|
|
" )\n",
|
|
" return {\n",
|
|
" # Append the new messages\n",
|
|
" \"messages\": new_messages,\n",
|
|
" # Unset the flag\n",
|
|
" \"ask_human\": False,\n",
|
|
" }\n",
|
|
"\n",
|
|
"\n",
|
|
"graph_builder.add_node(\"human\", human_node)"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"id": "d56e5c65-f7b7-48bd-b0b5-fc8e590eca7d",
|
|
"metadata": {},
|
|
"source": [
|
|
"Next, define the conditional logic. The `select_next_node` will route to the `human` node if the flag is set. Otherwise, it lets the prebuilt `tools_condition` function choose the next node.\n",
|
|
"\n",
|
|
"Recall that the `tools_condition` function simply checks to see if the `chatbot` has responded with any `tool_calls` in its response message. If so, it routes to the `action` node. Otherwise, it ends the graph."
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 6,
|
|
"id": "586a0d07-8303-47f4-b3cf-3bdd043e762b",
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"def select_next_node(state: State):\n",
|
|
" if state[\"ask_human\"]:\n",
|
|
" return \"human\"\n",
|
|
" # Otherwise, we can route as before\n",
|
|
" return tools_condition(state)\n",
|
|
"\n",
|
|
"\n",
|
|
"graph_builder.add_conditional_edges(\n",
|
|
" \"chatbot\",\n",
|
|
" select_next_node,\n",
|
|
" {\"human\": \"human\", \"tools\": \"tools\", \"__end__\": \"__end__\"},\n",
|
|
")"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"id": "66cd0bb1-b13e-477e-a08a-a7e657e2c19e",
|
|
"metadata": {},
|
|
"source": [
|
|
"Finally, add the simple directed edges and compile the graph. These edges instruct the graph to **always** flow from node `a`->`b` whenever `a` finishes executing."
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 7,
|
|
"id": "84101737-0048-4635-9f68-45b0c508b6b6",
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"# The rest is the same\n",
|
|
"graph_builder.add_edge(\"tools\", \"chatbot\")\n",
|
|
"graph_builder.add_edge(\"human\", \"chatbot\")\n",
|
|
"graph_builder.add_edge(START, \"chatbot\")\n",
|
|
"memory = SqliteSaver.from_conn_string(\":memory:\")\n",
|
|
"graph = graph_builder.compile(\n",
|
|
" checkpointer=memory,\n",
|
|
" # We interrupt before 'human' here instead.\n",
|
|
" interrupt_before=[\"human\"],\n",
|
|
")"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"id": "7f855593-8690-4a18-9ef8-7f3ccdc335bf",
|
|
"metadata": {},
|
|
"source": [
|
|
"If you have the visualization dependencies installed, you can see the graph structure below:"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 8,
|
|
"id": "b3220ae2-cba0-4447-96d1-eb0be4684e59",
|
|
"metadata": {},
|
|
"outputs": [
|
|
{
|
|
"data": {
|
|
"image/jpeg": "/9j/4AAQSkZJRgABAQAAAQABAAD/4gHYSUNDX1BST0ZJTEUAAQEAAAHIAAAAAAQwAABtbnRyUkdCIFhZ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D2vmvffwXmzhPiHECxcy9tniyTIysB/LyFu/61NETPqcTGdU5mYWJw1DA0m1MdThpVmku7OBgaCT3k7d5PiT1KzURQtuTuyIIiLACIiALS6o0pU1bVqwW5LEPm04sxSVZOze14a5nf8Ake4frW6RbRk4u6DV9zIT81VH2xm/ffwT5qqPtjN++/gpsi2zH4dEQ5NLkXREJ+aqj7Yzfvv4J81VH2xm/ffwU2RMx+HRDJpci6IhPzVUfbGb99/BPmqo+2M377+CmyJmPw6IZNLkXREJ+aqj7Yzfvv4J81VH2xm/ffwU2RMx+HRDJpci6IhPzVUfbGb99/BSjCYivp/D0cZUDhVpwsrxB7uZ3K0ADc+J2CzkWHOTVu43jCMPwpLyCIi0Nz//2Q==",
|
|
"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(graph.get_graph().draw_mermaid_png()))\n",
|
|
"except Exception:\n",
|
|
" # This requires some extra dependencies and is optional\n",
|
|
" pass"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"id": "a3b73851-810e-4466-89d8-37fba87e8494",
|
|
"metadata": {},
|
|
"source": [
|
|
"The chat bot can either request help from a human (chatbot->select->human), invoke the search engine tool (chatbot->select->action), or directly respond (chatbot->select->__end__). Once an action or request has been made, the graph will transition back to the `chatbot` node to continue operations.\n",
|
|
"\n",
|
|
"Let's see this graph in action. We will request for expert assistance to illustrate our graph."
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 9,
|
|
"id": "c1955d79-a1e4-47d0-ba79-b45bd5752a23",
|
|
"metadata": {},
|
|
"outputs": [
|
|
{
|
|
"name": "stdout",
|
|
"output_type": "stream",
|
|
"text": [
|
|
"================================\u001b[1m Human Message \u001b[0m=================================\n",
|
|
"\n",
|
|
"I need some expert guidance for building this AI agent. Could you request assistance for me?\n",
|
|
"==================================\u001b[1m Ai Message \u001b[0m==================================\n",
|
|
"\n",
|
|
"[{'id': 'toolu_017XaQuVsoAyfXeTfDyv55Pc', 'input': {'request': 'I need some expert guidance for building this AI agent.'}, 'name': 'RequestAssistance', 'type': 'tool_use'}]\n",
|
|
"Tool Calls:\n",
|
|
" RequestAssistance (toolu_017XaQuVsoAyfXeTfDyv55Pc)\n",
|
|
" Call ID: toolu_017XaQuVsoAyfXeTfDyv55Pc\n",
|
|
" Args:\n",
|
|
" request: I need some expert guidance for building this AI agent.\n"
|
|
]
|
|
}
|
|
],
|
|
"source": [
|
|
"user_input = \"I need some expert guidance for building this AI agent. Could you request assistance for me?\"\n",
|
|
"config = {\"configurable\": {\"thread_id\": \"1\"}}\n",
|
|
"# The config is the **second positional argument** to stream() or invoke()!\n",
|
|
"events = graph.stream(\n",
|
|
" {\"messages\": [(\"user\", user_input)]}, config, stream_mode=\"values\"\n",
|
|
")\n",
|
|
"for event in events:\n",
|
|
" if \"messages\" in event:\n",
|
|
" event[\"messages\"][-1].pretty_print()"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"id": "b3945ea4-8dbd-4e14-ae2a-34da7f05a0c1",
|
|
"metadata": {},
|
|
"source": [
|
|
"**Notice:** the LLM has invoked the \"`RequestAssistance`\" tool we provided it, and the interrupt has been set. Let's inspect the graph state to confirm."
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 10,
|
|
"id": "5320ba05-5696-4194-8278-5385c571264d",
|
|
"metadata": {},
|
|
"outputs": [
|
|
{
|
|
"data": {
|
|
"text/plain": [
|
|
"('human',)"
|
|
]
|
|
},
|
|
"execution_count": 10,
|
|
"metadata": {},
|
|
"output_type": "execute_result"
|
|
}
|
|
],
|
|
"source": [
|
|
"snapshot = graph.get_state(config)\n",
|
|
"snapshot.next"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"id": "ed2dd02e-f0a6-4f63-a7d6-e49ecf40db21",
|
|
"metadata": {},
|
|
"source": [
|
|
"The graph state is indeed **interrupted** before the `'human'` node. We can act as the \"expert\" in this scenario and manually update the state by adding a new ToolMessage with our input.\n",
|
|
"\n",
|
|
"Next, respond to the chatbot's request by:\n",
|
|
"1. Creating a `ToolMessage` with our response. This will be passed back to the `chatbot`.\n",
|
|
"2. Calling `update_state` to manually update the graph state."
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 11,
|
|
"id": "2cbac924-61ce-4282-9b1c-77f9090ea1f5",
|
|
"metadata": {},
|
|
"outputs": [
|
|
{
|
|
"data": {
|
|
"text/plain": [
|
|
"{'configurable': {'thread_id': '1',\n",
|
|
" 'thread_ts': '2024-05-06T22:31:39.973392+00:00'}}"
|
|
]
|
|
},
|
|
"execution_count": 11,
|
|
"metadata": {},
|
|
"output_type": "execute_result"
|
|
}
|
|
],
|
|
"source": [
|
|
"ai_message = snapshot.values[\"messages\"][-1]\n",
|
|
"human_response = (\n",
|
|
" \"We, the experts are here to help! We'd recommend you check out LangGraph to build your agent.\"\n",
|
|
" \" It's much more reliable and extensible than simple autonomous agents.\"\n",
|
|
")\n",
|
|
"tool_message = create_response(human_response, ai_message)\n",
|
|
"graph.update_state(config, {\"messages\": [tool_message]})"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"id": "79492363-7fc6-4ec7-977d-9030648029bc",
|
|
"metadata": {},
|
|
"source": [
|
|
"You can inspect the state to confirm our response was added."
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 12,
|
|
"id": "4b986c66-1c65-4da8-a404-db7e28f8364e",
|
|
"metadata": {},
|
|
"outputs": [
|
|
{
|
|
"data": {
|
|
"text/plain": [
|
|
"[HumanMessage(content='I need some expert guidance for building this AI agent. Could you request assistance for me?', id='ab75eb9d-cce7-4e44-8de7-b0b375a86972'),\n",
|
|
" AIMessage(content=[{'id': 'toolu_017XaQuVsoAyfXeTfDyv55Pc', 'input': {'request': 'I need some expert guidance for building this AI agent.'}, 'name': 'RequestAssistance', 'type': 'tool_use'}], response_metadata={'id': 'msg_0199PiK6kmVAbeo1qmephKDq', 'model': 'claude-3-haiku-20240307', 'stop_reason': 'tool_use', 'stop_sequence': None, 'usage': {'input_tokens': 486, 'output_tokens': 63}}, id='run-ff07f108-5055-4343-8910-2fa40ead3fb9-0', tool_calls=[{'name': 'RequestAssistance', 'args': {'request': 'I need some expert guidance for building this AI agent.'}, 'id': 'toolu_017XaQuVsoAyfXeTfDyv55Pc'}]),\n",
|
|
" ToolMessage(content=\"We, the experts are here to help! We'd recommend you check out LangGraph to build your agent. It's much more reliable and extensible than simple autonomous agents.\", id='19f2eb9f-a742-46aa-9047-60909c30e64a', tool_call_id='toolu_017XaQuVsoAyfXeTfDyv55Pc')]"
|
|
]
|
|
},
|
|
"execution_count": 12,
|
|
"metadata": {},
|
|
"output_type": "execute_result"
|
|
}
|
|
],
|
|
"source": [
|
|
"graph.get_state(config).values[\"messages\"]"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"id": "ea6b8616-de10-44d6-a8f0-3ac73c3c3680",
|
|
"metadata": {},
|
|
"source": [
|
|
"Next, **resume** the graph by invoking it with `None` as the inputs."
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 13,
|
|
"id": "6b32914d-4d60-491f-8e11-1e6867e38ffd",
|
|
"metadata": {},
|
|
"outputs": [
|
|
{
|
|
"name": "stdout",
|
|
"output_type": "stream",
|
|
"text": [
|
|
"=================================\u001b[1m Tool Message \u001b[0m=================================\n",
|
|
"\n",
|
|
"We, the experts are here to help! We'd recommend you check out LangGraph to build your agent. It's much more reliable and extensible than simple autonomous agents.\n",
|
|
"==================================\u001b[1m Ai Message \u001b[0m==================================\n",
|
|
"\n",
|
|
"It looks like the experts have provided some guidance on how to build your AI agent. They suggested checking out LangGraph, which they say is more reliable and extensible than simple autonomous agents. Please let me know if you need any other assistance - I'm happy to help coordinate with the expert team further.\n"
|
|
]
|
|
}
|
|
],
|
|
"source": [
|
|
"events = graph.stream(None, config, stream_mode=\"values\")\n",
|
|
"for event in events:\n",
|
|
" if \"messages\" in event:\n",
|
|
" event[\"messages\"][-1].pretty_print()"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"id": "48e0559b-d653-4dab-8928-b001004d14cb",
|
|
"metadata": {},
|
|
"source": [
|
|
"**Notice** that the chat bot has incorporated the updated state in its final response. Since **everything** was checkpointed, the \"expert\" human in the loop could perform the update at any time without impacting the graph's execution.\n",
|
|
"\n",
|
|
"**Congratulations!** you've now added an additional node to your assistant graph to let the chat bot decide for itself whether or not it needs to interrupt execution. You did so by updating the graph `State` with a new `ask_human` field and modifying the interruption logic when compiling the graph. This lets you dynamically include a human in the loop while maintaining full **memory** every time you execute the graph.\n",
|
|
"\n",
|
|
"We're almost done with the tutorial, but there is one more concept we'd like to review before finishing that connects `checkpointing` and `state updates`. \n",
|
|
"\n",
|
|
"This section's code is reproduced below for your reference.\n",
|
|
"\n",
|
|
"<details>\n",
|
|
"<summary>Full Code</summary>\n",
|
|
" <pre>\n",
|
|
"\n",
|
|
"```python\n",
|
|
"from typing import Annotated\n",
|
|
"\n",
|
|
"from langchain_anthropic import ChatAnthropic\n",
|
|
"from langchain_community.tools.tavily_search import TavilySearchResults\n",
|
|
"from langchain_core.messages import BaseMessage\n",
|
|
"from langchain_core.pydantic_v1 import BaseModel\n",
|
|
"from typing_extensions import TypedDict\n",
|
|
"\n",
|
|
"from langgraph.checkpoint.sqlite import SqliteSaver\n",
|
|
"from langgraph.graph import StateGraph\n",
|
|
"from langgraph.graph.message import add_messages\n",
|
|
"from langgraph.prebuilt import ToolNode, tools_condition\n",
|
|
"\n",
|
|
"\n",
|
|
"class State(TypedDict):\n",
|
|
" messages: Annotated[list, add_messages]\n",
|
|
" # This flag is new\n",
|
|
" ask_human: bool\n",
|
|
"\n",
|
|
"\n",
|
|
"class RequestAssistance(BaseModel):\n",
|
|
" \"\"\"Escalate the conversation to an expert. Use this if you are unable to assist directly or if the user requires support beyond your permissions.\n",
|
|
"\n",
|
|
" To use this function, relay the user's 'request' so the expert can provide the right guidance.\n",
|
|
" \"\"\"\n",
|
|
"\n",
|
|
" request: str\n",
|
|
"\n",
|
|
"\n",
|
|
"tool = TavilySearchResults(max_results=2)\n",
|
|
"tools = [tool]\n",
|
|
"llm = ChatAnthropic(model=\"claude-3-haiku-20240307\")\n",
|
|
"# We can bind the llm to a tool definition, a pydantic model, or a json schema\n",
|
|
"llm_with_tools = llm.bind_tools(tools + [RequestAssistance])\n",
|
|
"\n",
|
|
"\n",
|
|
"def chatbot(state: State):\n",
|
|
" response = llm_with_tools.invoke(state[\"messages\"])\n",
|
|
" ask_human = False\n",
|
|
" if (\n",
|
|
" response.tool_calls\n",
|
|
" and response.tool_calls[0][\"name\"] == RequestAssistance.__name__\n",
|
|
" ):\n",
|
|
" ask_human = True\n",
|
|
" return {\"messages\": [response], \"ask_human\": ask_human}\n",
|
|
"\n",
|
|
"\n",
|
|
"graph_builder = StateGraph(State)\n",
|
|
"\n",
|
|
"graph_builder.add_node(\"chatbot\", chatbot)\n",
|
|
"graph_builder.add_node(\"tools\", ToolNode(tools=[tool]))\n",
|
|
"\n",
|
|
"\n",
|
|
"def create_response(response: str, ai_message: AIMessage):\n",
|
|
" return ToolMessage(\n",
|
|
" content=response,\n",
|
|
" tool_call_id=ai_message.tool_calls[0][\"id\"],\n",
|
|
" )\n",
|
|
"\n",
|
|
"\n",
|
|
"def human_node(state: State):\n",
|
|
" new_messages = []\n",
|
|
" if not isinstance(state[\"messages\"][-1], ToolMessage):\n",
|
|
" # Typically, the user will have updated the state during the interrupt.\n",
|
|
" # If they choose not to, we will include a placeholder ToolMessage to\n",
|
|
" # let the LLM continue.\n",
|
|
" new_messages.append(\n",
|
|
" create_response(\"No response from human.\", state[\"messages\"][-1])\n",
|
|
" )\n",
|
|
" return {\n",
|
|
" # Append the new messages\n",
|
|
" \"messages\": new_messages,\n",
|
|
" # Unset the flag\n",
|
|
" \"ask_human\": False,\n",
|
|
" }\n",
|
|
"\n",
|
|
"\n",
|
|
"graph_builder.add_node(\"human\", human_node)\n",
|
|
"\n",
|
|
"\n",
|
|
"def select_next_node(state: State):\n",
|
|
" if state[\"ask_human\"]:\n",
|
|
" return \"human\"\n",
|
|
" # Otherwise, we can route as before\n",
|
|
" return tools_condition(state)\n",
|
|
"\n",
|
|
"\n",
|
|
"graph_builder.add_conditional_edges(\n",
|
|
" \"chatbot\",\n",
|
|
" select_next_node,\n",
|
|
" {\"human\": \"human\", \"tools\": \"tools\", \"__end__\": \"__end__\"},\n",
|
|
")\n",
|
|
"graph_builder.add_edge(\"tools\", \"chatbot\")\n",
|
|
"graph_builder.add_edge(\"human\", \"chatbot\")\n",
|
|
"graph_builder.set_entry_point(\"chatbot\")\n",
|
|
"memory = SqliteSaver.from_conn_string(\":memory:\")\n",
|
|
"graph = graph_builder.compile(\n",
|
|
" checkpointer=memory,\n",
|
|
" interrupt_before=[\"human\"],\n",
|
|
")\n",
|
|
"```\n",
|
|
"</pre>\n",
|
|
"</details>"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"id": "05283db2-2f26-4800-8eda-78a4468a3d8f",
|
|
"metadata": {},
|
|
"source": [
|
|
"## Part 7: Time Travel\n",
|
|
"\n",
|
|
"In a typical chat bot workflow, the user interacts with the bot 1 or more times to accomplish a task. In the previous sections, we saw how to add memory and a human-in-the-loop to be able to checkpoint our graph state and manually override the state to control future responses.\n",
|
|
"\n",
|
|
"But what if you want to let your user start from a previous response and \"branch off\" to explore a separate outcome? Or what if you want users to be able to \"rewind\" your assistant's work to fix some mistakes or try a different strategy (common in applications like autonomous software engineers)?\n",
|
|
"\n",
|
|
"You can create both of these experiences and more using LangGraph's built-in \"time travel\" functionality. \n",
|
|
"\n",
|
|
"In this section, you will \"rewind\" your graph by fetching a checkpoint using the graph's `get_state_history` method. You can then resume execution at this previous point in time.\n",
|
|
"\n",
|
|
"First, recall our chatbot graph. We don't need to make **any** changes from before:"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 2,
|
|
"id": "bb8a02de-a21b-4ef6-a714-7d6e44435e3a",
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"from typing import Annotated, Literal\n",
|
|
"\n",
|
|
"from langchain_anthropic import ChatAnthropic\n",
|
|
"from langchain_community.tools.tavily_search import TavilySearchResults\n",
|
|
"from langchain_core.messages import AIMessage, BaseMessage, ToolMessage\n",
|
|
"from langchain_core.pydantic_v1 import BaseModel\n",
|
|
"from typing_extensions import TypedDict\n",
|
|
"\n",
|
|
"from langgraph.checkpoint.sqlite import SqliteSaver\n",
|
|
"from langgraph.graph import StateGraph, START\n",
|
|
"from langgraph.graph.message import add_messages\n",
|
|
"from langgraph.prebuilt import ToolNode, tools_condition\n",
|
|
"\n",
|
|
"\n",
|
|
"class State(TypedDict):\n",
|
|
" messages: Annotated[list, add_messages]\n",
|
|
" # This flag is new\n",
|
|
" ask_human: bool\n",
|
|
"\n",
|
|
"\n",
|
|
"class RequestAssistance(BaseModel):\n",
|
|
" \"\"\"Escalate the conversation to an expert. Use this if you are unable to assist directly or if the user requires support beyond your permissions.\n",
|
|
"\n",
|
|
" To use this function, relay the user's 'request' so the expert can provide the right guidance.\n",
|
|
" \"\"\"\n",
|
|
"\n",
|
|
" request: str\n",
|
|
"\n",
|
|
"\n",
|
|
"tool = TavilySearchResults(max_results=2)\n",
|
|
"tools = [tool]\n",
|
|
"llm = ChatAnthropic(model=\"claude-3-haiku-20240307\")\n",
|
|
"# We can bind the llm to a tool definition, a pydantic model, or a json schema\n",
|
|
"llm_with_tools = llm.bind_tools(tools + [RequestAssistance])\n",
|
|
"\n",
|
|
"\n",
|
|
"def chatbot(state: State):\n",
|
|
" response = llm_with_tools.invoke(state[\"messages\"])\n",
|
|
" ask_human = False\n",
|
|
" if (\n",
|
|
" response.tool_calls\n",
|
|
" and response.tool_calls[0][\"name\"] == RequestAssistance.__name__\n",
|
|
" ):\n",
|
|
" ask_human = True\n",
|
|
" return {\"messages\": [response], \"ask_human\": ask_human}\n",
|
|
"\n",
|
|
"\n",
|
|
"graph_builder = StateGraph(State)\n",
|
|
"\n",
|
|
"graph_builder.add_node(\"chatbot\", chatbot)\n",
|
|
"graph_builder.add_node(\"tools\", ToolNode(tools=[tool]))\n",
|
|
"\n",
|
|
"\n",
|
|
"def create_response(response: str, ai_message: AIMessage):\n",
|
|
" return ToolMessage(\n",
|
|
" content=response,\n",
|
|
" tool_call_id=ai_message.tool_calls[0][\"id\"],\n",
|
|
" )\n",
|
|
"\n",
|
|
"\n",
|
|
"def human_node(state: State):\n",
|
|
" new_messages = []\n",
|
|
" if not isinstance(state[\"messages\"][-1], ToolMessage):\n",
|
|
" # Typically, the user will have updated the state during the interrupt.\n",
|
|
" # If they choose not to, we will include a placeholder ToolMessage to\n",
|
|
" # let the LLM continue.\n",
|
|
" new_messages.append(\n",
|
|
" create_response(\"No response from human.\", state[\"messages\"][-1])\n",
|
|
" )\n",
|
|
" return {\n",
|
|
" # Append the new messages\n",
|
|
" \"messages\": new_messages,\n",
|
|
" # Unset the flag\n",
|
|
" \"ask_human\": False,\n",
|
|
" }\n",
|
|
"\n",
|
|
"\n",
|
|
"graph_builder.add_node(\"human\", human_node)\n",
|
|
"\n",
|
|
"\n",
|
|
"def select_next_node(state: State) -> Literal[\"human\", \"tools\", \"__end__\"]:\n",
|
|
" if state[\"ask_human\"]:\n",
|
|
" return \"human\"\n",
|
|
" # Otherwise, we can route as before\n",
|
|
" return tools_condition(state)\n",
|
|
"\n",
|
|
"\n",
|
|
"graph_builder.add_conditional_edges(\n",
|
|
" \"chatbot\",\n",
|
|
" select_next_node,\n",
|
|
" {\"human\": \"human\", \"tools\": \"tools\", \"__end__\": \"__end__\"},\n",
|
|
")\n",
|
|
"graph_builder.add_edge(\"tools\", \"chatbot\")\n",
|
|
"graph_builder.add_edge(\"human\", \"chatbot\")\n",
|
|
"graph_builder.add_edge(START, \"chatbot\")\n",
|
|
"memory = SqliteSaver.from_conn_string(\":memory:\")\n",
|
|
"graph = graph_builder.compile(\n",
|
|
" checkpointer=memory,\n",
|
|
" interrupt_before=[\"human\"],\n",
|
|
")"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 3,
|
|
"id": "a7debb4a-2a3a-40b9-a48c-7052ec2c2726",
|
|
"metadata": {},
|
|
"outputs": [
|
|
{
|
|
"data": {
|
|
"image/jpeg": "/9j/4AAQSkZJRgABAQAAAQABAAD/4gHYSUNDX1BST0ZJTEUAAQEAAAHIAAAAAAQwAABtbnRyUkdCIFhZWiAH4AABAAEAAAAAAABhY3NwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAA9tYAAQAAAADTLQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAlkZXNjAAAA8AAAACRyWFlaAAABFAAAABRnWFlaAAABKAAAABRiWFlaAAABPAAAABR3dHB0AAABUAAAABRyVFJDAAABZAAAAChnVFJDAAABZAAAAChiVFJDAAABZAAAAChjcHJ0AAABjAAAADxtbHVjAAAAAAAAAAEAAAAMZW5VUwAAAAgAAAAcAHMAUgBHAEJYWVogAAAAAAAAb6IAADj1AAADkFhZWiAAAAAAAABimQAAt4UAABjaWFlaIAAAAAAAACSgAAAPhAAAts9YWVogAAAAAAAA9tYAAQAAAADTLXBhcmEAAAAAAAQAAAACZmYAAPKnAAANWQAAE9AAAApbAAAAAAAAAABtbHVjAAAAAAAAAAEAAAAMZW5VUwAAACAAAAAcAEcAbwBvAGcAbABlACAASQBuAGMALgAgADIAMAAxADb/2wBDAAMCAgMCAgMDAwMEAwMEBQgFBQQEBQoHBwYIDAoMDAsKCwsNDhIQDQ4RDgsLEBYQERMUFRUVDA8XGBYUGBIUFRT/2wBDAQMEBAUEBQkFBQkUDQsNF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a1oHQAAAAD1KT8K/5M9K/out/ZtXawH5NTzj8pHpPQmlX3f9JSiIrh6cIiICL5PhvgcnZksitLRsyHd8uPsSVy877kuDCA47+JBKwPmooe18177+Cm6KdV6i/USKrOO5SZCPmooe18177+CfNRQ9r5r338FN0Wc+px+RtnVOZkI+aih7XzXvv4L9HCjHg9ctmnD1G6fgpsixn1OIzqnMyN4jh3gsNcjuR1H2rsfVlm9M+xJGe7dheTyH/l28fWpIiKOU5Td5O5E25O7YREWhgIiIAiIgC0Gd0JhNRWfOrdLku7BvnlWV9ecgdwMkZDiB6iSPsW/RbxnKDvF2MptO6ISeFGO/m5XNNA7gLxP9ZBK/Pmooe18177+Cm6KTPqcSXOqczIR81FD2vmvffwXmzhPiHECxcy9tniyTIysB/LyFu/61NETPqcTGdU5mYWJw1DA0m1MdThpVmku7OBgaCT3k7d5PiT1KzURQtuTuyIIiLACIiALS6o0pU1bVqwW5LEPm04sxSVZOze14a5nf8Ake4frW6RbRk4u6DV9zIT81VH2xm/ffwT5qqPtjN++/gpsi2zH4dEQ5NLkXREJ+aqj7Yzfvv4J81VH2xm/ffwU2RMx+HRDJpci6IhPzVUfbGb99/BPmqo+2M377+CmyJmPw6IZNLkXREJ+aqj7Yzfvv4J81VH2xm/ffwU2RMx+HRDJpci6IhPzVUfbGb99/BSjCYivp/D0cZUDhVpwsrxB7uZ3K0ADc+J2CzkWHOTVu43jCMPwpLyCIi0Nz//2Q==",
|
|
"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(graph.get_graph().draw_mermaid_png()))\n",
|
|
"except Exception:\n",
|
|
" # This requires some extra dependencies and is optional\n",
|
|
" pass"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"id": "5414c482-215e-4cc0-9eef-4a8722d2f468",
|
|
"metadata": {},
|
|
"source": [
|
|
"Let's have our graph take a couple steps. Every step will be checkpointed in its state history:"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 4,
|
|
"id": "69071b02-c011-4b7f-90b1-8e89e032322d",
|
|
"metadata": {},
|
|
"outputs": [
|
|
{
|
|
"name": "stdout",
|
|
"output_type": "stream",
|
|
"text": [
|
|
"================================\u001b[1m Human Message \u001b[0m=================================\n",
|
|
"\n",
|
|
"I'm learning LangGraph. Could you do some research on it for me?\n",
|
|
"==================================\u001b[1m Ai Message \u001b[0m==================================\n",
|
|
"\n",
|
|
"[{'text': \"Okay, let me look into LangGraph for you. Here's what I found:\", 'type': 'text'}, {'id': 'toolu_011AQ2FT4RupVka2LVMV3Gci', 'input': {'query': 'LangGraph'}, 'name': 'tavily_search_results_json', 'type': 'tool_use'}]\n",
|
|
"Tool Calls:\n",
|
|
" tavily_search_results_json (toolu_011AQ2FT4RupVka2LVMV3Gci)\n",
|
|
" Call ID: toolu_011AQ2FT4RupVka2LVMV3Gci\n",
|
|
" Args:\n",
|
|
" query: LangGraph\n",
|
|
"=================================\u001b[1m Tool Message \u001b[0m=================================\n",
|
|
"Name: tavily_search_results_json\n",
|
|
"\n",
|
|
"[{\"url\": \"https://langchain-ai.github.io/langgraph/\", \"content\": \"LangGraph is framework agnostic (each node is a regular python function). It extends the core Runnable API (shared interface for streaming, async, and batch calls) to make it easy to: Seamless state management across multiple turns of conversation or tool usage. The ability to flexibly route between nodes based on dynamic criteria.\"}, {\"url\": \"https://blog.langchain.dev/langgraph-multi-agent-workflows/\", \"content\": \"As a part of the launch, we highlighted two simple runtimes: one that is the equivalent of the AgentExecutor in langchain, and a second that was a version of that aimed at message passing and chat models.\\n It's important to note that these three examples are only a few of the possible examples we could highlight - there are almost assuredly other examples out there and we look forward to seeing what the community comes up with!\\n LangGraph: Multi-Agent Workflows\\nLinks\\nLast week we highlighted LangGraph - a new package (available in both Python and JS) to better enable creation of LLM workflows containing cycles, which are a critical component of most agent runtimes. \\\"\\nAnother key difference between Autogen and LangGraph is that LangGraph is fully integrated into the LangChain ecosystem, meaning you take fully advantage of all the LangChain integrations and LangSmith observability.\\n As part of this launch, we're also excited to highlight a few applications built on top of LangGraph that utilize the concept of multiple agents.\\n\"}]\n",
|
|
"==================================\u001b[1m Ai Message \u001b[0m==================================\n",
|
|
"\n",
|
|
"Based on the search results, here's what I've learned about LangGraph:\n",
|
|
"\n",
|
|
"- LangGraph is a framework-agnostic tool that extends the Runnable API to make it easier to manage state and routing between different nodes or agents in a conversational workflow. \n",
|
|
"\n",
|
|
"- It's part of the LangChain ecosystem, so it integrates with other LangChain tools and observability features.\n",
|
|
"\n",
|
|
"- LangGraph enables the creation of multi-agent workflows, where you can have different \"nodes\" or agents that can communicate and pass information to each other.\n",
|
|
"\n",
|
|
"- This allows for more complex conversational flows and the ability to chain together different capabilities, tools, or models.\n",
|
|
"\n",
|
|
"- The key benefits seem to be around state management, flexible routing between agents, and the ability to create more sophisticated and dynamic conversational workflows.\n",
|
|
"\n",
|
|
"Let me know if you need any clarification or have additional questions! I'm happy to do more research on LangGraph if you need further details.\n"
|
|
]
|
|
}
|
|
],
|
|
"source": [
|
|
"config = {\"configurable\": {\"thread_id\": \"1\"}}\n",
|
|
"events = graph.stream(\n",
|
|
" {\n",
|
|
" \"messages\": [\n",
|
|
" (\"user\", \"I'm learning LangGraph. Could you do some research on it for me?\")\n",
|
|
" ]\n",
|
|
" },\n",
|
|
" config,\n",
|
|
" stream_mode=\"values\",\n",
|
|
")\n",
|
|
"for event in events:\n",
|
|
" if \"messages\" in event:\n",
|
|
" event[\"messages\"][-1].pretty_print()"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 5,
|
|
"id": "acbec099-e5d2-497f-929e-c548d7bcbf77",
|
|
"metadata": {},
|
|
"outputs": [
|
|
{
|
|
"name": "stdout",
|
|
"output_type": "stream",
|
|
"text": [
|
|
"================================\u001b[1m Human Message \u001b[0m=================================\n",
|
|
"\n",
|
|
"Ya that's helpful. Maybe I'll build an autonomous agent with it!\n",
|
|
"==================================\u001b[1m Ai Message \u001b[0m==================================\n",
|
|
"\n",
|
|
"[{'text': \"That's great that you're interested in building an autonomous agent using LangGraph! Here are a few additional thoughts on how you could approach that:\", 'type': 'text'}, {'id': 'toolu_01L3V9FhZG5Qx9jqRGfWGtS2', 'input': {'query': 'building autonomous agents with langgraph'}, 'name': 'tavily_search_results_json', 'type': 'tool_use'}]\n",
|
|
"Tool Calls:\n",
|
|
" tavily_search_results_json (toolu_01L3V9FhZG5Qx9jqRGfWGtS2)\n",
|
|
" Call ID: toolu_01L3V9FhZG5Qx9jqRGfWGtS2\n",
|
|
" Args:\n",
|
|
" query: building autonomous agents with langgraph\n",
|
|
"=================================\u001b[1m Tool Message \u001b[0m=================================\n",
|
|
"Name: tavily_search_results_json\n",
|
|
"\n",
|
|
"[{\"url\": \"https://github.com/langchain-ai/langgraphjs\", \"content\": \"LangGraph is a library for building stateful, multi-actor applications with LLMs, built on top of (and intended to be used with) LangChain.js.It extends the LangChain Expression Language with the ability to coordinate multiple chains (or actors) across multiple steps of computation in a cyclic manner. It is inspired by Pregel and Apache Beam.The current interface exposed is one inspired by ...\"}, {\"url\": \"https://github.com/langchain-ai/langgraph\", \"content\": \"LangGraph is a library for building stateful, multi-actor applications with LLMs. It extends the LangChain Expression Language with the ability to coordinate multiple chains (or actors) across multiple steps of computation in a cyclic manner. It is inspired by Pregel and Apache Beam.The current interface exposed is one inspired by NetworkX.. The main use is for adding cycles to your LLM ...\"}]\n",
|
|
"==================================\u001b[1m Ai Message \u001b[0m==================================\n",
|
|
"\n",
|
|
"The key things to keep in mind:\n",
|
|
"\n",
|
|
"1. LangGraph is designed to help coordinate multiple \"agents\" or \"actors\" that can pass information back and forth. This allows you to build more complex, multi-step workflows.\n",
|
|
"\n",
|
|
"2. You'll likely want to define different nodes or agents that handle specific tasks or capabilities. LangGraph makes it easy to route between these agents based on the state of the conversation.\n",
|
|
"\n",
|
|
"3. Make sure to leverage the LangChain ecosystem - things like prompts, memory, agents, tools etc. LangGraph integrates with these to give you a powerful set of building blocks.\n",
|
|
"\n",
|
|
"4. Pay close attention to state management - LangGraph helps you manage state across multiple interactions, which is crucial for an autonomous agent.\n",
|
|
"\n",
|
|
"5. Consider how you'll handle things like user intent, context, and goal-driven behavior. LangGraph gives you the flexibility to implement these kinds of complex behaviors.\n",
|
|
"\n",
|
|
"Let me know if you have any other specific questions as you start prototyping your autonomous agent! I'm happy to provide more guidance.\n"
|
|
]
|
|
}
|
|
],
|
|
"source": [
|
|
"events = graph.stream(\n",
|
|
" {\n",
|
|
" \"messages\": [\n",
|
|
" (\"user\", \"Ya that's helpful. Maybe I'll build an autonomous agent with it!\")\n",
|
|
" ]\n",
|
|
" },\n",
|
|
" config,\n",
|
|
" stream_mode=\"values\",\n",
|
|
")\n",
|
|
"for event in events:\n",
|
|
" if \"messages\" in event:\n",
|
|
" event[\"messages\"][-1].pretty_print()"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"id": "b2e48c77-65f3-4075-8030-ebf943a281f1",
|
|
"metadata": {},
|
|
"source": [
|
|
"Now that we've had the agent take a couple steps, we can `replay` the full state history to see everything that occurred."
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 6,
|
|
"id": "6c0dbed5-210d-40ad-b002-0bc52ef28fac",
|
|
"metadata": {},
|
|
"outputs": [
|
|
{
|
|
"name": "stdout",
|
|
"output_type": "stream",
|
|
"text": [
|
|
"Num Messages: 8 Next: ()\n",
|
|
"--------------------------------------------------------------------------------\n",
|
|
"Num Messages: 7 Next: ('chatbot',)\n",
|
|
"--------------------------------------------------------------------------------\n",
|
|
"Num Messages: 6 Next: ('action',)\n",
|
|
"--------------------------------------------------------------------------------\n",
|
|
"Num Messages: 5 Next: ('chatbot',)\n",
|
|
"--------------------------------------------------------------------------------\n",
|
|
"Num Messages: 4 Next: ()\n",
|
|
"--------------------------------------------------------------------------------\n",
|
|
"Num Messages: 3 Next: ('chatbot',)\n",
|
|
"--------------------------------------------------------------------------------\n",
|
|
"Num Messages: 2 Next: ('action',)\n",
|
|
"--------------------------------------------------------------------------------\n",
|
|
"Num Messages: 1 Next: ('chatbot',)\n",
|
|
"--------------------------------------------------------------------------------\n"
|
|
]
|
|
}
|
|
],
|
|
"source": [
|
|
"to_replay = None\n",
|
|
"for state in graph.get_state_history(config):\n",
|
|
" print(\"Num Messages: \", len(state.values[\"messages\"]), \"Next: \", state.next)\n",
|
|
" print(\"-\" * 80)\n",
|
|
" if len(state.values[\"messages\"]) == 6:\n",
|
|
" # We are somewhat arbitrarily selecting a specific state based on the number of chat messages in the state.\n",
|
|
" to_replay = state"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"id": "b182019e-bae3-4616-ba1b-f845c0ab6636",
|
|
"metadata": {},
|
|
"source": [
|
|
"**Notice** that checkpoints are saved for every step of the graph. This __spans invocations__ so you can rewind across a full thread's history. We've picked out `to_replay` as a state to resume from. This is the state after the `chatbot` node in the second graph invocation above.\n",
|
|
"\n",
|
|
"Resuming from this point should call the **action** node next."
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 7,
|
|
"id": "de8d5521-8d71-4093-a657-4920c790802f",
|
|
"metadata": {},
|
|
"outputs": [
|
|
{
|
|
"name": "stdout",
|
|
"output_type": "stream",
|
|
"text": [
|
|
"('action',)\n",
|
|
"{'configurable': {'thread_id': '1', 'thread_ts': '2024-05-06T22:33:10.211424+00:00'}}\n"
|
|
]
|
|
}
|
|
],
|
|
"source": [
|
|
"print(to_replay.next)\n",
|
|
"print(to_replay.config)"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"id": "7e8c61f5-3a4a-4cce-b81b-43fe1dcc971f",
|
|
"metadata": {},
|
|
"source": [
|
|
"**Notice** that the checkpoint's config (`to_replay.config`) contains a `thread_ts` **timestamp**. Providing this `thread_ts` value tells LangGraph's checkpointer to **load** the state from that moment in time. Let's try it below:"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 8,
|
|
"id": "85f17be3-eaf6-495e-a846-49436916b4ab",
|
|
"metadata": {},
|
|
"outputs": [
|
|
{
|
|
"name": "stdout",
|
|
"output_type": "stream",
|
|
"text": [
|
|
"=================================\u001b[1m Tool Message \u001b[0m=================================\n",
|
|
"Name: tavily_search_results_json\n",
|
|
"\n",
|
|
"[{\"url\": \"https://valentinaalto.medium.com/getting-started-with-langgraph-66388e023754\", \"content\": \"Sign up\\nSign in\\nSign up\\nSign in\\nMember-only story\\nGetting Started with LangGraph\\nBuilding multi-agents application with graph frameworks\\nValentina Alto\\nFollow\\n--\\nShare\\nOver the last year, LangChain has established itself as one of the most popular AI framework available in the market. This new library, introduced in January\\u2026\\n--\\n--\\nWritten by Valentina Alto\\nData&AI Specialist at @Microsoft | MSc in Data Science | AI, Machine Learning and Running enthusiast\\nHelp\\nStatus\\nAbout\\nCareers\\nBlog\\nPrivacy\\nTerms\\nText to speech\\nTeams Since the concept of multi-agent applications \\u2014 the ones exhibiting different agents, each having a specific personality and tools to access \\u2014 is getting real and mainstream (see the rise of libraries projects like AutoGen), LangChain\\u2019s developers introduced a new library to make it easier to manage these kind of agentic applications. Nevertheless, those chains were lacking the capability of introducing cycles into their runtime, meaning that there is no out-of-the-box framework to enable the LLM to reason over the next best action in a kind of for-loop scenario. The main feature of LangChain \\u2014 as the name suggests \\u2014 is its ability to easily create the so-called chains.\"}, {\"url\": \"https://blog.langchain.dev/langgraph-multi-agent-workflows/\", \"content\": \"As a part of the launch, we highlighted two simple runtimes: one that is the equivalent of the AgentExecutor in langchain, and a second that was a version of that aimed at message passing and chat models.\\n It's important to note that these three examples are only a few of the possible examples we could highlight - there are almost assuredly other examples out there and we look forward to seeing what the community comes up with!\\n LangGraph: Multi-Agent Workflows\\nLinks\\nLast week we highlighted LangGraph - a new package (available in both Python and JS) to better enable creation of LLM workflows containing cycles, which are a critical component of most agent runtimes. \\\"\\nAnother key difference between Autogen and LangGraph is that LangGraph is fully integrated into the LangChain ecosystem, meaning you take fully advantage of all the LangChain integrations and LangSmith observability.\\n As part of this launch, we're also excited to highlight a few applications built on top of LangGraph that utilize the concept of multiple agents.\\n\"}]\n",
|
|
"==================================\u001b[1m Ai Message \u001b[0m==================================\n",
|
|
"\n",
|
|
"The key things I gathered are:\n",
|
|
"\n",
|
|
"- LangGraph is well-suited for building multi-agent applications, where you have different agents with their own capabilities, tools, and personality.\n",
|
|
"\n",
|
|
"- It allows you to create more complex workflows with cycles and feedback loops, which is critical for building autonomous agents that can reason about their next best actions.\n",
|
|
"\n",
|
|
"- The integration with LangChain means you can leverage other useful features like state management, observability, and integrations with various language models and data sources.\n",
|
|
"\n",
|
|
"Some tips for building an autonomous agent with LangGraph:\n",
|
|
"\n",
|
|
"1. Define the different agents/nodes in your workflow and their specific responsibilities/capabilities.\n",
|
|
"2. Set up the connections and routing between the agents so they can pass information and decisions back and forth.\n",
|
|
"3. Implement logic within each agent to assess the current state and determine the optimal next action.\n",
|
|
"4. Use LangChain features like memory and toolkits to give your agents access to relevant information and abilities.\n",
|
|
"5. Monitor the overall system behavior and iteratively improve the agent interactions and decision-making.\n",
|
|
"\n",
|
|
"Let me know if you have any other questions! I'm happy to provide more guidance as you start building your autonomous agent with LangGraph.\n"
|
|
]
|
|
}
|
|
],
|
|
"source": [
|
|
"# The `thread_ts` in the `to_replay.config` corresponds to a state we've persisted to our checkpointer.\n",
|
|
"for event in graph.stream(None, to_replay.config, stream_mode=\"values\"):\n",
|
|
" if \"messages\" in event:\n",
|
|
" event[\"messages\"][-1].pretty_print()"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"id": "c2501fed-2591-420d-98e0-4a3836fb99a8",
|
|
"metadata": {},
|
|
"source": [
|
|
"Notice that the graph resumed execution from the `**action**` node. You can tell this is the case since the first value printed above is the response from our search engine tool.\n",
|
|
"\n",
|
|
"**Congratulations!** You've now used time-travel checkpoint traversal in LangGraph. Being able to rewind and explore alternative paths opens up a world of possibilities for debugging, experimentation, and interactive applications."
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"id": "e584d57f-5aad-4507-815f-0b2e4b64b791",
|
|
"metadata": {},
|
|
"source": [
|
|
"## Conclusion\n",
|
|
"\n",
|
|
"Congrats! You've completed the intro tutorial and built a chat bot in LangGraph that supports tool calling, persistent memory, human-in-the-loop interactivity, and even time-travel!\n",
|
|
"\n",
|
|
"The [LangGraph documentation](https://langchain-ai.github.io/langgraph/) is a great resource for diving deeper into the library's capabilities."
|
|
]
|
|
}
|
|
],
|
|
"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
|
|
}
|