Function Calling (Tool Use) in AI Models: How the Request-Execute-Return Loop Works

Hand tools laid out, representing AI tool use and function calling

Function calling, also called tool use, is the mechanism that lets a language model ask your application to run a specific function with specific arguments. The model never executes anything itself: it returns a structured request (“call get_order_status with order_id: A-1042“), your code runs the function, and you send the result back so the model can finish its answer. Every major API (Anthropic’s Claude, OpenAI, Google Gemini) implements this same loop, with different field names.

Featured image “Woodworking hand tools on timber planks” by A S M Jobaer, licensed under CC BY-SA 4.0, via Wikimedia Commons.

This guide walks through one complete round trip with real request and response shapes, compares the field names across the three providers using their official documentation, and lists the mistakes that most often break a tool integration in production.

The four-step loop behind every tool call

Every function-calling integration repeats the same four steps, regardless of provider. OpenAI’s guide describes the flow as send tools, receive a tool call, execute it, send the output back, and receive a final answer or more calls; Anthropic and Google document the same sequence.

  1. You declare the tools. Along with the user’s message, you send a list of tool definitions. Each one has a name, a plain-language description and a JSON Schema for its arguments. JSON Schema is a standard vocabulary for describing the shape of JSON data: which fields exist, their types, which are required.
  2. The model decides. Based on the conversation and the descriptions, the model either answers directly or emits one or more structured tool calls containing the tool name and arguments.
  3. Your code executes. Your application parses the call, validates the arguments, runs the real function (a database query, an HTTP request, a calculation) and captures the output or the error.
  4. You return the result. You send a new request that contains the whole conversation so far plus the tool result, linked to the original call by an ID. The model then writes its answer, or asks for another tool.

Two consequences follow from this design. First, the model only ever sees a tool’s name, description and schema, never your implementation, so the description is the entire interface. Second, nothing happens unless your code chooses to run it, which is where you put validation, permission checks and logging.

A complete round trip, step by step

The example below uses the Claude Messages API format from Anthropic’s tool use documentation. The order-lookup tool, order number and data are invented for illustration; the field names and structure are the documented ones.

Step 1: the request with a tool definition

{
  "model": "claude-opus-5-5",
  "max_tokens": 1024,
  "tools": [
    {
      "name": "get_order_status",
      "description": "Look up the current shipping status of a customer order by its order ID. Use this whenever the user asks where an order is, when it will arrive, or whether it has shipped. Do not use it for refunds or returns.",
      "input_schema": {
        "type": "object",
        "properties": {
          "order_id": {
            "type": "string",
            "description": "Order ID in the format A-1234, exactly as the customer wrote it"
          }
        },
        "required": ["order_id"]
      }
    }
  ],
  "messages": [
    {"role": "user", "content": "Has my order A-1042 shipped yet?"}
  ]
}

Why each part is there: the name is what the model writes back when it wants the tool, so make it a clear verb-noun pair. The description says what the tool does, when to use it and when not to; Anthropic’s docs state that Claude relies on it to decide whether to call the tool. The parameter description includes the expected format, which reduces malformed arguments. required tells the model which fields it cannot omit.

Step 2: the model’s tool call

When the model decides to use the tool, the response comes back with stop_reason set to "tool_use" and a content block like this:

{
  "type": "tool_use",
  "id": "toolu_01A09q90qw90lq917835lq9",
  "name": "get_order_status",
  "input": { "order_id": "A-1042" }
}

The stop_reason is the signal your loop checks: if it is tool_use, the model is waiting on you, not finished. The response can also contain a short text block before the call, and it can contain several tool_use blocks at once when the model wants to run independent lookups in parallel.

Step 3: your code runs the function

This is ordinary application code. A minimal Python dispatcher looks like this (illustrative; lookup_order stands in for your real data access):

import re

