AI Agents, Evergreen

How Autonomous Agents Perform Tool Selection and API Calling Reliably

Cartoon robot puzzled before a wall of tools, reaching for an oversized wrench while the correct tool is highlighted, with the headline Why Agents Pick Wrong Tools

Agent tool selection reliability is the difference between an agent that usually works and one you can put in front of users. The basic mechanism is straightforward: the model emits a structured request naming a tool and its arguments, your code runs the tool, and the result goes back to the model. Reliability lives in everything around that loop — choosing the right tool among similar ones, checking the call before it runs, handling errors, and knowing when to stop.

What reliable tool selection means

A tool call is a decision the model makes from the information you gave it. A tool is described to the model as a name, a natural-language description, and a JSON parameter schema, and the model sees only that description and schema — never your implementation. It emits a structured request, or answers directly when no tool is needed. Your code executes the request and returns the result, matched to the call by an identifier: a tool_call_id in OpenAI’s Chat Completions API, a tool_use id in Anthropic’s API, or an id or positional match in Gemini’s function calling.

A reliable agent meets four tests on each turn. It picks the right tool, fills in valid arguments, returns a result the agent can act on even when the tool fails, and stops cleanly instead of looping. Failures fall into recognisable groups — the wrong tool, malformed arguments, an unparseable output, an error swallowed as success, or a loop with no stop condition — and each group has a different fix, most of them in your code and tool definitions rather than in the model.

How the model chooses a tool

Cartoon robot choosing one tool description card marked with a green check from a row of symbol cards

Selection starts with what the model is shown. On every turn you send the conversation plus the tool definitions, and the model decides from the names, descriptions, and schemas whether a tool is needed and which one. That is why the description does most of the work: it is the model’s only documentation for the function, and a vague description produces flaky routing between similar tools.

You can also control how hard the model must use tools. Tool-choice controls let you leave the decision to the model, require at least one tool call, force a specific tool, or forbid tool calls on a turn — for example, a final turn that only composes an answer from results already returned. The exact mode names differ across vendors, so check the documentation for the API you are calling rather than assuming one vendor’s names work on another. Force a tool when the next step is already known; leave the choice automatic for open-ended assistance.

Parallel and sequential calling are part of the same decision. When several independent actions are needed — checking the weather in two cities, for example — the model can emit multiple calls in one turn and your code can run them together. When one call’s output feeds the next, the calls must be sequential. OpenAI provides parallel_tool_calls=false to serialize calls when ordering matters. Gemini requires that when the model returns multiple functionCall parts in a single response, all corresponding functionResponse parts are returned together in a single content object in the next turn, matched by id or by order. A result attached to the wrong call teaches the model the wrong lesson.

Designing tools so they can be selected correctly

Good selection is designed before any call is made. Anthropic’s tool-definition guidance puts it bluntly: “Provide extremely detailed descriptions. This is by far the most important factor in tool performance.” A description should explain what the tool does, when to use it, when not to use it, what data it returns, and what each parameter means. If two tools overlap, say so in each description and name the deciding factor — the data source, the freshness, or the side effect — so the model does not have to guess.

The schema is the second half of the design. Tight schemas rule out whole classes of bad arguments: mark required fields as required, use enums for closed sets of values, and give every parameter a clear type and description. A permissive schema invites invented arguments; a tight schema makes a bad call visible before anything runs. OpenAI calls the schema parameters, Anthropic input_schema, Gemini function declarations, and MCP inputSchema; the discipline is the same.

Example tool definition — the fields the model reads only:

{
  "name": "get_order_status",
  "description": "Look up the current status of one customer order by its order ID. Use this when the user asks where an order is or whether it has shipped. Do not use it to search for orders by customer name or email; use search_orders for that. Returns the order status, tracking number, and expected delivery date.",
  "parameters": {
    "type": "object",
    "properties": {
      "order_id": {
        "type": "string",
        "description": "The order ID, for example ORD-1042. It always starts with ORD- followed by digits."
      }
    },
    "required": ["order_id"],
    "additionalProperties": false
  }
}

Finally, keep the active tool set small. Every tool you add is another option the model must weigh on every turn. When a catalogue grows, group related operations behind a router or narrow the set offered on each turn to the tools that step can plausibly need. Gemini’s documentation allows up to 512 function declarations in a single request; that is an upper bound, not a target. A dozen well-described tools with distinct purposes will be selected more reliably than a hundred overlapping ones.

Validating and parsing tool calls before execution

Cartoon robot checking a tool-call card against a checklist at a checkpoint gate before it reaches a machine

Never execute a tool call you have not checked. Validation is the gate between the model’s output and your systems: parse the structured call, check the tool name against the tools you actually registered, and validate the arguments against the schema before running anything. An unknown tool, a missing required argument, or a wrong-typed value is a generation error: reject it safely, with no side effects.

Strict modes help at this gate. With OpenAI’s Structured Outputs turned on, the arguments generated by the model for function calls are guaranteed to match the JSON Schema you provide. That removes a large class of malformed-argument failures, but it does not remove the gate: strict modes constrain the shape of the arguments, not whether the chosen tool is right, whether a value exists in your system, or whether the call is safe. Always validate again in your own code, and treat a validation failure as information for the model rather than as a crash.

