An agent loop with tools: plans, calls and limits

60 min7 partsCoreFast-moving topicChecked Nov 2026
Start the lessonShort steps, each with something to do
What you'll learn
  • Write the loop that runs a tool-using model, and say what the model does and what your code does
  • Define a tool with a name, a description and a schema, and check every call's arguments before it runs
  • Return failed calls to the model as results, and stop a run on steps, repeats and budget
  • Put a person in front of consequential actions, and make them safe to retry with an idempotency key
  • Grade an agent by the state it leaves behind, over many runs
Part 1 of 7about 12 min
The loop

Agent harness

Anthropic ML engineer candidates report a tooling scenario in which the model plans and then calls a tool (1 report). In an OpenAI round billed as system design, the questions turned to an agent harness and its evals (1 report). It starts like this:

An agent is a model that calls tools in a loop. The model only writes text. Your code runs the tools.

Write run_agent(model, tools, task, max_steps=10). The transcript starts with the user's task. Each step calls model(transcript), which returns {"answer": text} or {"tool": name, "args": {...}}. For a tool call, run tools[name](**args), and add the call and its result to the transcript. Stop on an answer, or after max_steps model calls. Return a dict with the answer, why it stopped ("answer" or "max_steps"), and the transcript.

For the task "Can I return order A17?":

  1. The model asks for look_up_order with the args {"order_id": "A17"}. The loop runs it, and adds the call and its result, "A17: 2-person tent, delivered Nov 10, $189.00, unused".
  2. The model returns {"answer": "A17 can be returned."}. The loop adds the answer and stops.

So run_agent returns the answer "A17 can be returned.", stopped set to "answer", and a transcript of 4 messages. With max_steps=1, the model never gets its second turn: the answer is None, stopped is "max_steps", and the transcript holds 3 messages.

Then the levels come. Errors go back to the model as results, not crashes: a tool that doesn't exist, a tool that raises, arguments that don't fit the tool's schema. Then a person approves risky calls, and a run that makes the same call three times in a row stops as a loop. The follow-ups ask about budgets, a refund that must never run twice, and how you grade an agent.

You don't write it yet. This lesson builds each piece first on one example, a shop's returns agent: the loop, tool definitions, errors and limits, a person for risky calls, and grading. At the end you solve the whole problem, level by level, in an interview simulation with a 45-minute timer.

This is the newest kind of coding round: a loop around a model. Hold on to one idea from the start. The loop is plain code that owns every decision, and the model only suggests the next call.

An agent is a model calling tools in a loop, and the loop is your code

An outdoor shop wants its assistant to handle returns end to end: find the order, check the return window, and pay the refund, without a person in between for the easy cases. That takes an agent. Anthropic's engineering post on agents describes them as typically just LLMs using tools based on environmental feedback in a loop.

Anthropic's Applied AI Engineer posting asks for production experience with agent architectures (1 source).

Predict

The shop's refund tool is a function in the shop's own code. The model decides a refund is due. What runs the function?

Pick an answer above to see the rest

The model asks for a tool, your code runs it, and the result goes back

Anthropic's tool use docs put the whole idea in one line: every tool call is a round trip, where the model asks, you execute, you report back, and the model continues. The API says the model wants a tool by returning a stop reason of tool_use with one or more tool_use blocks. Your code runs the tool and sends a new request with all the earlier messages plus the results.

The model in the code below is a stand-in, a short script that plays the LLM's part, so the run is the same every time. The loop around it is the real thing.

def look_up_order(order_id: str) -> str:
    """The shop's order record, as text."""
    return {"A17": "A17: 2-person tent, delivered Nov 10, $189.00, unused"}.get(order_id, "no such order")


def return_window(item: str) -> str:
    """The return policy for one kind of item."""
    return "unused gear: 30 days from delivery"


# what the payment system did
refunds = []


def issue_refund(order_id: str, amount: float) -> str:
    """Pays the money back. This one has consequences."""
    refunds.append((order_id, amount))
    return f"refunded ${amount:.2f} on {order_id}"


TOOLS = {"look_up_order": look_up_order, "return_window": return_window, "issue_refund": issue_refund}


