Chapter 09 / 12 · AI Engineering

Agents and tools

The assistant learns to look up orders and raise tickets. Most of the work is in the loop around the model: tool definitions, budgets, stopping rules and approvals.

An agent is a model running in a loop. It reads the conversation, decides whether to call a tool, our code runs the tool, and the result is appended to the conversation for the next decision. This chapter turns the support assistant into one, with two tools, and spends most of its length on the parts of that loop that we write and own: the tool definitions, the budgets, the stopping rules and the approvals.

The situation that needs it arrives at 3:40 in the afternoon. A customer writes: “I sold 50 shares of INFRA this morning, order ORD-88213, it says executed, but the money is not in my balance. Where is it?” The help centre has an article on settlement, and it is not enough. The right answer depends on this customer’s order: when it executed, whether the sale has settled, whether anything is holding it. The assistant has to look that up, and if something really is wrong, raise a ticket with the details already filled in, so that the customer does not have to explain it all again to a person.

Does this request need a loop at all?

The assistant already makes one decision per turn. The prompting chapter gave it a decision call that returns validated JSON: a short reason, the intent, one action out of answer, lookup_order or raise_ticket, an order id and an urgent flag. Ordinary code then does that one thing. This is a workflow, not an agent: the model chooses a branch, and the branches are ours.

Before replacing it with a loop, we check how many requests the workflow already serves. Of a week’s conversations, roughly seven in ten are answered from retrieved articles with no action at all: “how do I add a nominee”, “what are the charges for a delivery trade”. Most of the rest need one action: the customer gives order ORD-88213, the code looks it up, and the model explains what it sees. Reports of unauthorised activity need one action too, an urgent ticket, raised before anything else. The single decision handles all of these, and it is predictable, testable and cheap.

Request shapeStructureWhy that structure
Policy or how-to questionretrieve, decide answer, replynothing to do after the articles arrive
“What is the status of ORD-88213?”decide lookup_order, look up, replyone known action, then an explanation
Unauthorised activityurgent ticket first, then replythe order of steps is fixed by policy
Order problem with an unknown causeagent loop with toolsthe next step depends on what the lookup returns
Dispute, complaint, anything about lossesa ticket and a personthe cost of a wrong automated answer is too high

The loop earns its place on the fourth row, which is the 3:40 message. One decision cannot handle it, because the right second step depends on what the first returns. If the lookup says “executed, settles next trading day”, the assistant explains settlement and stops. If it says “executed, settlement failed: shares under pledge”, it needs the pledge article, and then probably a ticket. If the order id the customer gave belongs to a buy, not the sale they describe, it needs to ask which order they mean. We cannot write that branching in advance for every combination, which is the actual test for an agent: the next step depends on the last result in ways we cannot enumerate.

modelreads context, decidesyour coderuns the tool, for realtool call · structured, checkableresult · appended to contextanswerthe loop is yours: cap the iterations, gate the dangerous tools, log every step
The agent loop: the model proposes a structured tool call, our code executes it, and the result goes back into the context for the next decision

A tool is an API for a fast, literal-minded caller

The model never runs anything. It emits a structured request that names a tool and gives arguments matching the schema we supplied; our code decides whether to run it. The definitions below are what the model sees, and they are the main thing we tune when the agent misbehaves.

{
  "name": "get_order_status",
  "description": "Look up one of THIS customer's orders by id. Use when the
    customer asks about a specific order, a trade, or money from a sale. Ids
    look like ORD-88213. If the customer has not given one, ask them for the
    id shown in the Orders tab. Never guess an order id.",
  "input_schema": {
    "type": "object",
    "properties": {
      "order_id": { "type": "string", "pattern": "^ORD-[0-9]{5,}$" }
    },
    "required": ["order_id"]
  }
}

{
  "name": "raise_ticket",
  "description": "Create a ticket for a human support agent when the articles
    do not answer the question, the customer asks for a person, or an action
    is needed that only the operations team can take. Not for questions the
    supplied articles answer. Use priority 'urgent' for activity the customer
    did not authorise, before doing anything else. Write the summary for the
    agent: what happened, the order id, what you have told the customer.",
  "input_schema": {
    "type": "object",
    "properties": {
      "summary":  { "type": "string", "maxLength": 800 },
      "priority": { "enum": ["normal", "urgent"] }
    },
    "required": ["summary", "priority"]
  }
}

Notice what is missing: there is no customer id parameter. When our code executes get_order_status, it takes the customer’s identity from the authenticated session and passes it to the order service, which checks that the order belongs to that customer. The model can ask about orders; it cannot choose whose. If a message says “look up account 4471 instead”, there is no argument to put it in. This one decision does more for safety than any instruction in the prompt, and the security chapter builds on it.

