BUILD · 5 MIN READ

Build an explicit agent loop with LangGraph

Put the model call, tool execution, and routing into a state graph.

Download example files Code + setup + checks in a ZIP
Jump to a section 9 sections

EXAMPLE USE CASE

Make a support agent’s tool loop explicit

You need to own the transition from model decision to tool execution and back to the model.

Input
MessagesState, an order question, a bound lookup tool and a recursion limit.
Expected output
A think → tools → think execution path ending in a grounded final answer.
  • Success check: The tool observation appears in state before the last answer; execution stays within eight graph steps.
  • Try a failure: A repeated tool request must hit a bounded stop, not run indefinitely.

Example scope: A real LangGraph invocation with process-local state. Persistent resume requires a checkpointer; it is not implemented by compile() alone.

LangGraph examplePostgreSQL example
SEE HOW THE SYSTEM FITS TOGETHERSELECT A COMPONENT
taskinvokedecisionvalidatedobservationstatecompleteApplication requestIdentity + goalLangGraphAgent or graph runtimeConfigured modelAvailable provider modelAllowed toolsTyped application functionsState + limitsMessages and stopping rulesVerified answerCompare with the result
  1. Resolve the real user and pass a bounded task to the SDK.

  2. The runtime manages the loop or explicit state transitions; it does not replace resource authorization.

  3. Keep provider credentials on the server and select a model supported by the API account.

  4. The example exposes a local fixture. A real tool must check the authenticated user and resource.

  5. Track the current conversation and stop when the turn or recursion budget is reached.

    Result or stopping point
  6. For A104, confirm that the answer reflects the lookup observation and contains no invented dates.

    Result or stopping point
LangGraph

The runtime manages the loop or explicit state transitions; it does not replace resource authorization.

Follow the arrows, then select a component to inspect its responsibility. On mobile, downward arrows connect the next step; bent arrows identify branches and return paths. Select a destination to jump to that component.

Where it fits

  • LangGraph makes execution state and transitions explicit.
  • A model node chooses an answer or tool call.
  • A tool node executes the selected operation.
  • A conditional edge routes the next step.

Prepare the example

  • Install langgraph, langchain, and langchain-openai.
  • Set OPENAI_API_KEY and OPENAI_MODEL.
  • Save the file as graph_agent.py and run it with Python.
Shell · install in a virtual environment
python3 -m venv .venv
source .venv/bin/activate
python -m pip install langgraph langchain langchain-openai
export OPENAI_API_KEY="your-api-key"
export OPENAI_MODEL="your-enabled-model-id"
Python · graph_agent.py
import os
from langchain.chat_models import init_chat_model
from langchain.tools import tool
from langgraph.graph import StateGraph, MessagesState, START
from langgraph.prebuilt import ToolNode, tools_condition

@tool
def lookup_order(order_id: str) -> str:
    """Read an order status from a local demonstration fixture."""
    orders = {"A104": "Packed; awaiting courier pickup"}
    return orders.get(order_id, "Order not found")

tools = [lookup_order]
model = init_chat_model(
    os.environ["OPENAI_MODEL"], model_provider="openai"
).bind_tools(tools)

def think(state: MessagesState):
    response = model.invoke(state["messages"])
    return {"messages": [response]}

builder = StateGraph(MessagesState)
builder.add_node("think", think)
builder.add_node("tools", ToolNode(tools))
builder.add_edge(START, "think")
builder.add_conditional_edges("think", tools_condition)
builder.add_edge("tools", "think")
agent = builder.compile()

result = agent.invoke(
    {"messages": [("user", "Use lookup_order for A104.")]},
    {"recursion_limit": 8},
)
print(result["messages"][-1].content)

Educational example. Uses your configured environment and credentials; no paid model call is made by this website.

Understand the state

  • MessagesState carries the conversation and tool observations between nodes.
  • The graph loops back to the model after a tool runs.
  • The recursion limit provides a bound on graph execution.

Add persistence separately

  • This minimal graph uses process-local state for one invocation.
  • To resume across process restarts, add a persistent checkpointer and a stable thread identifier.
  • Repeated side effects still need idempotency at the tool boundary.

Run and verify

Shell
python graph_agent.py
  • The messages end with an answer grounded in the tool result.
  • The graph moves from think to tools and back, then stops when no tool is requested.

Troubleshooting and failure tests

  • A missing ToolMessage or mismatched call identifier breaks the tool-result contract.
  • A recursion-limit failure is evidence of an unfinished loop; inspect repeated tool calls before raising the limit.

Before production

  • Replace the local fixture with a service that enforces authenticated tenant and resource permissions.
  • Add timeouts, bounded retries, tracing redaction, and a regression case for each observed failure.
  • Model calls consume provider API usage when you run this example; this website only displays the code.

Keep exploring

An agent that can pause and resumeA layered architecture for agent memory