def scripted_model(transcript: list[dict]) -> dict:
    """Stands in for the LLM: the next move, given what's happened so far."""
    done = [m["tool"] for m in transcript if m["role"] == "result"]
    if "look_up_order" not in done:
        return {"tool": "look_up_order", "args": {"order_id": "A17"}}
    if "return_window" not in done:
        return {"tool": "return_window", "args": {"item": "tent"}}
    if "issue_refund" not in done:
        return {"tool": "issue_refund", "args": {"order_id": "A17", "amount": 189.0}}
    return {"answer": "Your refund of $189.00 is on its way."}


for m in run_agent(scripted_model, TOOLS, "I want to return my tent, order A17", 10):
    print(m["role"], "|", m.get("tool", ""), m.get("args", m.get("content", m.get("text", ""))))
Predict

How many times does run_agent call the model before it gets an answer?

Pick one to see what it prints.
Pick an answer above to see the rest
Part 1 done
Part 2 of 7about 9 min
Tools

A tool is a name, a description and a schema, and the harness checks every call against it

What the model reads before it calls a tool

A tool reaches the model as a definition: a name, a description in plain words, and an input schema, which Anthropic's docs describe as a JSON Schema object defining the expected parameters for the tool. Here's the refund tool:

REFUND_TOOL = {
    "name": "issue_refund",
    "description": "Refund an order. Call it only after look_up_order shows the order is unused and inside "
                   "its return window. amount is the refund in dollars, at most the order total.",
    "input_schema": {
        "type": "object",
        "properties": {"order_id": {"type": "string"}, "amount": {"type": "number"}},
        "required": ["order_id", "amount"],
    },
}
Predict

Which part of a tool definition matters most to how well the model uses the tool?

Pick an answer above to see the rest

Check every call's arguments before anything runs

The schema tells the model what to send, and the model can still send something else. A harness checks before it runs anything.

# what issue_refund takes
REFUND_ARGS = {"order_id": str, "amount": float}


for args in ({"order_id": "A17", "amount": 189.0}, {"order_id": "A17", "amount": "189"},
             {"order_id": "A17"}, {"order_id": "A17", "amount": 189.0, "reason": "too big"}):
    print(check_args(args, REFUND_ARGS))
Predict

The model sends amount as the text "189" instead of the number 189.0. What does the check report?

Pick one to see what it prints.
Pick an answer above to see the rest
Part 2 done
Part 3 of 7about 13 min
When things go wrong

Errors go back to the model as results, and every loop needs limits

When a tool fails in the middle of a run

The order service will time out some day, in the middle of a run. If the harness lets that exception escape, the run dies and the customer gets nothing. Anthropic's docs say to send a tool_result block with is_error set to true when a tool fails or a call is invalid, so the model can decide what to do next.

The code below uses run_tool(tools, name, args), which runs one call and returns a result with an is_error flag. You write its last piece in this step's task. Here it calls an order service that times out once, then calls it again, then asks for a tool that doesn't exist.

tries = {"n": 0}


def flaky_lookup(order_id: str) -> str:
    """The order service times out on its first call."""
    tries["n"] += 1
    if tries["n"] == 1:
        raise TimeoutError("order service timed out")
    return look_up_order(order_id)


print(run_tool({"look_up_order": flaky_lookup}, "look_up_order", {"order_id": "A17"}))
print(run_tool({"look_up_order": flaky_lookup}, "look_up_order", {"order_id": "A17"}))
print(run_tool({}, "cancel_everything", {}))
Predict

The first call to flaky_lookup raises a timeout. What does the second print line show?

Pick one to see what it prints.
Pick an answer above to see the rest

Stop on a step limit, on repeated calls, and on a budget

Anthropic's agents post notes that it's common to include stopping conditions, such as a maximum number of iterations, to maintain control, and that the autonomy of agents means higher costs and the potential for compounding errors.

Predict

A model calls look_up_order for A17, gets the record, and asks for the same lookup again, over and over. The loop's only limit is 10 steps. How many lookups run?

Pick an answer above to see the rest

