Katkat

Tool Calling and the Agent Loop

By the Katkat team · Updated · 8 min read

Quick overview

Learn how LLM tool calling works, how the observe-think-act agent loop runs, and which stopping conditions stop agents from looping or overspending.

Lesson 26 of 88 · AI Engineering Interview Course

After this lesson you should be able to explain what actually happens when a model "calls a function": the model only writes a request, and your code does the work. You should be able to sketch the observe-think-act loop that turns single tool calls into an agent, and to list the conditions that must end that loop. You should also be able to estimate what a multi-step loop costs in tokens.

What tool calling is (and is not)

A language model can only produce tokens. It cannot query a database, call an API or run code. Tool calling (also called function calling) is a convention that lets a model ask for those things in a structured way, so that the application around it can do them.

The division of labour is the key idea:

  • The model decides whether a tool is needed, picks which one, and writes the arguments.
  • Your code validates the request, runs the tool, and decides what to send back.
  • The model reads the result and either answers or asks for another tool.

Models learn this behaviour during post-training: they are fine-tuned on examples where a tool request is the right output. See From Pretraining to Chat Model: SFT and RLHF for where that fits in. The model is not "running" anything. It is predicting a well-formed request.

The function-calling handshake

Most major APIs follow the same shape, though field names differ by vendor.

  1. Declare tools. With each request you send a list of tool definitions. Each has a name, a natural-language description, and a parameter schema, usually JSON Schema.
  2. Model responds with a tool call. Instead of (or alongside) text, the response contains one or more tool-call blocks: a tool name, an arguments object, and usually an ID.
  3. Execute. Your code parses the arguments, validates them against the schema, and runs the function.
  4. Return the result. You append a tool-result message that references the call ID, then call the model again with the whole conversation.
  5. Model continues. It reads the result as new context and produces the next output.

Three details matter in practice:

  • The tool definitions are prompt text. They are tokenised and count against the context window on every call. A large toolset is a real cost.
  • Arguments are generated, not guaranteed. The model can produce a missing field, a wrong type or an invented value. Always validate. Some APIs offer stricter schema-constrained generation, but you should not rely on it without checking the provider's documentation. See Getting Reliable JSON and Structured Output if you need the background.
  • Descriptions drive selection. The model chooses tools mostly from their names and descriptions. Vague descriptions cause wrong calls, which is covered in Designing Tools an Agent Can Use.

The observe-think-act loop

A single tool call is a one-shot feature. An agent is what you get when you run the handshake in a loop and let the model decide how many rounds it needs.

  • Observe: the model receives the current context: the task, previous steps, and the latest tool results.
  • Think: the model reasons about what is known and what is missing. This may be visible text or hidden reasoning, depending on the model.
  • Act: the model either emits a tool call or emits a final answer.

The loop is plain code:

messages = [system_prompt, user_task]
for step in range(MAX_STEPS):
    reply = model(messages, tools=TOOLS)
    messages.append(reply)
    if not reply.tool_calls:          # model chose to answer
        return reply.text
    for call in reply.tool_calls:
        result = run_tool(call.name, call.arguments)   # validate, time out, catch errors
        messages.append(tool_result(call.id, result))
raise StepLimitReached

The only thing that makes this an agent is that the model, not the programmer, chooses the next action on every iteration. Named patterns such as ReAct, plan-and-execute and reflection are variations on what goes into the "think" step and how the context is structured; they are compared in Agent Patterns: ReAct, Plan-and-Execute and Reflection. To practise writing the loop yourself, try Implement a Minimal Tool-Calling Agent Loop.

Note that the loop is stateless on the model side. The model remembers nothing between calls except what you put in messages. That is why the whole history is re-sent each time.

Worked example: what a four-call loop costs

Suppose:

  • System prompt plus tool definitions: 1,500 tokens
  • User task: 100 tokens
  • Each model turn that requests a tool: 80 output tokens
  • Each tool result: 400 tokens
  • Final answer: 150 output tokens
  • The agent makes 3 tool calls, then answers (4 model calls in total)

Each step adds 80 + 400 = 480 tokens of history. The input size of each call is:

Model callInput tokensCalculation
11,6001,500 + 100
22,0801,600 + 480
32,5602,080 + 480
4 (final)3,0402,560 + 480

Total input processed: 1,600 + 2,080 + 2,560 + 3,040 = 9,280 tokens. Total output: 3 × 80 + 150 = 390 tokens.

The final context is only 3,040 tokens, but you processed about 3x that as input (9,280 / 3,040 ≈ 3.05). Input cost grows roughly quadratically with the number of steps, because each step re-reads everything before it. With a hypothetical price of $3 per million input tokens, the input side costs 9,280 × 3 / 1,000,000 ≈ $0.028 for this one task. Caching a stable prefix can reduce that bill, as discussed in Prefix Caching, and the latency compounds too: four sequential model calls means four time-to-first-token delays plus the tool execution time.

