Tool-using agent: a model that acts through checked function calls

A tool-using agent lets the model ask for functions such as search or a database lookup, while your code checks and runs each call. Use it when answers need live data or real actions.

Tool-using agent in 60 seconds

  • What: the model proposes a call to a named function with arguments. Your code validates it, checks permission, runs it, and returns the result.
  • Why it matters: it gives the model fresh facts and the ability to act, which text alone cannot.
  • Best for: requests that need live data, calculations, or actions in other systems, such as order status, bookings, or ticket updates.
  • Weak spots: wrong tool choice, badly formed arguments, repeated side effects, and tools that can do more than they should.
  • Origin: Toolformer (Schick et al., 2023) showed a model can learn when to call tools, and ReAct (Yao et al., 2022) showed tool results can steer later reasoning.

Where this type fits

In the Types of AI agents hub, the tool-using agent is the first of the family about the kind of agent you build, alongside coding, browser, voice, and long-running agents. Most of those are tool-using agents with a particular set of tools. The deeper detail of how tool schemas and protocols work is on the tool calling and MCP page. This page is about the agent design around those calls.

The problem it solves

A model on its own knows only what it was trained on, and that has a cut-off date. Ask it for the status of order 4412 and it can only guess, and a confident guess is worse than none. It also cannot do anything. It cannot cancel a booking, send an email, or update a record.

The naive fix is to paste data into the prompt. That works for a small, fixed set of facts. It fails when the data is large, private to each user, or changes by the minute. It also does nothing for actions.

Tools give the model a way to ask. You describe each function in a schema: its name, what it does, and the arguments it takes. The model replies with a structured request instead of prose. This creates a new problem, though: the model is now proposing actions, and a proposal is not always safe. It may call the wrong tool, send a malformed argument, or request something the user has no right to. So the design centres on checking each call before running it.

How it works

  • Describe the tools: each tool has a name, a clear description, and a typed argument schema. The model sees these descriptions with the request.
  • The model proposes a call: instead of a final answer, the model returns the tool name and arguments in a structured format.
  • Validate the arguments: your code checks types, ranges, and required fields against the schema. Invalid calls are refused, and the error goes back to the model.
  • Check permission: your code decides whether this user, in this context, may run this tool with these arguments. This check never relies on the model's judgement.
  • Run the tool: execute with a timeout, and for actions that change things, an idempotency key so a retry does not repeat the effect.
  • Return the result: the output, or a clear error, goes back to the model. The model then calls another tool or writes the answer. A step limit ends the loop.
Every proposed call passes validation and a permission check before it runs, and the result returns to the model.

The two middle boxes are the heart of the design. Validation stops malformed calls. The permission check stops allowed-looking calls that the user has no right to make. Both run in your code, outside the model, so a persuasive prompt cannot talk its way past them.

The dashed arrow is what makes it an agent rather than a single call. The result is not the end. The model reads it and decides: call another tool, retry with fixed arguments, or answer. Because this can repeat, the loop needs a hard cap on steps and a total time budget.

A worked example

Acme Shop has a support agent with three tools: get_order(order_id) (read only), cancel_order(order_id, reason) (changes data), and send_email(to, body) (side effect, needs approval).

Request. A signed-in customer, user 77, writes: 'Please cancel my order 4412, it was a mistake.'

Step 1. The model proposes get_order(order_id="4412"). Validation passes: the id is a string of digits. Permission check: the order belongs to user 77, so it is allowed. The tool returns {status: "processing", total: 59.00, owner: 77}.

Step 2. The model proposes cancel_order(order_id="4412", reason="customer mistake"). Validation passes. The permission check confirms the order is owned by user 77 and is still cancellable. The call carries the idempotency key cancel-4412-77. The tool returns {status: "cancelled"}.

Step 3. The model wants to confirm by email and proposes send_email(...). This tool is marked 'needs confirmation', so the loop pauses and asks the customer. They agree, and the email is sent.

Answer. 'Order 4412 is cancelled. A confirmation email is on its way.' The run used three tool calls, well under the cap of eight.

A failure case. Suppose the model had proposed cancel_order(order_id="4413"), an order owned by user 90. Validation would pass, but the permission check would refuse. The error 'not permitted' returns to the model, which tells the customer it cannot help with that order.

A tool definition with a typed schema (illustrative) (json)
{
  "name": "cancel_order",
  "description": "Cancel an order that has not shipped. Changes data. Use only when the customer asks to cancel.",
  "side_effect": true,
  "needs_confirmation": false,
  "parameters": {
    "type": "object",
    "properties": {
      "order_id": { "type": "string", "pattern": "^[0-9]{1,10}$" },
      "reason": { "type": "string", "maxLength": 200 }
    },
    "required": ["order_id", "reason"]
  }
}

Building it

The loop below is the whole pattern. The model call, tools, and permission store are placeholders. Notice that validation and permission live in plain code, and that every loop has limits.

A tool loop with validation, permission, and limits (illustrative) (python)
# Placeholders: llm, tools, and policy are stand-ins, not real libraries.

MAX_STEPS = 8            # stop runaway loops
TOOL_TIMEOUT_S = 15      # no tool may hang the run
MAX_RESULT_CHARS = 4000  # keep results from flooding the context

def validate(tool, args):
    # Check required fields and types against the tool's schema.
    errors = tool.schema.check(args)
    return errors  # empty list means valid