def run_tool(name, args):
    if name == "get_order_status":
        order_id = args.get("order_id", "")
        if not re.fullmatch(r"A-\d{4}", order_id):
            return f"Invalid order_id '{order_id}'. Expected format A-1234.", True
        order = lookup_order(order_id)          # your database or API call
        if order is None:
            return f"No order found with ID {order_id}.", True
        return f"Status: {order.status}. Carrier: {order.carrier}. ETA: {order.eta}.", False
    return f"Unknown tool '{name}'.", True

Note that the function validates the argument even though a schema was supplied. The model generates arguments; your code should treat them like any other untrusted input.

Step 4: returning the result

You send the original user message, the assistant turn containing the tool_use block, and a new user turn with the result:

{
  "role": "user",
  "content": [
    {
      "type": "tool_result",
      "tool_use_id": "toolu_01A09q90qw90lq917835lq9",
      "content": "Status: shipped. Carrier: UPS. ETA: 2026-10-27."
    }
  ]
}

The model now writes a normal reply (“Yes, order A-1042 shipped with UPS and should arrive on October 27”). If the lookup had failed, you would send the error text with "is_error": true. Anthropic’s guide to handling tool calls recommends error messages that say what went wrong and what to try next, rather than a bare “failed”, and notes that Claude typically retries with corrected input a couple of times before telling the user it could not complete the request.

Same idea, different field names: Claude vs. OpenAI vs. Gemini

The concept is portable across providers, but the request and response shapes are not, so switching providers means rewriting the plumbing. The table below summarizes the current documentation for each API as of October 2026 (OpenAI’s Responses API and Google’s current Gemini function-calling guide).

ConceptClaude (Messages API)OpenAI (Responses API)Gemini API
Argument schema fieldinput_schemaparametersparameters
Model’s calltool_use content block with id, name, input (object)function_call output item with call_id, name, arguments (JSON string)function call with id, name, arguments
Your resulttool_result block with tool_use_idfunction_call_output item with call_id and outputfunction result with matching call_id
“Waiting on a tool” signalstop_reason: "tool_use"function_call items present in outputfunction call present in the response
Control modestool_choice: auto, any, tool, nonetool_choice: auto, required, a forced function, allowed_tools, noneauto, any, none, validated
Schema enforcementstrict: true on the toolstrict: true on the functionvalidated mode

One detail in that table catches people: OpenAI returns arguments as a JSON-encoded string you must parse, while Claude returns input as an already-parsed object. A deeper side-by-side, including how each provider handles JSON Schema features, is in how Claude, OpenAI, and Gemini each define function calling.

Client tools vs. provider-hosted tools

Not every tool runs in your code: providers now host some tools themselves. Anthropic’s documentation splits them into two groups:

  • Client tools run in your application. These include your own custom functions and Anthropic-defined tools such as bash, text_editor and computer, where Anthropic defines the schema but you implement the execution.
  • Server tools run on Anthropic’s infrastructure, for example web_search, web_fetch and code_execution. You add them to the tools array and the results come back in the same response, with no handler code on your side.

Google documents the same split with built-in tools such as Google Search that can be combined with custom functions in one request. The practical difference is responsibility: with a client tool you own execution, permissions and errors; with a server tool you trade control for convenience and pay any per-use fees the provider charges.

Controlling when the model calls a tool

By default the model decides on its own whether a tool is needed, and you can override that. On Claude, tool_choice accepts auto (the default), any (must call some tool), tool (must call a named tool) and none. Anthropic’s docs advise using tool_choice rather than a system-prompt instruction when a call must happen, because instructions are followed less reliably than an API-level constraint.

Forcing a specific tool is also the standard trick for structured extraction: define a tool whose schema is the JSON you want, force it, and read the arguments instead of running anything. If that is your goal, compare it with native structured output modes in choosing between Claude, OpenAI, and Gemini structured output modes.

Parallel calls are the other control. Claude, OpenAI and Gemini can all return several independent calls in one turn, which saves round trips but means your loop must execute every call and return every result. On Claude you can turn this off with disable_parallel_tool_use inside tool_choice; on OpenAI, set parallel_tool_calls to false.

What tools cost in tokens