Every turn sends the whole history again, so a run reads far more than its last turn

The budget matters because every turn sends the whole transcript again. Anthropic's docs describe each follow-up request as containing the original messages, the assistant's response and the tool results.

In the returns run, the first model call reads 2,400 tokens: the instructions, the tool definitions and the question. Each call and its result then add to the history, by 120, 80, 60 and 40 tokens, and every later call reads all of it. turn_sizes(first, added) lists what each call reads. You write it in this step's task.

sizes = turn_sizes(2400, [120, 80, 60, 40])
print(sizes, sum(sizes))
Predict

The returns run takes 5 model calls, and the last one reads 2,700 tokens. About how many input tokens did the whole run read?

Pick one to see what it prints.
Pick an answer above to see the rest
Part 3 done
Part 4 of 7about 9 min
Consequences

Actions with consequences need a person, and must be safe to repeat

Some calls can hurt someone

Looking up an order can't hurt anyone, and paying money can. Anthropic's docs for its computer use tool list asking a human to confirm decisions that might result in meaningful real-world consequences, and say that if your application asks for confirmation, the check comes before each action runs.

Predict

The shop's rule: a person approves any refund over $100. The agent wants to refund $189 on order A17. What does the harness do?

Pick an answer above to see the rest

Make the risky tool safe to call twice

The refund call times out. Did the money move? The harness can't tell, and retrying might pay twice. The fix is an idempotency key: a name for the operation, so a repeat with the same key does nothing new. The code below calls refund_once, the refund you write in this step's task.

# idempotency key -> amount paid
paid = {}
print(refund_once(paid, "A17", 189.0, "A17-return-1"))
# the retry after a timeout
print(refund_once(paid, "A17", 189.0, "A17-return-1"))
print("payments:", len(paid))
Predict

The refund call times out after the payment went through, and the agent retries with the same key. How many payments are there?

Pick one to see what it prints.
Pick an answer above to see the rest
Part 4 done
Part 5 of 7about 4 min
Grading agents

Grade an agent by the state it leaves behind, over many runs

Anthropic's advice on writing tools for agents includes building an evaluation to measure how well the tools perform. For the returns agent, the outcome is what the payment system holds after the run: one refund, for the right amount, on the right order. That's checkable in code, whatever path the agent took.

The simulation below runs the agent 300 times, and one run in ten slips a digit in the amount. The check looks only at the outcome. It also prints pass^3, from the evals lesson: the chance that three runs in a row all pass.

import random

rng = random.Random(4)
outcomes = []
for _ in range(300):
    # one run in ten slips a digit
    amount = 189.0 if rng.random() < 0.9 else 18.9
    # the outcome check: the right refund
    outcomes.append(amount == 189.0)
p = sum(outcomes) / len(outcomes)
print(f"pass rate {p:.1%}, so pass^3 is about {p ** 3:.1%}")
Predict

A customer who comes back three times meets the agent three times. If 88% of runs pass, about how often do all three go right?

Pick one to see what it prints.
Pick an answer above to see the rest
Part 5 done
Part 6 of 7about 5 min
The worked example

A worked example: the shop's returns agent, designed out loud

The prompt, from a candidate's Anthropic round: a tooling scenario in which the model must plan, then call a tool. How would you build it (1 report)? Answer it with the returns agent.

Clarify what the agent may do, then build the loop around it

1. Clarify. Which actions are irreversible? Refunds. What may the agent never do? Change an address or cancel an order. What's the refund limit before a person approves? How fast must it answer, and what happens when a tool is down?

Predict

The agent should never cancel orders. What's the surest way to enforce that?

Pick an answer above to see the rest
Predict

Which of these is the model's job in the returns agent, not the harness's?

Pick an answer above to see the rest
Part 6 done
Part 7 of 7about 8 min
Follow-ups

What interviewers ask next

Two calls in one turn

A model's reply can hold more than one tool call. Here, the returns agent wants the order and the return policy at once.

Predict

The model asks for look_up_order and return_window in the same turn. Can the harness run them at once?

Pick an answer above to see the rest

A long task fills the context, so summarize as you go