Stopping conditions

A loop without exit conditions is a bug. A well-built agent has a natural stop plus several hard limits that fire when the natural stop does not happen.

ConditionWho decidesTypical response
Model returns no tool callModelTreat the text as the final answer. This is the normal exit.
Max steps reachedYour codeStop, return partial progress and an explicit "incomplete" status.
Token or cost budget exceededYour codeStop, or force a final summarising call with tools disabled.
Wall-clock timeoutYour codeCancel in-flight tool calls, return what exists.
Repeated identical callYour codeDetect same name and arguments seen before; break or inject a hint.
Unrecoverable tool errorYour codeFail fast, or escalate to a human.
Human approval declinedHumanStop or replan, depending on the product.
Explicit "done" or "give up" toolModelUseful when text output alone is an ambiguous signal.

Practical notes:

  • Step limits are a safety net, not a design. If a task regularly needs 20 steps, the limit should be above that, and you should ask why it needs so many.
  • Budget on tokens as well as steps. Ten cheap steps and ten expensive steps are not the same risk. The quadratic growth above is the reason.
  • A forced final call is friendlier than a crash. When a limit hits, one more model call with tools turned off (or a "summarise what you found" instruction) usually produces a more useful result than raising an exception.
  • Loop detection should compare normalised arguments, since a looping model often changes a single word in a query. Diagnosis of this failure is covered in An Agent Keeps Looping: How Do You Fix It?.

Trade-offs and design choices

Loop versus fixed workflow. If the steps are known in advance (retrieve, then summarise), a hard-coded pipeline is cheaper, faster and easier to test. Use an agent loop when the number and order of steps genuinely depend on intermediate results.

Parallel tool calls. Many APIs let the model request several independent calls in one turn. Running them concurrently saves wall-clock time and one model round trip. You must return a result for every call ID, and you must handle partial failure.

Forcing tool use. APIs generally let you choose between letting the model decide, requiring some tool call, requiring a specific tool, or disallowing tools. Exact option names vary by provider. Forcing a specific tool is a good way to get structured extraction; leaving it automatic is right for open-ended agents.

Tool errors are observations. When a tool fails, return a short, informative error as the tool result rather than throwing. The model can often correct a bad argument on the next turn. Retries, timeouts and idempotency belong in your code, not the prompt; see Making Agents Reliable: Retries, Timeouts and Checkpoints.

Tool results are untrusted input. A web page or document returned by a tool can contain instructions aimed at the model. Treat results as data, limit what tools can do, and require approval for side effects, as covered in Agent Safety: Permissions, Sandboxing and Human Approval.

Context growth. Long results crowd out the task. Truncate, summarise or store large outputs outside the context and return a handle.

How does this come up in interviews?

1. Walk me through what happens when a model "calls a function". The model never executes anything. It emits a structured request (name and JSON arguments), the application validates and runs it, then appends the result to the conversation and calls the model again. The model sees the result as ordinary context and continues. Mention that the tool schemas are part of the prompt and count towards tokens.

2. How would you design the stopping logic for an agent? The natural exit is the model replying without a tool call. Around that, add a max step count, a token or cost budget, a wall-clock timeout, and repeated-call detection. When a limit fires, return partial results with a clear status, or make one last tool-free call to summarise, rather than failing silently.

3. Your agent makes four tool calls. Why is the cost more than four times one call? Every iteration re-sends the full history, so input tokens grow with each step. In the example above, a 3,040-token final context cost 9,280 input tokens in total. Caching the stable prefix and trimming tool results reduce this.

4. The model passes a malformed argument to a tool. What do you do? Validate against the schema before executing. Return a concise error as the tool result so the model can retry, and cap the number of retries. If malformed calls are frequent, improve the tool description or simplify the schema.

5. When would you not use an agent loop? When the sequence of steps is fixed and known, a deterministic pipeline with one or two model calls is faster, cheaper and easier to evaluate. Use a loop only when the next step depends on what earlier steps return.

Common mistakes

  • Saying the model "runs" the tool. It only requests it; your code is responsible for execution and safety.
  • Forgetting to send tool results back with the matching call ID, or sending the result without the model's tool-call message in the history.
  • Trusting generated arguments without validation.
  • Relying on "the model will stop when it is done" with no step, token or time limit.
  • Counting only the final context size when estimating cost, instead of summing input across all calls.
  • Returning huge raw tool outputs, which inflates cost and buries the task.
  • Throwing exceptions on tool failure instead of returning an error the model can act on.
  • Giving the agent many overlapping tools with vague descriptions, which causes wrong selection.
  • Letting tool output (web pages, emails, files) be treated as instructions.