AgentLu
← Learn

Tools & Actions

15 min read

A model on its own can only produce text. It cannot look up tomorrow's weather, convert kilometres to miles, check whether a course has seats left, or put a notebook in a shopping cart. Everything an agent actually *does* is done by ordinary functions that you wrote, called from ordinary code that you control.

The model's contribution is deciding which of those functions to call, with which arguments, and when to stop. That is genuinely useful - it is the difference between an app that only handles the three requests you coded and one that handles the request the student actually typed. But it is a *request*, not an action, and keeping those two ideas separate is the whole skill in this section.

It also changes what 'the agent' looks like. There is no magic step where the model reaches into your app. There is a loop: your code shows the model a list of tools, the model replies with a tool name and some arguments, your code checks them, runs the function, and feeds the result back. Every exercise here shows you that loop running, step by step, in the preview.

What a tool call actually is

A tool is three things in one file. A catalogue entry - a name, a description and the arguments it takes - which is what your code shows the model so it knows what it may ask for. An argument check - a function that decides whether a request is complete and sane. And the tool itself - a plain function that does the work and returns a value, or an error.

None of that involves a model. You could call the tool yourself from any other part of your app. The model's only role is choosing it: 'the student said convert 5 km to miles, so I will ask for `convert` with `{ value: 5, from: "km", to: "miles" }`.'

Which means the answer to 'why did the agent do that?' is always readable. It is either in the catalogue (the model had the option), in the model's reply (it asked for it), or in your code (you decided to run it). The tool trace in the exercises shows all three side by side, because an agent you cannot inspect is an agent you cannot fix.

export const TOOLS = [
  { name: "convert", description: "Convert a value between units of the same kind", args: ["value", "from", "to"] },
];

export function checkArgs(name, args) {
  const tool = TOOLS.find((entry) => entry.name === name);
  if (!tool) return { ok: false, issues: [{ field: "tool", message: "unknown tool: " + name }] };
  const missing = tool.args.filter((arg) => args?.[arg] === undefined || args[arg] === null);
  return { ok: missing.length === 0, issues: missing.map((arg) => ({ field: arg, message: arg + " is required" })) };
}

export async function convert({ value, from, to } = {}) {
  const source = UNITS[String(from).toLowerCase()];
  const target = UNITS[String(to).toLowerCase()];
  if (!source) return { error: "I do not know the unit " + from };
  if (!target) return { error: "I do not know the unit " + to };
  if (source.dim !== target.dim) return { error: "cannot convert " + source.dim + " to " + target.dim };
  return { value: (Number(value) * source.to) / target.to };
}javascript

One tool, in the three parts it always has. The catalogue is data the model can read; the check is code the model never sees; the tool is the thing that does the work.

When a tool beats a prompt

Tools are for the things a prompt cannot do: look something up, calculate something exactly, or change something. Reaching for a prompt where a tool belongs is the most common design mistake in this section.

Asking the model to know a fact

Weak
System: You are a campus assistant. Answer questions about course availability.
User: Does CS 210 have seats left?javascript
Improved
System: You are a campus assistant. You do not know course data - use the tools: searchCourses, checkPrerequisites, getSeats.
User: Does CS 210 have seats left?javascript

The first version invites the model to invent a plausible seat count, and a plausible seat count is worse than no answer. The second version says where the truth lives and gives the model a way to get it. A model that has been told it does not know something is much less likely to make it up.

One tool that does everything

Weak
Tools: [ { name: "handleCampusRequest", args: ["request"] } ]javascript
Improved
Tools: [ searchCourses(query), checkPrerequisites(course), getSeats(course) ]javascript

A single giant tool just moves the hard work into a function you have to write by hand - and you lose the model's judgement about *what* to look up. Small tools with obvious names are also much easier to validate: each one has two or three arguments you can check, instead of one blob of free text.

The model asks, your code acts

The loop is short enough to write out in full. You show the model the catalogue. The model replies with a tool name and arguments - or with nothing, when it has enough to answer. You check the arguments. If they are bad, you stop and say what is missing. If they are good, you run the tool, keep the result, and go round again with the result included.

Two details make the difference between a demo and something that works. First, the arguments are checked *before* the tool runs, by you - because a model can name a tool that does not exist, or leave out the one argument the tool needs, and a prompt cannot promise otherwise. Second, the loop has a limit. A model that keeps asking for the same tool is a real failure mode, and 'it eventually stops' is not a plan.

Notice who writes the final sentence. The model is good at choosing what to look up and bad at turning three JSON results into a clear answer, so in these exercises the *code* builds the reply from the results. That is not a shortcut; it is the point. The model decides, the code is responsible.