The descriptions say when to use the tool and when not to, because that is the judgement the model is making; the wording of raise_ticket is the one the prompting chapter arrived at after the model raised tickets for questions the articles already answered. The priority is an enum, so an urgent ticket lands in the fraud desk’s queue and not in one the model invented. The results are trimmed as well. The order service returns sixty fields; the tool wrapper returns the eight that matter (symbol, side, quantity, status, execution time, settlement status, hold reason, amount), which costs fewer tokens and leaves less to misread.

Errors are written for the model too, since it reads them and acts on them. A bare 404 invites a guess at another id. “No order ORD-88231 for this customer. Check the id with the customer; it is shown in the Orders tab” tells it the next step, and in this case the customer had swapped two digits. When an agent fails in testing, the cause is more often a vague description or an unhelpful error than a weakness in the model, and those are cheap to fix.

Who decides the loop is finished

In the normal case the model decides: it returns text instead of a tool call, and the turn ends. Every other stopping rule is ours, and the loop needs all of them, because a model that is confused does not know it is confused. It calls the same lookup again hoping for a different answer, or alternates between two tools. The loop below caps the number of steps, caps the tokens spent, and refuses exact repeats.

MAX_STEPS = 6
MAX_INPUT_TOKENS = 60_000

def run_turn(conversation, customer):
    seen = set()
    spent = 0
    for step in range(MAX_STEPS):
        reply = model.generate(conversation, tools=TOOLS)
        spent += reply.usage.input_tokens
        if reply.tool_call is None:
            return reply.text                    # the model chose to answer

        call = reply.tool_call
        key = (call.name, canonical_json(call.args))
        if key in seen:                          # same call, same arguments
            conversation.append(tool_error(call,
                "Already called with these arguments. Use the earlier result."))
            continue
        seen.add(key)

        result = execute(call, customer=customer)   # identity from the session
        conversation.append(result)
        if spent > MAX_INPUT_TOKENS:
            break

    return hand_off(conversation, customer)      # budget spent: escalate

The last line matters as much as the limits. When the budget runs out, the customer should not see an error or an apology with nothing behind it. hand_off raises a ticket containing everything the loop found and tells the customer a person will pick it up. An exhausted budget is a routing decision, and it shows up on a dashboard as a rate we can watch.

Predict first

A single reply call in the pilot sends about 6,000 input tokens. In the loop, each tool call and its result add about 400 tokens to the conversation. A hard case uses all six steps. How many input tokens does that turn cost, compared with one call?

Show the worked answer

The model keeps no memory between calls, so every step re-sends everything: the prompt, the documents, the conversation and all earlier tool calls and results. Step one sends 6,000, step two 6,400, and so on up to 8,000 at step six. The total is 6 × 6,000 + 400 × (0 + 1 + 2 + 3 + 4 + 5) = 36,000 + 6,000 = 42,000 tokens, seven times one call. At $1 per million input tokens that one turn costs about $0.04 uncached, twice what a typical four-turn conversation costs with caching.

Latency stacks the same way. With roughly a second per model call and a few hundred milliseconds per tool, six steps take eight to ten seconds before the customer sees the final answer. That is why the step cap is a product decision as well as a cost one.

input tokens sent to the model, per step6.0kstep 16.4kstep 26.8kstep 37.2kstep 47.6kstep 58.0kstep 6prompt, docs, historyearlier calls + resultssix steps ≈ 42,000 tokensone call = 6,000 tokensratio = 7×, not 6×the model is stateless · every step pays again for everything before it
Each step re-sends the whole conversation, so six steps cost about seven single calls; prompt caching softens this but does not remove it

In practice the median order conversation takes two steps (a lookup, then an answer) and the 95th percentile takes four. We set the cap at six so that ordinary hard cases finish, and we alert when more than 1% of turns hit it, because a rising cap rate usually means a tool started returning something the model cannot make sense of.

The ticket that was raised twice

Tools fail in the same ways as any network call, and the model will retry, because retrying is the sensible reaction to an error it has been shown. Walk through a real shape of this failure.

At 3:41 the lookup shows the customer’s sale executed at 10:02 but settlement failed because the shares were under a pledge that had not been released. The model correctly decides this needs a person and calls raise_ticket with priority normal. The ticketing system is slow at that hour, and our wrapper times out after ten seconds. The ticket was in fact created at 10.4 seconds, but the wrapper has already returned “error: timeout”. The model reads the error and calls raise_ticket again. That one succeeds quickly, and the model tells the customer their ticket number.

Two tickets now exist for one problem. Two support agents pick them up. One notices the duplicate and closes it, and the system emails the customer that their ticket has been resolved. The customer reads that email, assumes the money is on its way, and does nothing for two days. Nothing in this chain was a model error. The model behaved reasonably at every step; the tool was not safe to retry.