An agent working through a long task piles up tool results until the context fills. Anthropic describes compaction: summarize a conversation nearing the context limit and start a new context window with the summary.

Predict

The agent works through 40 returns in one run and nears the context limit. What should the summary keep?

Pick an answer above to see the rest

Where this shows up

The reports behind this lesson, each with its source.

Applied AI Engineer, Enterprise asks for production experience with LLM applications: prompting, context engineering and agent architectures.

“Production experience with LLM-powered applications, including prompting, context engineering, agent architectures”
Company source·Anthropic job posting (Greenhouse)Source

Practice

Sources (20)
  1. Building effective agents · Anthropic Engineering · Dec 19, 2024
    “They are typically just LLMs using tools based on environmental feedback in a loop.”
  2. Building effective agents · Anthropic Engineering · Dec 19, 2024
    “the most successful implementations weren't using complex frameworks or specialized libraries. Instead, they were building with simple, composable patterns.”
  3. Building effective agents · Anthropic Engineering · Dec 19, 2024
    “it's also common to include stopping conditions (such as a maximum number of iterations) to maintain control.”
  4. Building effective agents · Anthropic Engineering · Dec 19, 2024
    “The autonomous nature of agents means higher costs, and the potential for compounding errors.”
  5. How tool use works · Anthropic, Claude Platform Docs · Nov 19, 2026
    “every tool call is a round trip: the model asks, you execute, you report back, the model continues.”
  6. How tool use works · Anthropic, Claude Platform Docs · Nov 19, 2026
    “Claude responds with stop_reason: "tool_use" and one or more tool_use blocks.”
  7. How tool use works · Anthropic, Claude Platform Docs · Nov 19, 2026
    “Send a new request containing the original messages, the assistant's response, and a user message with the tool_result blocks.”
  8. Handle tool calls · Anthropic, Claude Platform Docs · Nov 19, 2026
    “When a client tool fails or a call is invalid, send a tool_result block with is_error set to true.”
  9. Handle tool calls · Anthropic, Claude Platform Docs · Nov 19, 2026
    “Claude might then call the tool again with a new tool_use block, so limit how many retries your loop allows.”
  10. Define tools · Anthropic, Claude Platform Docs · Nov 19, 2026
    “input_schema A JSON Schema object defining the expected parameters for the tool.”
  11. Define tools · Anthropic, Claude Platform Docs · Nov 19, 2026
    “Provide extremely detailed descriptions. This is by far the most important factor in tool performance.”
  12. Parallel tool use · Anthropic, Claude Platform Docs · Nov 19, 2026
    “Independent, read-only operations are usually safe to run in parallel for lower latency.”
  13. Function calling · OpenAI API docs · Nov 19, 2026
    “The model may choose to call multiple functions in a single turn.”
  14. Writing effective tools for agents - with agents · Anthropic Engineering · Sep 11, 2025
    “tool implementations should take care to return only high signal information back to agents.”
  15. Writing effective tools for agents - with agents · Anthropic Engineering · Sep 11, 2025
    “Building an evaluation allows you to systematically measure the performance of your tools.”
  16. Effective context engineering for AI agents · Anthropic Engineering · Sep 29, 2025
    “Context, therefore, must be treated as a finite resource with diminishing marginal returns.”
  17. Effective context engineering for AI agents · Anthropic Engineering · Sep 29, 2025
    “Compaction is the practice of taking a conversation nearing the context window limit, summarizing its contents, and reinitiating a new context window with the summary.”
  18. ReAct: Synergizing Reasoning and Acting in Language Models · Yao et al., arXiv 2210.03629 (ICLR 2023) · Oct 6, 2022
    “we explore the use of LLMs to generate both reasoning traces and task-specific actions in an interleaved manner”
  19. Computer use tool · Anthropic, Claude Platform Docs · Nov 19, 2026
    “Asking a human to confirm decisions that might result in meaningful real-world consequences and any tasks requiring affirmative consent”
  20. Computer use tool · Anthropic, Claude Platform Docs · Nov 19, 2026
    “If your application asks a human to confirm consequential actions, make that check before each block runs”