← All news

News / Learn / AI agents

How does the agent loop work?

You'll be able to explain how an agent loop works and write a minimal one that calls tools until a task is done.

An agent loop is a cycle. The model looks at the task and what has happened so far, then either answers or asks for a tool to run. Your code runs that tool, adds the result to the conversation, and sends everything back to the model. The loop repeats until the model gives a final answer or a limit stops it.

Most useful AI products that act, rather than just answer, rely on this cycle. Once you understand it, you can predict cost, latency and failure modes. You also see where your code must enforce limits, because the model cannot stop itself reliably.

Each pass through the loop starts with a request. Your code sends the system prompt, the conversation so far, and the list of tools the model may call. The model returns either text or a tool call. A tool call names a function and gives arguments, usually as structured output.

Your code does the work. It checks that the tool name exists and the arguments match the expected shape. It runs the function and gets a result, such as a search hit, a file read or an error message. It then appends the tool call and its result to the message history. Nothing runs inside the model itself.

The loop ends when the model returns plain text with no tool call. That text is the answer. Your code should also stop the loop after a set number of steps or a set amount of spend, because a model can keep requesting tools without making progress.

Every pass resends the growing history, so the context window fills up. Long loops cost more and get slower. Keep tool results short and trim old turns when you can.

A minimal loop with a step cap. The call_model and run_tool functions stand in for your provider's SDK and your own tools.

def run_agent(task, tools, max_steps=8):
    messages = [{"role": "user", "content": task}]
    for step in range(max_steps):
        reply = call_model(messages, tools)
        messages.append(reply)
        if not reply.get("tool_calls"):
            return reply["content"]
        for call in reply["tool_calls"]:
            try:
                result = run_tool(call["name"], call["arguments"], tools)
            except Exception as err:
                result = f"Error: {err}"
            messages.append({
                "role": "tool",
                "tool_call_id": call["id"],
                "content": str(result)[:4000],
            })
    raise RuntimeError("Agent stopped: step limit reached")

A short sketch to show the idea. Check the official docs of the tool you use.

  • No step limit Cap the number of loop iterations and raise or return a clear error when the cap is hit. Models can repeat the same tool call indefinitely.
  • Trusting tool arguments blindly Validate tool names and arguments against a schema before running anything. The model may produce malformed or unexpected input.
  • Returning huge tool outputs Truncate or summarize tool results before adding them to history. Large outputs fill the context window and raise cost.
  • Letting tool errors crash the loop Send errors back to the model as tool results. It can often recover, retry differently, or explain the failure to the user.

Study tool calling and structured output next, since the loop depends on both. Then read about guardrails and evals to learn how to test an agent's behavior across many runs.

Is the agent loop the same as the agent?

No. The loop is the control flow. The agent is the whole system: the model, the prompt, the tools, the memory and the loop that ties them together.

Does the model run the tools itself?

No. The model only requests a tool call with arguments. Your code runs the function and returns the result to the model.

How do I know when the loop should end?

The loop ends when the model returns a response with no tool call. Your code should also enforce a hard step limit as a safety stop.

Why does each step cost more than the last?

Each request resends the full message history, so the input grows with every tool call and result. Trimming history keeps cost and latency down.

Written with AI by CapyLaunch. Spotted a mistake? Email hello@capylaunch.com.