BUILD · 5 MIN READ
Build an explicit agent loop with LangGraph
Put the model call, tool execution, and routing into a state graph.
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.
Resolve the real user and pass a bounded task to the SDK.
The runtime manages the loop or explicit state transitions; it does not replace resource authorization.
invokeTo 03 · Configured modelvalidatedTo 04 · Allowed toolscompleteTo 06 · Verified answerKeep provider credentials on the server and select a model supported by the API account.
decisionBack to 02 · LangGraphThe example exposes a local fixture. A real tool must check the authenticated user and resource.
observationBack to 02 · LangGraphTrack the current conversation and stop when the turn or recursion budget is reached.
Result or stopping pointFor A104, confirm that the answer reflects the lookup observation and contains no invented dates.
Result or stopping point
The runtime manages the loop or explicit state transitions; it does not replace resource authorization.
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, andlangchain-openai. - Set
OPENAI_API_KEYandOPENAI_MODEL. - Save the file as
graph_agent.pyand run it with Python.
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"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
MessagesStatecarries 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
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.