Agents Guide 10 of 25

Tool use and function calling: how AI models take actions

A model can only write text. Tool use is the contract that turns that text into a database query, a refund, or an email — and your code decides whether it ever runs.

  • 9 min read
  • Updated 
  • 8 sources

Key takeaways

  • The model never runs a tool. For functions you define, it proposes a call; your code validates, authorizes, executes, and returns the result. Control and safety live there.
  • Tool definitions are prompts. Clear names, detailed descriptions, enums, and compact, human-readable results can deliver large accuracy gains on their own.
  • Strict schemas guarantee a call’s shape, not its correctness. Check amounts, ownership, and business rules inside the tool itself.
  • Large tool libraries cost context and accuracy. Keep the starting set small, defer the rest with tool search, and use code-based orchestration for heavy multi-step work.
  • Treat every tool result as untrusted input. Never give one agent private data, untrusted content, and an outbound channel without a hard check.
On this page 7 sections

A tool call can be perfectly formed and still refund the wrong order. Getting a large language model (LLM) to request an action in valid JSON (JavaScript Object Notation) is now the easy part. The engineering is deciding which actions it may request, and checking them before they run. Tool use, also called function calling, is the contract: you describe functions, the model asks to call one, and your code decides whether to run it.

Almost every AI agent is built on this mechanism. So are many assistants that look something up before answering, and many extraction pipelines that need clean JSON. If the model supplies the judgment, tools are its hands, and much of the real engineering in an agent goes into shaping those hands.

That engineering has moved on. As of October 2026, getting a model to emit schema-valid arguments is largely solved. The hard problems are choosing and describing tools well, keeping hundreds of tool definitions from crowding out the actual task, and making sure a malicious web page cannot talk an agent into moving money.

How does function calling actually work?

OpenAI’s function calling guide describes a five-step loop. You send a request that includes tool definitions. The model replies with a tool call; your application executes it and sends the output back; the model then answers or asks for more calls.

Each tool definition has three parts: a name, a plain-language description, and a JSON Schema for the arguments. The provider places these definitions in the model’s context, so they take up room and are charged as input tokens on every request. When the model judges that a tool would help, it emits a tool name plus arguments as structured data instead of a final answer.

Stripped of vendor-specific details, the application side looks like this:

def run_agent(user_message, current_user, max_steps=10):
    messages = [user_message]
    # Never loop forever.
    for _ in range(max_steps):
        reply = model.generate(
            messages, tools=TOOL_DEFINITIONS)
        messages.append(reply)
        if not reply.tool_calls:
            # The model answered in prose.
            return reply.text
        for call in reply.tool_calls:
            args = validate_schema(
                call.name, call.arguments)
            # Your policy, not the model's.
            authorize(current_user, call.name, args)
            # Your code does the work.
            result = TOOLS[call.name](**args)
            messages.append(tool_result(call.id, result))
    raise StepLimitExceeded(max_steps)

Notice what the model does not do: execute anything. It proposes; your code disposes. Validation, permissions, retries, rate limits, and audit logs all sit on your side of that boundary, which is exactly where they belong. Provider-hosted tools, such as OpenAI’s built-in web search and code execution, are the exception: the vendor runs those calls, so that control moves outside your code.

Two settings matter in practice. A tool-choice parameter lets you leave the decision to the model, require at least one call, force a specific tool, or switch tools off for a turn. Models can also request several independent calls at once — say, three customer lookups — which saves round trips but means your executor must handle a batch of calls in a single reply.

From Toolformer to strict schemas: how tool use matured

The research came before the product. In February 2023, Meta AI Research’s Toolformer showed that a 6.7-billion-parameter model could largely teach itself when to call five tools, including a calculator, a search engine, and a calendar. Starting from a few examples per tool, it sampled candidate calls in ordinary text, ran them, and kept only those whose results made the following words easier to predict. On fact-completion and math benchmarks it beat GPT-3, a 175-billion-parameter model, though it trailed GPT-3 on open-domain questions and could not chain one tool’s output into another.

Four months later, on 13 June 2023, OpenAI shipped function calling in its application programming interface (API). Two new model snapshots, gpt-3.5-turbo-0613 and gpt-4-0613, had been fine-tuned to spot when a described function was needed and to reply with JSON matching its signature. The same post warned that a tool’s output could smuggle in instructions the model might follow. It recommended confirmation steps before real-world actions such as emailing, posting, or buying.