Tool definitions are not free: they are sent as input tokens on every request. Both Anthropic and OpenAI state that tool names, descriptions and schemas count against the context window and are billed as input. Anthropic also adds a hidden tool-use system prompt whenever tools is present; its pricing table lists 286 extra tokens for auto/none and 406 for any/tool on the current Claude 5.5 models. The tool_use and tool_result blocks themselves are also billed, and each round trip resends the conversation.

For an app with a handful of tools this is small. For an app that loads 50 verbose tool definitions on every turn, it adds up fast, which is one reason providers now offer tool search features that load definitions on demand. Prompt caching can also cut the cost of a stable tool list.

Mistakes that break tool integrations, and the fix for each

Most tool-use bugs are not model problems; they are mismatches between what the API expects and what the loop sends. These are the common ones, drawn from the error conditions and best practices in the provider docs.

1. The tool result is in the wrong place

Claude requires tool_result blocks to come immediately after the assistant message that contains the matching tool_use, and they must come before any text in that user message. Putting “Here are the results:” first returns a 400 error. Fix: build the result message from the tool results alone, then append text if needed.

2. Only the first of several calls is answered

Code written as response.content[0] or “take the first function_call” silently drops parallel calls, and the next request fails because a call has no result. Fix: iterate over every call in the response and return one result per ID.

3. Vague descriptions

A description like “Gets data” gives the model nothing to choose with, so it calls the wrong tool or none. OpenAI’s best practices recommend clear names, detailed parameter descriptions and explicit guidance on when to use each function; Anthropic’s docs make the same point. Fix: write what the tool does, when to use it, when not to, and the format of each argument. A line-by-line checklist is in writing tool descriptions Claude won’t misread.

4. Asking the model for values your code already knows

If the user is logged in, do not make user_id a tool parameter; the model may guess or be talked into another user’s ID. OpenAI lists this explicitly as a best practice. Fix: inject known context (user, tenant, permissions) in your dispatcher, not through the model.

5. Too many overlapping tools

OpenAI suggests keeping the number of functions available at the start of a turn under roughly 20 as a soft guideline, and merging functions that are always called in sequence. Fix: consolidate, use enums to narrow choices, and evaluate accuracy as the tool count grows.

6. Trusting arguments and results blindly

Tool arguments are model output, and tool results often contain text from outside sources (web pages, emails, tickets) that can carry instructions aimed at the model. Fix: validate arguments, require confirmation for destructive actions, and treat returned content as data. The attack patterns are explained in prompt injection and how to defend against it.

7. Assuming the model will ask for missing information

Anthropic’s documentation notes that Claude may not always ask for a missing required parameter and can infer a value instead, especially with ambiguous prompts. Fix: make the description say “ask the user if X is not given”, and enable strict: true so at least the types and required fields always match your schema.

Function calling, agents and MCP: how they relate

Function calling is the low-level mechanism; agents and MCP are built on top of it. When you put the four-step loop in a while loop and let the model keep calling tools until it decides the task is done, you have the core of an AI agent, explained in AI agents: how autonomous AI systems work. The Model Context Protocol (MCP) is a standard way to package tools so one server can expose them to many AI applications; under the hood, the host application still presents those tools to the model as ordinary tool definitions.

A useful rule: if you are writing a single integration for one app, define tools directly. If you want the same set of tools to work in several clients, such as a desktop assistant, an IDE and your own app, MCP saves rewriting them.

A pre-launch checklist

  • Every tool has a verb-noun name, a description with when-to-use and when-not-to-use, and a format hint on each parameter.
  • Required fields are marked, enums are used wherever the set of values is known, and strict mode is on where the provider supports it.
  • The loop handles zero, one or many calls per response and returns one result per call ID.
  • Errors are returned to the model as error results with actionable text, not raised as exceptions that kill the conversation.
  • Identity and permissions come from your session, never from model-supplied arguments.
  • Destructive or costly actions (payments, deletes, outbound email) require a human confirmation step.
  • The loop has a maximum iteration count, so a confused model cannot call tools forever.
  • You log every call, its arguments and its result, so you can debug wrong tool choices later.

Sources

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top