Binding tools, ToolNode and tools_condition
Overview
In the previous lesson, you learned how to transform ordinary Python functions into tools using LangChain’s @tool decorator.
However, defining a tool does not automatically give a language model the ability to execute it. An application must communicate the tool’s capabilities to the model, interpret its requests, execute the corresponding Python functions, and return the results.
This lesson connects those responsibilities using three important components:
bind_tools()exposes tool definitions to a language model.ToolNodeexecutes tool calls requested by the model.tools_conditiondetermines whether the graph should execute tools or terminate.
Together with a model-calling node, these components form the foundation of a tool-calling agent.
Consider an inventory assistant that receives the following request:
Find the price of a mechanical keyboard and calculate the cost of buying five units.
The assistant must retrieve information before performing the calculation. It cannot reliably complete the task with a single predetermined sequence of operations because different questions may require different tools.
LangGraph addresses this through a conditional execution loop. The following diagram illustrates its structure.
The model decides what action to request, while the graph determines how that action is executed.
Environment setup
Install LangChain, LangGraph, and the OpenAI integration in a Python 3.11 or newer environment.
python -m pip install -U "langchain[openai]>=1,<2" "langgraph>=1,<2"Configure your OpenAI API key as an environment variable.
export OPENAI_API_KEY="your-api-key"On Windows PowerShell:
$env:OPENAI_API_KEY="your-api-key"The live examples use the course-standard gpt-5.4-mini model. Your API account must have access to it. Examples that construct messages manually do not require an API key.
The API signatures and behavior in this lesson follow the current official documentation. Live model outputs are illustrative; the examples have not been executed against a live API in the lesson-authoring environment.
Binding Tools to a Language Model
What binding actually does
A language model runs remotely from your Python application. It cannot directly inspect your local functions, database connections, or Python interpreter.
When you bind a tool, LangChain prepares a provider-compatible representation of its interface. This representation generally includes:
- The tool’s name.
- A description explaining its purpose.
- An argument schema derived from type annotations or an explicit schema.
- Information about required arguments and supported constraints.
The provider receives these definitions alongside the conversation. The model can then generate structured requests for those tools.
Importantly, the Python implementation remains under your application’s control.
Example: Binding a multiplication tool
The following standalone example defines a calculator, binds it to a model, and inspects the resulting tool request.
from langchain.chat_models import init_chat_model
from langchain.messages import HumanMessage
from langchain.tools import tool
@tool
def multiply(a: int, b: int) -> int:
"""Multiply two integers and return their product."""
return a * b
model = init_chat_model("openai:gpt-5.4-mini")
model_with_tools = model.bind_tools([multiply])
response = model_with_tools.invoke([
HumanMessage(
content="Use the multiplication tool to calculate 17 times 24."
)
])
print("Content:", response.content)
print("Tool calls:", response.tool_calls)Representative output:
Content:
Tool calls: [
{
'name': 'multiply',
'args': {'a': 17, 'b': 24},
'id': 'call_example123',
'type': 'tool_call'
}
]The model has requested an operation but has not executed multiply().
The empty content is normal for a tool-calling response, although some models also include text or other content blocks. Always inspect tool_calls rather than assuming that empty content indicates a failure.
Understanding tool schemas and validation
A schema is a machine-readable description of acceptable inputs. For example, the multiplication tool expects two integer arguments.
You can inspect a tool’s model-facing input schema directly:
import json
from langchain.tools import tool
@tool
def multiply(a: int, b: int) -> int:
"""Multiply two integers."""
return a * b
schema = multiply.tool_call_schema.model_json_schema()
print(json.dumps(schema, indent=2))The output describes an object containing integer properties named a and b, both of which are required.
LangChain uses this schema when preparing the tool definition for the model. At execution time, the tool’s validation machinery checks the supplied arguments.
Schema validation and business validation serve different purposes. An integer quantity of -5 may satisfy the type requirement but still violate an ordering system’s business rules. Such constraints must be enforced through schemas or trusted application code.
Controlling tool selection
The OpenAI integration supports several options when binding tools.
| Configuration | Behavior |
|---|---|
bind_tools(tools) |
Uses the provider’s default tool-selection behavior. |
tool_choice="auto" |
Allows the model to choose tools or answer directly. |
tool_choice="required" |
Requires at least one tool request. |
tool_choice="multiply" |
Requests the specified tool. |
parallel_tool_calls=False |
Prevents multiple tool calls in one model response. |
strict=True |
Enables strict schema adherence for supported tool schemas. |
For example:
from langchain.chat_models import init_chat_model
from langchain.tools import tool
@tool
def multiply(a: int, b: int) -> int:
"""Multiply two integers."""
return a * b
model = init_chat_model("openai:gpt-5.4-mini")
bound_model = model.bind_tools(
[multiply],
tool_choice="multiply",
parallel_tool_calls=False,
)
response = bound_model.invoke("Calculate 8 multiplied by 7.")
print(response.tool_calls)Expect a request for the multiply tool with arguments representing 8 and 7.
These options are provider-dependent. Consult the OpenAI integration’s bind_tools reference when switching models or providers.
Note: Forcing tool selection on every invocation of an agent node can prevent the agent from producing a final answer. Automatic selection is usually appropriate for a general-purpose agent loop.
The Agent Node
The agent node is responsible for invoking the model and recording its response.
It does not execute tools itself. Separating model inference from external execution makes the workflow easier to inspect, test, and control.
Understanding MessagesState
A conversation-based agent needs to retain more than the original user question. It must also retain tool requests, tool results, and subsequent assistant messages.
LangGraph provides MessagesState for this purpose.
Conceptually, its message field uses the add_messages reducer:
from typing import Annotated, TypedDict
from langchain.messages import HumanMessage, AIMessage
from langgraph.graph.message import add_messages
class State(TypedDict):
messages: Annotated[list, add_messages]
history = [HumanMessage(content="Calculate 5 times 6.")]
update = [AIMessage(content="The answer is 30.")]
merged = add_messages(history, update)
for message in merged:
print(message.type, message.content)Expected output:
human Calculate 5 times 6.
ai The answer is 30.The reducer merges message updates into the existing conversation. New message IDs normally append messages, while matching IDs allow existing messages to be updated.
MessagesState provides this behavior without requiring you to define the schema yourself.
Implementing an agent node
The following example constructs an agent node and invokes it independently before adding it to a graph.
from langchain.chat_models import init_chat_model
from langchain.messages import HumanMessage, SystemMessage
from langchain.tools import tool
from langgraph.graph import MessagesState
@tool
def get_temperature(city: str) -> str:
"""Retrieve a city's temperature from the demonstration dataset."""
temperatures = {
"chennai": "32°C",
"london": "12°C",
"tokyo": "18°C",
}
return temperatures.get(
city.lower(),
"Temperature unavailable."
)
model = init_chat_model("openai:gpt-5.4-mini")
model_with_tools = model.bind_tools([get_temperature])
def agent(state: MessagesState):
instructions = SystemMessage(
content=(
"You are a weather demonstration assistant. "
"Use the temperature tool for weather questions. "
"The tool returns sample data, not live observations."
)
)
response = model_with_tools.invoke(
[instructions, *state["messages"]]
)
return {"messages": [response]}
update = agent({
"messages": [
HumanMessage(content="What is the temperature in Chennai?")
]
})
print(update["messages"][0].tool_calls)Expect a request for get_temperature with Chennai as its argument.
The node returns only the new message. LangGraph’s reducer handles merging that update into the conversation when the node runs inside a graph.
The system message is supplied to each model invocation without repeatedly inserting it into the persistent message history.
ToolNode
ToolNode is LangGraph’s prebuilt execution component for application-side tools.
Without it, you would need to maintain a registry of callable tools, validate arguments, handle execution failures, associate results with call IDs, and construct appropriate response messages.
ToolNode handles these responsibilities for you.
from langgraph.prebuilt import ToolNodeHow ToolNode works internally
When invoked with ordinary message state, ToolNode reads the tool calls from the latest assistant message. It resolves each requested name against its registered tools and invokes the corresponding implementation.
The following diagram illustrates the execution process.
For tools that return ordinary values, such as strings, numbers, or dictionaries, the node produces ToolMessage results that can be supplied to the model.
More advanced tools can return Command objects to update graph state or influence control flow. Those capabilities are not required for the basic execution loop.
Example: Executing tool requests without an LLM
You can test ToolNode in isolation by constructing an AIMessage containing tool requests. In current LangGraph releases ToolNode needs the graph runtime, so wrap it in a one-node graph instead of calling tool_node.invoke(...) on its own.
This is especially useful because it eliminates model variability and API costs during unit testing.
from langchain.messages import AIMessage, ToolMessage
from langchain.tools import tool
from langgraph.prebuilt import ToolNode
@tool
def add(a: int, b: int) -> int:
"""Add two integers."""
return a + b
@tool
def multiply(a: int, b: int) -> int:
"""Multiply two integers."""
return a * b
tool_node = ToolNode([add, multiply])
request = AIMessage(
content="",
tool_calls=[
{
"name": "add",
"args": {"a": 10, "b": 20},
"id": "call_add",
"type": "tool_call",
},
{
"name": "multiply",
"args": {"a": 5, "b": 6},
"id": "call_multiply",
"type": "tool_call",
},
],
)
from langgraph.graph import StateGraph, MessagesState, START, END
def run_tool_node(node, request):
"""Run a ToolNode inside a minimal graph and return only the new ToolMessages."""
builder = StateGraph(MessagesState)
builder.add_node("tools", node)
builder.add_edge(START, "tools")
builder.add_edge("tools", END)
state = builder.compile().invoke({"messages": [request]})
return {"messages": state["messages"][1:]}
result = run_tool_node(tool_node, request)
for message in result["messages"]:
assert isinstance(message, ToolMessage)
print(
message.name,
message.tool_call_id,
message.content,
)
assert {
message.tool_call_id: message.content
for message in result["messages"]
} == {
"call_add": "30",
"call_multiply": "30",
}Expected output:
add call_add 30
multiply call_multiply 30The node executes both requests without invoking a language model.
Why tool call IDs matter
Each tool request has an identifier. The corresponding ToolMessage contains that identifier in its tool_call_id field.
| Message | Relevant field | Example |
|---|---|---|
AIMessage |
tool_calls[0]["id"] |
call_add |
ToolMessage |
tool_call_id |
call_add |
ToolMessage |
content |
30 |
ToolMessage |
name |
add |
The identifier establishes which result belongs to which request, particularly when several tools are invoked together.
Dropping assistant tool-call messages, inventing identifiers, or omitting required tool responses can produce an invalid conversation that the model provider rejects.
Parallel tool execution
A model can request several independent operations in one response.
ToolNode supports concurrent execution of those requests, using an executor for synchronous execution and asynchronous concurrency for asynchronous execution.
For example, retrieving inventory for three different products can happen in one tool-execution round.
However, dependent operations should generally occur in separate rounds. A calculation requiring a newly retrieved price cannot reliably execute alongside the price lookup if that price is not yet known.
Tools that modify shared resources also require concurrency safeguards. Parallel execution should not be confused with a database transaction.
See the official ToolNode reference for its supported execution options.
Error Handling
Tools can fail even when the language model selects the correct function.
Common failure categories include:
- Invalid or missing arguments.
- Unknown tool names.
- Business-rule violations.
- Unavailable records.
- Network or service failures.
- Unexpected implementation errors.
A useful agent distinguishes errors that the model can correct from errors that require intervention by the application.
Default error behavior
Current LangGraph 1.x versions distinguish between invalid tool arguments and failures arising during tool execution.
By default, ToolNode converts tool-argument validation failures into error messages that the model can use to correct its request. Ordinary execution exceptions normally propagate.
An unknown tool name is also handled by the node through its tool-name validation path.
The handle_tool_errors parameter allows you to customize exception handling.
| Configuration | Behavior |
|---|---|
| Default | Handles tool invocation validation errors; propagates ordinary execution exceptions. |
True |
Converts ordinary handled exceptions into descriptive error messages. |
False |
Disables exception-to-message handling. |
| Custom string | Returns a fixed error message for caught exceptions. |
| Exception class or tuple | Handles matching exception types. |
| Callable | Formats matching exceptions into custom messages. |
These settings do not override special graph-control exceptions used for mechanisms such as interrupts.
Example: Recovering from invalid division
The following offline example allows an expected business error to become a tool observation rather than terminating execution.
from langchain.messages import AIMessage
from langchain.tools import tool
from langgraph.prebuilt import ToolNode
from langgraph.prebuilt.tool_node import ToolInvocationError
class InvalidDivisionError(ValueError):
pass
@tool
def divide(a: float, b: float) -> float:
"""Divide a by a nonzero value b."""
if b == 0:
raise InvalidDivisionError("Division by zero.")
return a / b
def format_error(
error: InvalidDivisionError | ToolInvocationError,
) -> str:
if isinstance(error, InvalidDivisionError):
return "Cannot divide by zero. Use a nonzero divisor."
return "Invalid arguments. Supply two numeric values."
tool_node = ToolNode(
[divide],
handle_tool_errors=format_error,
)
request = AIMessage(
content="",
tool_calls=[
{
"name": "divide",
"args": {"a": 10, "b": 0},
"id": "call_divide",
"type": "tool_call",
}
],
)
from langgraph.graph import StateGraph, MessagesState, START, END
def run_tool_node(node, request):
"""Run a ToolNode inside a minimal graph and return only the new ToolMessages."""
builder = StateGraph(MessagesState)
builder.add_node("tools", node)
builder.add_edge(START, "tools")
builder.add_edge("tools", END)
state = builder.compile().invoke({"messages": [request]})
return {"messages": state["messages"][1:]}
result = run_tool_node(tool_node, request)
message = result["messages"][0]
print("Status:", message.status)
print("Content:", message.content)Expected output:
Status: error
Content: Cannot divide by zero. Use a nonzero divisor.Because the callable declares specific exception types, unrelated implementation errors can still propagate.
In a complete agent graph, the model receives the error message during its next invocation and can explain the failure or request a corrected operation.
Choosing an error-handling strategy
Returning an error to the model is not equivalent to retrying the operation automatically.
The model decides whether another request is appropriate. Automatic infrastructure retries belong to a separate execution policy, such as a LangGraph node retry policy.
If an exception is converted into a ToolMessage, the node has completed normally from the graph scheduler’s perspective. An exception-triggered node retry will therefore not activate for that handled error.
Tip: Avoid exposing stack traces, credentials, internal database details, or unrestricted exception messages to the model. Return actionable, sanitized errors and preserve diagnostic information in protected application logs.
The later lesson on robust tools will explore infrastructure retries, external service failures, and database integration in greater depth.
tools_condition
After the model responds, the graph needs to determine what should happen next.
The tools_condition function implements the standard routing decision for a tool-calling agent.
from langgraph.prebuilt import tools_conditionFor the normal agent message protocol, its behavior is equivalent to checking whether the latest assistant message contains tool calls.
It returns one of two routing values:
"tools"when tool calls are present."__end__"when no tool calls are present.
The second value corresponds to LangGraph’s END constant.
Example: Testing conditional routing
This standalone example demonstrates both outcomes without a model invocation.
from langchain.messages import AIMessage
from langgraph.graph import END
from langgraph.prebuilt import tools_condition
tool_request = AIMessage(
content="",
tool_calls=[
{
"name": "multiply",
"args": {"a": 5, "b": 4},
"id": "call_123",
"type": "tool_call",
}
],
)
final_response = AIMessage(
content="The result is 20."
)
route_one = tools_condition({
"messages": [tool_request]
})
route_two = tools_condition({
"messages": [final_response]
})
print(route_one)
print(route_two)
assert route_one == "tools"
assert route_two == ENDExpected output:
tools
__end__The function only determines the destination. It does not execute tools or invoke the model.
Mapping routes to graph nodes
Use add_conditional_edges() to register the routing function:
builder.add_conditional_edges(
"agent",
tools_condition,
{
"tools": "tools",
END: END,
},
)The mapping associates the router’s return values with actual graph destinations.
If your execution node is named "execute_tools" instead, map "tools" to "execute_tools".
An explicit mapping also makes the graph’s possible transitions clear.
See the tools_condition API reference for additional supported state formats and custom message keys.
Putting It Together
We will now build a complete product research and calculation assistant. It uses a local catalog so you can concentrate on orchestration without configuring external APIs or databases.
The agent has three capabilities:
- Search the catalog for products.
- Retrieve an exact unit price using a product identifier.
- Calculate an order total using retrieved information.
All monetary values are represented as integer INR amounts.
Complete working agent graph
Save the following example as catalog_agent.py.
from langchain.chat_models import init_chat_model
from langchain.messages import HumanMessage, SystemMessage
from langchain.tools import tool
from langgraph.graph import StateGraph, MessagesState, START, END
from langgraph.prebuilt import ToolNode, tools_condition
from langgraph.errors import GraphRecursionError
CATALOG = {
"KB101": {
"name": "Mechanical Keyboard",
"price": 2500,
},
"MS202": {
"name": "Wireless Mouse",
"price": 1200,
},
"MN303": {
"name": "27-inch Monitor",
"price": 18000,
},
}
@tool
def search_catalog(query: str) -> list[dict]:
"""Search product names and return matching product IDs and names."""
query = query.strip().lower()
if not query:
raise ValueError("Search query cannot be empty.")
return [
{
"product_id": product_id,
"name": product["name"],
}
for product_id, product in CATALOG.items()
if query in product["name"].lower()
]
@tool
def get_price(product_id: str) -> int:
"""Retrieve the unit price in INR for an exact product ID."""
product_id = product_id.strip().upper()
if product_id not in CATALOG:
raise ValueError("Unknown product ID.")
return CATALOG[product_id]["price"]
@tool
def calculate_total(unit_price: int, quantity: int) -> int:
"""Multiply a unit price in INR by a positive order quantity."""
if unit_price < 0 or quantity <= 0:
raise ValueError("Invalid price or quantity.")
return unit_price * quantity
tools = [
search_catalog,
get_price,
calculate_total,
]
model = init_chat_model("openai:gpt-5.4-mini")
model_with_tools = model.bind_tools(tools)
def agent(state: MessagesState):
system_message = SystemMessage(
content=(
"You are a product research and quotation assistant. "
"Search the catalog when only a product name is given. "
"Retrieve exact prices using get_price. "
"Use calculate_total for order calculations. "
"Never invent product IDs or prices. "
"Report missing products clearly. "
"Do not repeatedly request a tool with unchanged "
"arguments after receiving an error. "
"Express monetary values in INR."
)
)
response = model_with_tools.invoke(
[system_message, *state["messages"]]
)
return {"messages": [response]}
builder = StateGraph(MessagesState)
builder.add_node("agent", agent)
builder.add_node(
"tools",
ToolNode(
tools,
handle_tool_errors="Invalid request. Check the product or arguments.",
),
)
builder.add_edge(START, "agent")
builder.add_conditional_edges(
"agent",
tools_condition,
{
"tools": "tools",
END: END,
},
)
builder.add_edge("tools", "agent")
graph = builder.compile()
if __name__ == "__main__":
question = (
"Find the mechanical keyboard and calculate "
"the total cost of 5 units."
)
try:
result = graph.invoke(
{
"messages": [
HumanMessage(content=question)
]
},
config={"recursion_limit": 15},
)
for message in result["messages"]:
message.pretty_print()
print("\nFinal answer:")
print(result["messages"][-1].text)
except GraphRecursionError:
print("The agent exceeded its execution budget.")Run the application:
python catalog_agent.pyA representative final answer is:
The Mechanical Keyboard (KB101) costs INR 2,500 per unit.
Quantity: 5
Total cost: INR 12,500.Exact wording, tool call IDs, and model-generated execution details may vary.
Understanding the graph construction
The graph begins with MessagesState, giving both nodes access to the accumulated conversation.
The agent node receives that conversation and requests a model response. The tools node executes any requested operations.
The conditional edge makes tool execution optional. The ordinary edge from "tools" back to "agent" makes repeated execution possible.
Notice that there is no unconditional edge from "agent" to "tools". Such an edge would schedule tool execution even when the model has produced a final answer.
The same tool collection is used for both binding and execution. This prevents accidental discrepancies between capabilities advertised to the model and capabilities available in the application.
Tool Execution Cycles
A tool execution cycle consists of a model decision, external execution, and observation of the result.
The product quotation example requires several dependent cycles.
| Step | Component | Operation | Result |
|---|---|---|---|
| 1 | Agent | Requests catalog search | Search for keyboard |
| 2 | ToolNode | Executes search | Product KB101 |
| 3 | Agent | Requests unit price | Lookup KB101 |
| 4 | ToolNode | Retrieves price | 2500 |
| 5 | Agent | Requests calculation | 2500 × 5 |
| 6 | ToolNode | Executes calculation | 12500 |
| 7 | Agent | Produces final answer | INR 12,500 |
| 8 | Router | Finds no tool calls | END |
At every cycle, message history preserves the evidence collected during earlier operations.
In LangGraph’s execution model, nodes run in discrete execution steps. Their state updates become available to subsequent scheduled nodes. The reducer preserves the conversation as execution moves between the agent and tools.
This creates adaptive behavior without requiring a Python while loop around the graph.
Observing execution with streaming
Inspecting only the final response hides the intermediate operations. Streaming exposes node-level updates as the graph executes.
Save the following script alongside catalog_agent.py.
from langchain.messages import HumanMessage, AIMessage, ToolMessage
from catalog_agent import graph
inputs = {
"messages": [
HumanMessage(
content="Find the wireless mouse and price 3 units."
)
]
}
for chunk in graph.stream(
inputs,
config={"recursion_limit": 15},
stream_mode=["updates"],
version="v2",
):
if chunk["type"] != "updates":
continue
for node_name, update in chunk["data"].items():
print(f"\nNode: {node_name}")
for message in update.get("messages", []):
if isinstance(message, AIMessage):
if message.tool_calls:
for call in message.tool_calls:
print("Requested:", call["name"])
print("Arguments:", call["args"])
else:
print("Final answer:", message.text)
elif isinstance(message, ToolMessage):
print("Executed:", message.name)
print("Result:", message.content)Representative output:
Node: agent
Requested: search_catalog
Arguments: {'query': 'wireless mouse'}
Node: tools
Executed: search_catalog
Result: [{"product_id":"MS202","name":"Wireless Mouse"}]
Node: agent
Requested: get_price
Arguments: {'product_id': 'MS202'}
Node: tools
Executed: get_price
Result: 1200
Node: agent
Requested: calculate_total
Arguments: {'unit_price': 1200, 'quantity': 3}
Node: tools
Executed: calculate_total
Result: 3600
Node: agent
Final answer: Three wireless mice cost INR 3,600.The v2 streaming interface provides structured chunks containing their event type and data. Other stream modes expose model-generated message chunks and custom application events.
Refer to the LangGraph streaming documentation when extending this example.
Preventing uncontrolled execution
An agent may repeatedly call a failing tool, alternate between unnecessary operations, or fail to recognize that its task is complete.
Set an explicit recursion limit:
config = {"recursion_limit": 15}The recursion limit bounds graph super-steps, not individual tool requests. Multiple tools can execute within a single tools-node step.
When the budget is exhausted, LangGraph raises GraphRecursionError. This is a safeguard rather than a successful termination condition.
Production systems should additionally enforce wall-clock deadlines, tool-specific execution limits, and cost budgets.
Common Mistakes
Several implementation errors recur when developers first build tool-calling graphs.
| Mistake | Consequence | Correct approach |
|---|---|---|
| Binding tools without an executor | Requests remain unexecuted. | Register a ToolNode. |
| Invoking the original unbound model | Tool definitions are unavailable. | Invoke the bound model. |
| Omitting the return edge | Results never reach the model again. | Connect tools back to the agent. |
| Using unconditional tool routing | Execution occurs unnecessarily. | Use tools_condition. |
| Replacing message history | The model loses earlier observations. | Use MessagesState. |
| Returning the entire history unnecessarily | Updates become harder to reason about. | Return new messages only. |
| Forcing tools every turn | The agent may never terminate normally. | Allow automatic tool selection. |
| Catching every exception indiscriminately | Implementation failures become hidden. | Handle expected failures selectively. |
Another subtle mistake is assuming that a tool’s return_direct setting automatically overrides custom graph edges. In a manually constructed graph, you must explicitly implement any required early-termination behavior.
Production Engineering Considerations
Treat the model as an untrusted requester
A syntactically valid tool request is not proof that the action is authorized.
Enforce access permissions, business constraints, and resource ownership within trusted application code. Tools requiring user-specific information should receive it through injected runtime context, such as ToolRuntime, rather than trusting identity arguments generated by the model.
The official LangChain tools documentation describes runtime context and state injection.
Tool results are also potentially untrusted. Retrieved documents and external service responses can contain misleading instructions. Treat them as data, not as application policy.
Design for reliable execution
Prefer narrow tools with clear responsibilities. A tool called get_product_price is easier to validate and authorize than a general-purpose database execution tool.
For operations with side effects, use idempotency safeguards and appropriate approval mechanisms. Repeated execution must not accidentally create duplicate orders, payments, or records.
Test execution separately from model intelligence
Write deterministic tests for tool implementations, schema validation, error conversion, and conditional routing.
Then perform end-to-end model evaluations covering successful operations, missing data, direct answers, multiple independent calls, and dependent calls.
Use LangSmith tracing when investigating unexpected routing decisions, repeated calls, latency, or excessive model usage.
Choose the appropriate abstraction
LangGraph’s low-level graph construction offers explicit control over execution topology and state transitions.
For conventional agents that do not need custom graph orchestration, LangChain 1.x also provides the higher-level create_agent API through langchain.agents.
Understanding the lower-level components remains valuable because production applications frequently require specialized routing, authorization, recovery, and human approval behavior.
Connection to the Next Lesson
You have now connected tool definitions, model-generated requests, executable operations, and conditional graph transitions.
In the next lesson, Building a ReAct agent from scratch, you will use these components to develop a more deliberate reasoning-and-action architecture. Rather than treating tool calling as an isolated feature, you will examine how repeated decisions and observations enable an agent to solve multi-step problems.
The chapter’s hands-on project will extend this foundation into an integrated assistant with search, calculator, and database tools. The local catalog used here provides a controlled starting point before introducing external dependencies and production-grade execution requirements.
Build a Product Quotation Agent
Build a LangGraph agent that retrieves product prices and calculates order totals using two custom tools. Bind both tools to the language model, execute requested tools through ToolNode, and use tools_condition to control the execution loop. Configure appropriate error handling and a recursion limit, then test the agent with a valid product, an unknown product, and a question that requires no tools.
from langchain.chat_models import init_chat_model
from langchain.messages import HumanMessage, SystemMessage
from langchain.tools import tool
from langgraph.graph import StateGraph, MessagesState, START, END
from langgraph.prebuilt import ToolNode, tools_condition
PRODUCTS = {
"KB101": 2500,
"MS202": 1200,
"MN303": 18000,
}
@tool
def get_price(product_id: str) -> int:
"""Return the unit price in INR for a product ID."""
# TODO: Retrieve the price or raise ValueError.
raise NotImplementedError
@tool
def calculate_total(unit_price: int, quantity: int) -> int:
"""Calculate the total price in INR for a quantity."""
# TODO: Validate the inputs and calculate the total.
raise NotImplementedError
tools = [get_price, calculate_total]
model = init_chat_model("openai:gpt-5.4-mini")
# TODO: Bind tools to the model.
def agent(state: MessagesState):
# TODO: Invoke the bound model and return a message update.
raise NotImplementedError
builder = StateGraph(MessagesState)
# TODO: Register the agent node and ToolNode.
# TODO: Connect START to the agent.
# TODO: Configure conditional routing with tools_condition.
# TODO: Connect the tools node back to the agent.
# TODO: Compile the graph.
# TODO: Invoke the graph with a recursion limit.
# Test: What is the total price of 4 units of KB101?
# Expected total: INR 10,000.from langchain.chat_models import init_chat_model
from langchain.messages import HumanMessage, SystemMessage
from langchain.tools import tool
from langgraph.graph import StateGraph, MessagesState, START, END
from langgraph.prebuilt import ToolNode, tools_condition
from langgraph.errors import GraphRecursionError
PRODUCTS = {
"KB101": 2500,
"MS202": 1200,
"MN303": 18000,
}
@tool
def get_price(product_id: str) -> int:
"""Return the unit price in INR for a product ID."""
product_id = product_id.strip().upper()
if product_id not in PRODUCTS:
raise ValueError("Unknown product ID.")
return PRODUCTS[product_id]
@tool
def calculate_total(unit_price: int, quantity: int) -> int:
"""Calculate the total price in INR for a positive quantity."""
if unit_price < 0 or quantity <= 0:
raise ValueError("Invalid unit price or quantity.")
return unit_price * quantity
tools = [get_price, calculate_total]
model = init_chat_model("openai:gpt-5.4-mini")
model_with_tools = model.bind_tools(tools)
def agent(state: MessagesState):
instructions = SystemMessage(
content=(
"You are a product quotation assistant. "
"Retrieve actual product prices using get_price. "
"Use calculate_total for order totals. "
"Never invent missing prices. "
"If a product ID is unknown, inform the user "
"instead of repeatedly requesting the same product. "
"Answer general questions directly."
)
)
response = model_with_tools.invoke(
[instructions, *state["messages"]]
)
return {"messages": [response]}
builder = StateGraph(MessagesState)
builder.add_node("agent", agent)
builder.add_node(
"tools",
ToolNode(
tools,
handle_tool_errors="Invalid tool input or unavailable product."
),
)
builder.add_edge(START, "agent")
builder.add_conditional_edges(
"agent",
tools_condition,
{"tools": "tools", END: END},
)
builder.add_edge("tools", "agent")
graph = builder.compile()
questions = [
"What is the total price of 4 units of KB101?",
"What is the price of product UNKNOWN?",
"What can you help me with?",
]
for question in questions:
print("\nQuestion:", question)
try:
result = graph.invoke(
{"messages": [HumanMessage(content=question)]},
config={"recursion_limit": 12},
)
for message in result["messages"]:
message.pretty_print()
print("Final answer:", result["messages"][-1].text)
except GraphRecursionError:
print("The agent exceeded its execution budget.")Summary
- Binding tools exposes their names, descriptions, and argument schemas to the language model without executing their Python implementations.
- An agent node invokes the bound model and returns its AIMessage as an update to the graph state.
- ToolNode dispatches requested tools, validates arguments, executes independent calls concurrently, and produces corresponding ToolMessage objects.
- Each ToolMessage must correlate with its original tool request through the tool_call_id field.
- The tools_condition function routes execution to the tools node when tool calls exist and to END otherwise.
- Connecting the tools node back to the agent creates a repeating model-execution-observation cycle.
- Production agent loops require appropriate validation, error handling, execution budgets, authorization, and observability.