Early function calling was best effort: nothing guaranteed that the arguments matched the schema. On 6 August 2024, OpenAI introduced Structured Outputs, which uses constrained decoding: at each step, any token that would break the schema is masked out. Our guide to prompts in production covers the fine print, from refusals and truncation to partial schema support.

OpenAI’s current guide recommends turning on strict mode for every function. The format problem is largely solved. The judgment problem — which tool, which arguments, when to stop — is not.

What makes a good tool?

A tool definition is a prompt. The model knows nothing about your refund function beyond its name, description, and schema. In its September 2025 guide to writing tools, Anthropic reported that precise edits to tool descriptions helped Claude 3.5 Sonnet reach what was then a state-of-the-art score on SWE-bench Verified, a coding benchmark. OpenAI’s guide proposes a simple bar: could an intern use the function correctly with only what the model sees?

The bigger shift is designing tools for an agent instead of mirroring your API. Endpoints serve programs that already know exactly what they want. An agent behaves more like a new colleague exploring an unfamiliar system, and it pays for every byte it reads.

Design choiceEndpoint-shaped toolAgent-shaped tool
Scopelist_contacts returns everyonesearch_contacts(query) returns matches
GranularitySeparate calls to check availability and bookOne schedule_event that finds a slot and books it
IdentifiersOpaque internal IDsReadable names; raw IDs only where a later call needs them
Output sizeFull records every timeConcise by default, detailed on request
Errors400 Bad RequestWhat went wrong and how to fix the call
Namessearch, sendcrm_search_contacts, slack_send_message

Most of the right-hand column comes from Anthropic’s guide. Its team found that resolving cryptic IDs into meaningful names noticeably improved retrieval precision. At the time, Claude Code capped tool responses at 25,000 tokens by default, and a concise Slack response used 72 tokens where the detailed version used 206.

Two habits from OpenAI’s guide complete the picture. First, use enums and structure so invalid states cannot be expressed; a light switch with separate on and off booleans invites contradictions. Second, never ask the model for an argument your code already has. If the session already holds the order ID, the refund tool should read it from there.

Where does tool calling break?

Knowing the failure modes tells you what to test.

Wrong tool, wrong arguments. Anthropic’s November 2025 write-up names these as the most common failures with large tool libraries, especially between near-twin tools such as one that notifies a user and one that notifies a channel. A schema checks types, not intent. A strict-mode call can be flawless JSON and still refund the wrong order.

Too many tools. Definitions are not free. In the same post, Anthropic counted 58 tools from five Model Context Protocol (MCP) servers, including GitHub and Slack, consuming about 55,000 tokens before a conversation began. Internally, it had seen tool definitions alone reach 134,000 tokens before optimization. OpenAI suggests that fewer than 20 functions be visible when a turn begins, and calls even that a soft rule.

Long, stateful tasks. The Berkeley Function Calling Leaderboard paper, presented at the International Conference on Machine Learning (ICML) in 2025, found that leading models handle single-turn calls well. Carrying memory across turns, adjusting decisions as results arrive, and planning over long horizons remained open problems. The benchmark also tests abstention: noticing that no tool fits, or that a required detail is missing.

Bloated results. A tool that dumps 10,000 log lines does more than cost money. It can bury the original instructions and leaves less room for the rest of the task.

How do you scale past a handful of tools?

Three techniques have emerged for large tool libraries. Anthropic described all three, with internal measurements, in its November 2025 post.

  1. Tool search. Mark most tools as deferred and give the model a search tool that loads definitions on demand; in Anthropic’s example, upfront context fell from about 77,000 tokens to roughly 8,700. On its MCP evaluations, Claude Opus 4 rose from 49% to 74% accuracy and Opus 4.5 from 79.5% to 88.1%. As of October 2026, OpenAI supports tool search on gpt-5.4 and later models.
  2. Programmatic tool calling. Rather than one call per model turn, the model writes a short script that runs in a sandbox and calls many tools. Bulky intermediate data never enters the model’s context; the model sees only the script’s result. Anthropic measured average usage falling from 43,588 to 27,297 tokens on complex research tasks, with far fewer inference round trips.
  3. Tool use examples. Attach a few sample calls to a complex tool to show conventions a schema cannot express, such as date formats or which optional fields travel together. Anthropic saw accuracy on complex parameter handling rise from 72% to 90%.

