From f1158fcbbb14df17832b4765b2b6e31fa70b3919 Mon Sep 17 00:00:00 2001 From: William FH <13333726+hinthornw@users.noreply.github.com> Date: Thu, 13 Jun 2024 10:13:15 -0700 Subject: [PATCH] [Docs] Update ToolNode docstring (#664) To impart more clarity on what it expects and returns. --- docs/mkdocs.yml | 1 - langgraph/prebuilt/tool_node.py | 21 +++++++++++++++++++-- 2 files changed, 19 insertions(+), 3 deletions(-) diff --git a/docs/mkdocs.yml b/docs/mkdocs.yml index 03b15f54b..613e78ca3 100644 --- a/docs/mkdocs.yml +++ b/docs/mkdocs.yml @@ -2,7 +2,6 @@ site_name: LangGraph site_description: Build language agents as graphs site_url: https://langchain-ai.github.io/langgraph/ repo_url: https://github.com/langchain-ai/langgraph -edit_uri: edit/main/docs/docs/ theme: name: material custom_dir: overrides diff --git a/langgraph/prebuilt/tool_node.py b/langgraph/prebuilt/tool_node.py index b747b5091..ecb051581 100644 --- a/langgraph/prebuilt/tool_node.py +++ b/langgraph/prebuilt/tool_node.py @@ -22,11 +22,28 @@ def str_output(output: Any) -> str: class ToolNode(RunnableCallable): - """ - A node that runs the tools requested in the last AIMessage. It can be used + """A node that runs the tools requested in the last AIMessage. It can be used either in StateGraph with a "messages" key or in MessageGraph. If multiple tool calls are requested, they will be run in parallel. The output will be a list of ToolMessages, one for each tool call. + + The `ToolNode` is roughly analogous to: + + ```python + tools_by_name = {tool.name: tool for tool in tools} + def tool_node(state: dict): + result = [] + for tool_call in state["messages"][-1].tool_calls: + tool = tools_by_name[tool_call["name"]] + observation = tool.invoke(tool_call["args"]) + result.append(ToolMessage(content=observation, tool_call_id=tool_call["id"])) + return {"messages": result} + ``` + + Important: + - The state MUST contain a list of messages. + - The last message MUST be an `AIMessage`. + - The `AIMessage` MUST have `tool_calls` populated. """ def __init__(