When validation fails, return a precise, machine-usable error to the model. Name the problem, the field or tool involved, and what a valid call would look like. A vague “failed” teaches the model nothing and invites it to repeat the same call; a specific error gives it something it can correct. In Anthropic’s API, results are returned as tool_result blocks carrying the matching tool_use id, with an is_error flag set to true when the tool failed or the call was invalid, and every tool_use block must be answered by a tool_result block. The same principle applies on every vendor’s API: every call gets a result, including failed ones, and failed results must be marked as failures rather than returned as empty successes.

Validation fragment — not a complete program; client setup and execution omitted:

# Fragment: validate a tool call before executing it.
# tool_call carries the model-chosen name and arguments;
# TOOLS maps registered names to their JSON Schemas.
if tool_call.name not in TOOLS:
    result = error_result("Unknown tool: " + tool_call.name)
else:
    errors = validate_against_schema(tool_call.arguments, TOOLS[tool_call.name])
    if errors:
        result = error_result("Invalid arguments for " + tool_call.name + ": " + "; ".join(errors))
    else:
        result = execute_tool(tool_call)

Handling API and execution errors reliably

Errors come in four kinds, and each needs a different response. Generation errors are malformed calls, handled at the validation gate. API errors — rate limits, timeouts, service errors — hit the call to the model provider itself. Tool execution errors happen inside the tool: a downstream API error, a missing record, a denied permission. Timeouts are their own kind, because a timed-out call may still have completed.

Tool-call recovery uses the same loop: when a tool call was actually made and returned an error, feed that error back as the tool’s result and let the model correct its arguments, try a different tool, re-plan, or stop and tell the user what happened. That only works if errors are honest and specific — what went wrong, whether retrying could help, and what to do instead, naming the parameter or tool. Remove stack traces and internal details, and never return an empty success when something failed.

Provider-request failures are handled differently, in your own code, because they may produce no tool call to attach a result to. When a request to the model provider fails or times out, apply bounded application-side handling: back off and retry the request a limited number of times, and if it still fails, stop the run and report that the provider request failed rather than presenting it as a tool result. Do not invent a tool result for a call that never happened.

Retries need guardrails of their own. Set a hard cap on loop iterations and on retries per tool, back off between attempts, and give every attempt a timeout. Make retries safe to repeat: reads generally avoid duplicate write effects, but a retry is still bounded — capped, backed off, timed out, and attempted only for a failure that retrying could plausibly fix — while an action that creates, charges, or sends something must be idempotent or guarded so a retry does not repeat the side effect. Distinguish errors worth retrying — a transient downstream failure — from errors that will fail the same way every time, such as a missing record or a permission denial. When the cap is reached, stop and report the state honestly, including what did and did not happen.

MCP tools follow the same pattern with one extra step: discovery. A client lists the tools a server exposes with tools/list and invokes them with tools/call, and the tools are model-controlled — the model discovers and invokes them from their name, description, and input schema, just as with native function definitions. Validate MCP calls the same way, and treat a failed tools/call as a result the model needs to see, not a silence to paper over.

Testing and measuring agent tool selection reliability

Reliability that is not measured is assumed, and assumed reliability is how flaky agents ship. Build test cases from the failure groups: overlapping tools where the wrong choice is tempting, ambiguous requests that admit two readings, invalid arguments the model might plausibly emit, and tools that fail — a downstream API down, a record missing, a timeout. For each case, write down the expected behaviour first: the right tool, valid arguments, a recovery attempt, or a clean stop.

Log everything the loop does: the tool chosen, the arguments sent, the result returned, whether the result was an error, and how many turns the task took. When a failure appears in production, the log should let you replay the exact sequence of calls and see where the decision went wrong — the description that misled the model, the schema that allowed a bad value, or the error that was swallowed.

Measure what matters: how often the right tool is chosen, how often arguments pass validation first time, how often the agent recovers after an error, and how many turns tasks take. The ReAct paper reported absolute success-rate gains of 34% on ALFWorld and 10% on WebShop over imitation and reinforcement learning baselines with only one or two in-context examples — evidence that observing tool results and reasoning about them helps on those tasks, not a promise about your agent. Your own measurements decide whether a change helped.

Reliability checklist and common mistakes

Before an agent goes live, check each item in this list. Descriptions state what each tool does, when to use it, when not to use it, and what it returns. Schemas are tight, with required fields and enums where values are closed. Every call is validated against its schema before execution, and unknown tools are rejected without side effects. Every call gets a result, errors are marked as errors, and error messages say what went wrong and what to do instead. Retries are capped, backed off, and safe to repeat, and the loop has a hard stop. Parallel calls are used only for independent actions, and results are matched to the calls that produced them. Finally, calls, arguments, results, and retries are logged so failures can be traced.

The common mistakes are the inverses of that list: vague descriptions that leave the model guessing between overlapping tools; schemas that accept anything; executing unvalidated calls; swallowing errors and returning empty successes; retrying without a cap until the loop runs away; and treating a vendor’s upper limit on tool counts as a design target. When an agent is unreliable, simplify first: fewer tools, clearer boundaries, a human step for actions that must not be retried. Reliable tool selection is mostly unglamorous work — clear descriptions, strict schemas, honest errors, and bounded loops — done before the model is ever asked to choose.