New Tool Radar

AI Agents & Automation

How to Build a First LangGraph State Graph That Loops Between Model and Tools

Build a LangGraph StateGraph with model and tool nodes and a conditional edge so the agent loops until it can answer.

Schematic diagram with three steps: Define the state, Add model and tool nodes, then Add the loop edge.

LangGraph models an application as a state machine: nodes are functions such as model calls and tools, and edges define which node comes next. Unlike a classic pipeline, cycles are allowed, and an agent is a cycle: model, tool, model, until the model can answer.

Before you start

You need Python with LangGraph installed and an API key for one chat model. Decide the state first: one list of messages is enough for a first graph, because everything flowing through the graph lives in that single inspectable object.

Define the state and add the model and tool nodes

Define a state schema with a messages list, using an annotation that appends new messages. Add a model node that calls the chat model and a tool node that runs the tools the model requested. Nodes do not mutate the state: they receive it and return a dictionary with the keys to update, and LangGraph merges the updates.

Add the conditional edge that makes the loop

Add a conditional edge from the model node: if the model reply requests a tool, route to the tool node, and after the tool node return to the model. If the reply has no tool call, route to the end. Run one question and read the state after each step to confirm the loop runs.

Worked example: One loop for a fictional support agent

Northwind Support is a fictional help desk. Its LangGraph agent checks an order with one tool. The table shows the loop for one question.

Step Node What happens
1 Model Reads the question about order 1042
2 Tool Looks up order 1042
3 Model Reads the tool result
4 End Replies with the delivery status

Expected result (UNTESTED): the question produces one tool call and a reply quoting the tool result, and the state shows the messages in order. We checked the LangGraph documentation summary, which describes state graphs, nodes, conditional edges and cycles, but we did not run the graph on this machine.

Limits

A graph without a loop limit can cycle forever if the model keeps calling tools, so add a limit before you trust it. Keep the state lean: everything in state is saved on every node transition when a checkpointer is attached.

Sources

See all