These are vendor numbers on vendor tests, so read them as direction rather than promise. Programmatic calling also adds moving parts: model-written code needs an isolated sandbox, whether the vendor hosts it or you do, and each tool it calls still needs your authorization checks. Reach for it when multi-step data wrangling is the bottleneck, not by default.

Why is tool use a security boundary?

Once a model can act, prompt injection stops being an embarrassment and becomes an incident. Models cannot reliably separate your instructions from instructions hidden in a web page, an email, or a support ticket they were asked to read. OpenAI flagged exactly this risk in its 2023 launch post.

Simon Willison’s “lethal trifecta”, from June 2025, is a useful way to reason about it. Danger peaks when one agent can read private data, ingest untrusted content, and communicate externally. Willison’s advice is to avoid that combination rather than trust filters to catch every attack. Mix-and-match tool ecosystems such as MCP make it easy to assemble all three by accident.

The defenses are architectural, not prompt-based:

  • Authorize inside the tool. Run each call with the end user’s permissions and narrowly scoped credentials, never a shared admin key.
  • Gate irreversible actions. Payments, deletions, external messages, and production changes need human confirmation or a deterministic policy check.
  • Break the trifecta. If an agent reads untrusted content, remove or tightly allowlist its outbound channels for that session.
  • Make tools safe to retry. Idempotency keys make a duplicated call harmless, and a dry-run mode lets a risky call be previewed before it commits.
  • Log every call. Record the arguments, the result, and the user it ran for, so any incident can be reconstructed.

What this means for your team

Function calling itself is mature plumbing; reliability now comes from tool design, evaluation, and controls. A practical sequence:

  1. Start from tasks, not endpoints. List the jobs the agent must do, then build the fewest tools that cover them. Resist generating one tool per API route.
  2. Write descriptions like onboarding docs. Say what the tool does, when not to use it, what each parameter means, and what comes back. Then run the intern test.
  3. Turn on strict schemas, then validate meaning. Check amounts, ownership, and business rules in the tool. Schema-valid is not the same as correct.
  4. Budget context explicitly. Measure tokens spent on definitions and results. Paginate, truncate with guidance, and defer rarely used tools once the starting set passes about 20.
  5. Evaluate on realistic multi-step tasks. Score tool selection, argument accuracy, and end-to-end success, and read the transcripts. Rerun the suite whenever the model or a tool changes.
  6. Treat every tool result as untrusted input. Assume the model will eventually be talked into something, and scope permissions so a hijacked call does limited damage.

One test is worth running before launch. For each tool, ask what happens if the model calls it with the worst plausible arguments at the worst possible moment. If the answer is unacceptable, the fix belongs in the tool, not the prompt.

If your team is wiring an agent into systems that move money or customer data, start with the tool layer — it is the kind of work we do at SurgeX Labs.

Sources

  1. Toolformer: Language Models Can Teach Themselves to Use Tools (opens in new tab) — Meta AI Research (arXiv), 2023 arxiv.org

  2. Function calling and other API updates (opens in new tab) — OpenAI, 2023 openai.com

  3. Introducing Structured Outputs in the API (opens in new tab) — OpenAI, 2024 openai.com

  4. Function calling (API guide) (opens in new tab) — OpenAI, 2026 developers.openai.com

  5. Writing effective tools for agents — with agents (opens in new tab) — Anthropic Engineering, 2025 anthropic.com

  6. Introducing advanced tool use on the Claude Developer Platform (opens in new tab) — Anthropic Engineering, 2025 anthropic.com

  7. The Berkeley Function Calling Leaderboard (BFCL): From Tool Use to Agentic Evaluation of Large Language Models (opens in new tab) — UC Berkeley (ICML 2025, PMLR), 2025 proceedings.mlr.press

  8. The lethal trifecta for AI agents: private data, untrusted content, and external communication (opens in new tab) — Simon Willison, 2025 simonwillison.net

Where this shows up in our work

Building this? Talk to an engineer.

If this guide maps to a system you’re planning, send a short brief. A senior engineer replies within one business day.