1:1 mentoring with Big Tech AI engineers
LLM & Agentic

Tools & Routing

Define LangGraph tools with @tool, wire ToolNode and tools_condition into an agent loop, use the prebuilt create_agent, and write custom routers that branch on your own state.

Last updated

After this section you can

  • Define a tool whose docstring and type hints drive model selection
  • Wire ToolNode and tools_condition into a working agent loop
  • Choose between the prebuilt create_agent and a hand-built graph
  • Write a custom router that branches on your own state, not just tool calls
  • Handle a failing tool instead of assuming ToolNode already did
02

Tools & Routing

A tool is a typed Python function with a docstring. Wiring it into a graph takes one prebuilt node and one conditional edge — and those two lines are the entire agent loop.

THE CENTRAL IDEA

The model never runs your tool. It emits a tool_call; ToolNode executes it and appends the result; tools_condition decides whether to go round again. Everything you would hand-write in a while-loop is those two edges.

A tool is a function the model can read

The docstring is not a comment — it is the tool description the model selects on, and the type hints become the JSON schema.

from langchain_core.tools import tool

@tool
def get_order_status(order_id: str) -> str:
    """Look up the current delivery status of a customer order by its ID.

    Use for questions about where an order is or when it arrives.
    Not for refunds or cancellations.
    """
    return f"Order {order_id}: shipped, arriving Tuesday."

# what the model actually sees:
get_order_status.args_schema.model_json_schema()
Two edges make the loop: one conditional out of the agent, one unconditional back into it
START agent llm.bind_tools(…) tools_condition last message → which edge? ToolNode runs every call END has tool_calls no tool_calls — the model answered in text tool results append to state, the agent runs again The loop is not a for statement anywhere — it is the cycle these two edges form. The run ends when the model stops asking for tools. ToolNode turns a bad argument into a ToolMessage the model can retry. An exception raised inside your tool is re-raised by default and kills the run. Always cap the cycle: {"recursion_limit": 25}. The default is 10007, which is not a bound anyone meant to rely on.

Related

More in LLM & Agentic

Get full access to all 74+ sections with code examples, diagrams, and interactive animations.

Unlock Premium