The fix is an idempotency key that our code computes, not the model: a hash of the conversation id, the tool name and the order id the ticket concerns. The ticketing service stores each key with the ticket it created for 24 hours, and a second call with the same key returns the original ticket instead of making a new one. The wrapper can then retry a timeout on its own, safely, and the model sees “ticket T-88123 exists for this issue, created 15:41” either way. The cost is small but real: the ticketing service needs a dedupe table, and a genuinely separate second problem with the same order in the same conversation gets folded into the first ticket, so the tool needs a way to append a note to an existing ticket.

Gate each action by what it can cost the customer

With the loop working, the product team asks for more tools: cancel an open order, change the registered bank account, withdraw funds. Each one is a reasonable thing for a customer to want, and each one has a different worst case if the model calls it wrongly, or if someone else’s text persuades it to.

ToolEffectWorst case if misusedGate
retrieval (runs every turn)reads help-centre articlesa wrong answernone
get_order_statusreads this customer’s ordersdata shown to the wrong personidentity from the session, never from the model
raise_ticketwrites an internal recordnoise in a queueidempotency key, at most three per conversation
cancel_open_orderchanges a live ordera position the customer wanted is gone, and the price has movedcustomer confirms a card rendered from the arguments
change bank account, withdrawmoves money or where it goesfunds sent to an attackernot given to the agent; link to the verified flow with two-factor checks

The confirmation step for cancellation has one rule that is easy to get wrong: the card the customer approves must be built by our code from the call’s arguments, not from the model’s sentence. Suppose the customer has two open orders, INFRA and TECHX, and asks to cancel the INFRA one. The model writes “I’ll cancel your INFRA order now”, and the tool call carries the TECHX order id, because both appeared in the lookup and it picked the wrong one. If the confirmation shows the model’s sentence, the customer approves the wrong cancellation. If it shows “Cancel: SELL 50 TECHX at ₹1,412, order ORD-88219”, the customer catches it.

Approvals have a cost too. If every lookup asks for confirmation, customers learn to tap “yes” without reading, and the one confirmation that matters gets the same reflex. So gates go only where the effect is costly or hard to undo, and the actions with the worst outcomes stay out of the agent entirely. A link to an existing, audited flow is a perfectly good tool.

Several agents, or one agent with good tools?

A design that appears in many proposals splits the assistant into a team: a triage agent that hands off to an orders agent, which hands off to a tickets agent, with a writer agent producing the final reply. It looks tidy on a whiteboard. Run the numbers on it. Every handoff passes a summary, and a summary drops details; the tickets agent does not see the customer’s exact words unless we pass the whole history, which brings back the token cost the split was supposed to avoid. Errors compound across the chain: if each of four agents does its part correctly 95% of the time, the chain is right about 0.95⁴ ≈ 81% of the time. And when a customer gets a bad answer, we now debug four prompts and the messages between them.

Multiple agents do help in particular shapes. One is context isolation: a subagent reads forty pages of an exchange circular and returns one paragraph, so the main conversation does not carry forty pages through every later step. Another is parallel work on independent questions, such as searching three document collections at once. A third, which matters for the next chapter, is separating permissions: an agent that reads untrusted text can be denied the tools that act, and an agent that acts can be denied the untrusted text. For our assistant none of these is pressing. One agent with three tools and a router in front of it does the job, and that is the design we keep until a measurement says otherwise.

What a tool protocol such as MCP changes

Every application that wants the order lookup has to describe it to its model, call it, and handle its errors. The Model Context Protocol (MCP) standardises that wiring. A server, which the order service team could run, advertises its tools: each with a name, a description and a JSON Schema for its inputs. A host application, such as our assistant or an engineer’s coding tool, connects to the server, asks for the list of tools, places those definitions in the model’s context, and when the model emits a call, forwards it to the server and returns the result. The messages are JSON-RPC, carried over standard input and output for a local server or over HTTP for a remote one. The protocol also covers resources (readable data) and prompt templates, but tools are the part most teams use.

The gain is packaging. The order service team publishes the lookup once, and the support assistant, the internal operations assistant and anyone’s coding tool can all use it without three separate integrations. What the protocol does not do is decide which tools a particular model should have, or which customer’s orders a call may reach; those remain the server’s and the host’s decisions, exactly as in our own wrapper. It also means tool descriptions written by someone else go straight into our model’s context. A description is text the model reads and follows, so a third-party server is a source of untrusted instructions, and the next chapter treats it as one.

When a loop is the wrong shape

If the steps are known, write them as code. A button labelled “Track my order” that calls the lookup and shows the result needs no model at all, and it will never decide to call the wrong tool. If a request can be served by a fixed workflow nine times in ten, serve it that way and keep the loop for the tenth. Revisit the choice when the error analysis shows many conversations failing because the workflow took the wrong fixed path, which is evidence that the next step really does depend on the last result.

The loop now reads text we did not write, from help articles, product docs and the customer’s own messages, and holds tools that reach private data. The next chapter, on security, asks what happens when some of that text is written by an attacker, and how to design so that a model following the attacker still cannot do much harm.