for (let turn = 0; turn < 4; turn += 1) {
  const plan = await llm({ system: PLAN_PROMPT, user: JSON.stringify({ request: input, steps }), json: true });
  const call = safeParse(plan.content);
  if (!call || !call.tool) break;                    // the model is done asking

  const check = checkArgs(call.tool, call.args);      // before anything runs
  if (!check.ok) { issues = check.issues; break; }

  const result = await callTool(call.tool, call.args);
  steps.push({ tool: call.tool, args: call.args, result });
}

const answer = summarise(steps);                      // code writes the replyjavascript

The whole tool loop. The model's reply is a request; everything after `checkArgs` is your app deciding whether to honour it.

Building the campus assistant, step by step

The exercise asks 'can I take CS 210?' and the answer needs three tools, in order. Each turn of the loop is one model decision and one piece of your code.

1. Look at the loop you were given

The starter already does everything once: it asks the model for a tool call, checks the arguments, runs the tool, and answers from that single result. Run it and watch the trace - you will see one model request, one `searchCourses` call, and an answer that stops short. Nothing is broken; the loop simply is not a loop yet.

2. Feed the result back and go round again

The change that makes it an agent is passing the steps so far back to the model on each turn. The model now sees that the catalogue was already searched and that the course id is CS 210, so the next thing it asks for is the prerequisites. You are not telling it what to do - you are giving it the state it needs to decide.

const plan = await llm({
  system: PLAN_PROMPT,
  user: JSON.stringify({ request: input, steps }),
  json: true,
});javascript

3. Stop when the model stops asking

The model signals 'I have enough' by replying with no tool. That is the loop's exit condition, and it is why the prompt has to say so explicitly: 'when no tool is needed any more, reply with { "tool": null }'. Without it a model will happily keep searching for something to do, which is how a two-second answer becomes a ten-call run.

4. Validate before you run, and answer from the results

`checkArgs` runs before `callTool`, every time, and a failed check ends the loop with the issues kept. That is what turns 'the tool threw an error' into 'I need the course code before I can check the prerequisites'. Then the code writes the reply from the three results - the course, whether the prerequisites are met, and how many seats are open - so the sentence the student reads is assembled from facts rather than generated.

Read-only and state-changing tools are not the same risk

Searching a catalogue twice is harmless. Adding the same notebook to a cart twice is not. Reading a seat count costs nothing; booking the seat costs something. The moment a tool changes state, the cost of a wrong request stops being a bad answer and starts being a wrong order, a double booking, or a message sent to the wrong person.

That is why argument checking matters most exactly where it feels least necessary. A missing quantity in a search is a slightly worse search; a missing quantity in an order is a guess about how many notebooks somebody wanted. In the store exercise the request 'add two notebooks' reaches the planner as the word 'two' - present, and not a number - and the check that catches it is the type check, not the presence check.

The habit worth building is simple: before a state-changing call, ask what the worst version of this request would do. If the answer is 'change something nobody meant to change', the argument check is not optional, and neither is refusing to run the tool until the request is complete. Saying 'how many would you like?' is a better answer than a cart with the wrong thing in it.

Mistakes worth catching early

What goes wrongWhat it looks likeWhat to do instead
Running the tool without checkingA tool called with a missing argument, or one the catalogue does not contain.Call `checkArgs` before `callTool`, every time, and stop on a failure.
Checking presence but not type'two' passes the check and becomes a quantity, because it is not empty.Declare the type of each argument in the catalogue and check it.
An unbounded loopThe model asks for the same tool five times and the run never ends.Cap the loop at three or four turns and answer from what you have.
Letting the model write the final answerA confident sentence that contradicts the tool results above it.Build the reply in code from the results you actually got.
Tools nobody can seeNo trace, so 'why did it do that?' has no answer.Show the model's request, the call and the result - the preview does this for you.
A tool that throws instead of reportingOne bad request ends the whole run, and the student sees a crash.Return `{ error: "..." }` from the tool and let the agent decide what to say.

Debugging a tool-using agent

  • Read the trace before you read your code. The three things that go wrong - the model asked for the wrong tool, the arguments were wrong, or the tool itself failed - are each visible in a different step.
  • Check the catalogue first. A model cannot ask for a tool it was never shown, and it will ask for a tool whose description is too vague to tell apart from its neighbour.
  • When the same tool is called over and over, the model is not seeing its own result. Feed the steps back, and say in the prompt what to do when it has enough.
  • When an argument is wrong, decide whether the fix belongs in the prompt (the model chose badly) or in the check (the model could not know). 'quantity must be a number' is a check; 'quantities are numbers, not words' is a prompt line.
  • Test the failure path on purpose: a missing argument, an unknown unit, a product that is out of stock. An agent that only works on the happy path is an agent that has never been tested.