BUILD · 6 MIN READ
Build an explicit agent loop with LangGraph
Put the model call, tool execution, and routing into a state graph.
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.
pip install langgraph langchain langchain-openaiimport 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.