def run_agent(user, request):
    messages = [{"role": "user", "content": request}]
    for step in range(MAX_STEPS):
        reply = llm.generate(messages, tools=tools.describe_all())
        if not reply.tool_call:
            return reply.text                       # the model has answered

        call = reply.tool_call
        tool = tools.get(call.name)
        if tool is None:
            result = {"error": "unknown tool"}      # never run unknown names
        else:
            errors = validate(tool, call.args)
            if errors:
                result = {"error": f"invalid arguments: {errors}"}
            elif not policy.allowed(user, tool, call.args):
                result = {"error": "not permitted"}  # enforced in code
            elif tool.needs_confirmation and not ask_user(user, call):
                result = {"error": "user declined"}
            else:
                key = f"{tool.name}-{call.args.get('order_id')}-{user.id}"
                result = tool.run(call.args, timeout_s=TOOL_TIMEOUT_S,
                                  idempotency_key=key)

        text = str(result)[:MAX_RESULT_CHARS]
        messages.append({"role": "tool", "name": call.name, "content": text})

    return "I could not finish this in the allowed steps. A person will follow up."

Design decisions

  • Tool granularity: prefer a few narrow tools with clear names over one broad tool. 'cancel_order' is safer and easier for the model to choose than 'run_query'.
  • Permission model: run each call with the end user's rights, not a shared powerful account. The model should never hold wider access than the person it serves.
  • Read versus write: mark tools that change things. Require confirmation for risky ones, and consider read-only mode as the default for new deployments.
  • Idempotency: give every side-effecting call a key, so retries and loops do not repeat the action. See the idempotency page.
  • Result handling: trim and clean tool output before it returns to the model. Treat returned text as untrusted, since it may contain instructions planted by a third party.
  • Limits and timeouts: set a step cap, a per-tool timeout, and a total time budget. A recommended starting point is eight steps and 15 seconds per tool.
  • Failure handling: return clear errors to the model so it can retry or explain. After repeated failures, hand over to a person.

Measuring it

  • Tool selection accuracy: on a labelled set of requests, the share where the first tool chosen is the expected one.
  • Argument validity rate: calls that pass validation first time, divided by all calls. A low rate points to unclear schemas or descriptions.
  • Task success rate: requests that reach the correct end state, checked against the real system, not just the model's reply.
  • Steps per task: the average and the 95th percentile. A long tail suggests loops or confusion between tools.
  • Refusal and denial rate: the share of calls blocked by permission checks. A rise can mean prompt manipulation or a tool description that invites misuse.
Tool selection accuracy on a labelled set (illustrative) (python)
def tool_selection_accuracy(cases):
    # each case has a request and the tool a person expects first
    hits = 0
    for c in cases:
        first = first_tool_call(run_agent(c["user"], c["request"]))
        hits += 1 if first == c["expected_tool"] else 0
    return hits / max(len(cases), 1)

When to use it, and when not to

SituationUse this type?Why
Answers depend on live or private dataYesTools fetch fresh facts for the right user instead of guessing.
The agent must change something, such as a bookingYes, with controlsActions need validation, permission, confirmation, and idempotency.
The facts are small, fixed, and publicNoPut them in the prompt. Tools add latency and failure points.
Steps are always the sameMaybeA fixed pipeline calling the same functions may be simpler and cheaper.
A tool can cause serious harm if misusedOnly with a personRequire approval, or keep the agent read-only.
Tools are slow or unreliableNot yetFix timeouts and error handling first, or the agent will compound the problems.
Many tools overlap in purposeNot yetMerge or rename them, or tool choice will be poor.

Trade-offs

DimensionEffectWhat to do about it
QualityAnswers are grounded in real data and can complete real tasks.Test tool choice and argument quality on labelled requests.
LatencyEach call adds a model round trip plus the tool's own time.Set timeouts, run independent calls in parallel, and cap steps.
CostMore model calls, and tool results add tokens.Trim results, keep the tool list short, and cache read-only lookups.
ComplexityNeeds schemas, permissions, confirmation, and logging.Start with a few read-only tools and add write tools one at a time.
Failure modesWrong tool, bad arguments, repeated effects, and injected instructions.Validate, check permissions in code, use idempotency keys, and treat results as untrusted.

A ReAct agent is a tool-using agent that writes a short thought before each action, so the loop is easier to follow and can adapt to results. The tool-using page covers the call-handling side: schemas, checks, and limits. In practice you combine them.

A plain model with no tools is cheaper and safer, but cannot fetch or act. A fixed pipeline of function calls is more predictable, but cannot adapt when a result is surprising. Pick the tool-using agent when the path depends on what the tools return.

What this means for your role

Common mistakes

Further reading

  • Types of AI agents: the hub page for all agent types.
  • Toolformer (Schick et al., 2023): a model learns by itself which tools (APIs) to call, when, and with which arguments.
  • ReAct (Yao et al., 2022): interleaves reasoning traces with actions such as tool calls, so the model can update its plan from what the tools return.
  • Tool calling and MCP: schemas and protocols in more detail.
  • Guardrails and safety: limits and checks around agent actions.

The model proposes, and your code decides. Keep that split clear, and a tool-using agent stays useful and safe.

Search topics

↑↓ to move · Enter to open · Esc to close