05. Tool-Calling Agent in LangGraph

Chapter 5 of 18 · 15 min

A tool-calling agent in LangGraph is a node that uses a model with bound tools and loops until the model emits a ToolCall-structured message or a plain text response. LangGraph provides a create_react_agent factory that builds this pattern automatically, but building it by hand clarifies what is happening.

The manual pattern: a llm_with_tools bound model, a routing function that checks if the last message is a ToolMessage, and a while loop inside the node that re-invokes the model when tools are returned. With create_react_agent, this is done for you:

from langgraph.prebuilt import create_react_agent
from langchain_ollama import OllamaLLM

llm = OllamaLLM(model="llama3.2:latest", temperature=0)

tools = [search_web, read_file]

agent_app = create_react_agent(model=llm, tools=tools)

result = agent_app.invoke({
    "messages": [{"role": "user", "content": "Find the Python version in requirements.txt"}]
})

The returned result["messages"] contains the full turn-by-turn exchange including tool calls and tool responses. create_react_agent uses a specific state schema internally (MessagesState) with a tools field. If you need custom fields alongside the built-in message history, use create_react_agent with a custom state class that inherits from MessagesState:

from langgraph.graph import MessagesState

class AgentState(MessagesState):
    task_id: str
    metadata: dict

The failure mode: tools that raise exceptions return a ToolMessage with status="error". The model sees this as a tool result and may retry, loop infinitely, or give up depending on prompt engineering. Always wrap tool implementations in try/except and return informative error strings rather than propagating exceptions.

Local verification checkpoint

Run the smallest example from this chapter in a local workspace and record the package version, runtime, data path, and observed output. If the result depends on model size, vector count, CPU/GPU backend, or available memory, note that constraint beside the exercise so the lesson remains reproducible.

EXERCISE

Create a ReAct agent with a custom AdditionTool that adds two integers. Call it with input "What is 23 + 17?" and inspect the message history to see the tool call and the model's final answer.