Illustration of an AI agent selecting and calling external tools and APIs

Building Dependable Function Calling and Tool Use for AI Agents

Once a large language model is wired to internal microservices, relational databases and external application programming interfaces (APIs), it stops being a passive text generator and becomes an engine that carries out operations. Yet production agentic systems fail most often at the seam between deterministic software infrastructure and probabilistic token generation. A demo notebook may call a weather API correctly nine times out of ten, but an enterprise workflow that chains five tool calls, each 90% reliable, finishes successfully only 59% of the time (0.905).

Closing that gap means giving LLM tool calls the same defensive engineering discipline you would apply to webhooks from an untrusted third party. Polite system prompts that ask the model for valid JSON do not produce production-grade function calling. It has to be engineered, using grammar-constrained decoding, semantic schema validation, enforced idempotency, and dynamic pruning of the tool registry.

How Tool Use Fails in Production

Before building a robust tool execution harness, systems architects need a precise list of the ways an agent breaks when it works with external tools under real traffic:

  1. Syntactic Hallucinations and Broken Payloads: Ordinary autoregressive decoding chooses tokens by statistical likelihood. With no token-level constraints, a model will sometimes drop a closing brace, leave a quotation mark unescaped inside a string, or tack conversational remarks onto the end of the JSON block, and the downstream json.loads() parser then throws an unrecoverable exception.
  2. Schema Drift and Invented Arguments: Valid JSON syntax does not stop a model from making up parameter keys that do not exist (sending user_email to an endpoint that wants account_id, for example), breaking data types (a "true" string where a boolean belongs), or producing realistic-looking UUIDs that appear nowhere in the database.
  3. Colliding Tool Choices: Once an agent’s context window holds more than about fifteen to twenty tool definitions, and especially when their domains overlap, as with get_billing_history, list_recent_invoices and search_customer_orders, attention degrades and the model calls the wrong function altogether.
  4. Side Effects from Non-Idempotent Retries: Suppose an agent calls a provision_cloud_instance or create_wire_transfer tool, and the downstream API processes the request but then times out. A naive retry loop calls the tool again, and the infrastructure deployment or financial transaction happens twice.
Type of Failure Underlying Cause Mitigation in Production
Broken JSON Syntax Probability sampling with no constraints while tokens are generated Decoding driven by a Finite State Machine (FSM) or Context-Free Grammar (CFG)
Hallucinated Entity IDs The model guesses database primary keys or UUIDs that are absent from context Foreign-key lookup hooks before execution, plus strict enum binding
Mismatched Parameter Types Weak type constraints or vague JSON Schema descriptions Validation in Pydantic V2 strict mode using a custom @field_validator
Mutations Executed Twice A network timeout mid-call causes the LLM to retry automatically Deterministic idempotency keys computed from a hash of the tool and state
Context Bloat from Tool Results Raw 50KB JSON API responses are handed straight to the LLM Middleware for pagination, response projection and per-field truncation

Designing the Execution Pipeline: Constrained Decoding Through Sandboxed Execution

Removing both syntactic and semantic failures requires splitting the tool invocation lifecycle into four separate architectural stages, run in this order: Schema Compilation, then Constrained Inference, then Pre-Execution Validation, and finally Sandboxed Dispatch.

1. Syntactic Determinism Through Constrained Decoding

In production engineering, depending on prompt instructions to keep output inside a JSON schema is an outdated approach. Modern inference servers, among them vLLM, TensorRT-LLM and enterprise API providers that offer strict structured outputs, compile the supplied JSON Schema, ahead of generating any token, into either a Deterministic Finite Automaton (DFA) or a Context-Free Grammar (CFG).

On every forward pass, the inference engine checks where the DFA currently stands and applies a logit bias mask. Any token that would break the JSON Schema has its probability set to negative infinity, which becomes zero after softmax. If the schema calls for an integer field and then a closing brace, the model simply cannot sample a letter or leave the brace out.

Engineers do need to watch grammar compilation latency, though:

  • Compiling a schema into a token mask can take several hundred milliseconds when it relies on unbounded regular expression patterns or on deeply nested oneOf or anyOf unions.
  • Flatten tool parameter hierarchies wherever you can, reuse compiled grammar artifacts between requests, and do not change the schema dynamically on each turn unless you truly have to.

2. Semantic Validation and High-Signal Tool Contracts

What constrained decoding ensures the output has the shape your schema describes. Whether the values are sensible for the business is another matter. Under plain JSON Schema rules, an integer field called quantity will accept -999999 without complaint unless someone writes the semantic limits down explicitly.

When you write tool definitions, think of the validation rules and the schema’s description fields as the main interface contract the LLM works against:

from enum import Enum
from typing import Optional
from pydantic import BaseModel, Field, field_validator
import re

class CurrencyCode(str, Enum):
    USD = "USD"
    EUR = "EUR"
    GBP = "GBP"

class IssueVendorRefundInput(BaseModel):
    """Executes a verified refund against an existing settled invoice.
    Do NOT invoke this tool unless invoice_status is confirmed as 'SETTLED'."""

    invoice_id: str = Field(
        ...,
        description="Exact invoice identifier from the ERP system matching format INV-YYYY-NNNNN (e.g., INV-2026-48291). Never guess or fabricate this ID."
    )
    refund_amount: float = Field(
        ...,
        gt=0.0,
        le=10000.0,
        description="Monetary amount to refund. Must be strictly greater than 0 and cannot exceed the original invoice balance or the $10,000 automated limit."
    )
    currency: CurrencyCode = Field(
        ...,
        description="Three-letter ISO currency code matching the original invoice ledger."
    )
    reason_code: str = Field(
        ...,
        min_length=15,
        max_length=300,
        description="Detailed audit explanation referencing the specific line-item discrepancy ID."
    )

    @field_validator("invoice_id")
    @classmethod
    def validate_invoice_format(cls, v: str) -> str:
        if not re.match(r"^INV-\d{4}-\d{5}$", v):
            raise ValueError(
                f"Invalid invoice_id '{v}'. Expected format 'INV-YYYY-NNNNN'. "
                "Call 'lookup_vendor_invoices' first to retrieve the exact ID."
            )
        return v

The IssueVendorRefundInput contract above shows three important engineering patterns:

  • Negative Constraints in Descriptions: Both the docstring and the field descriptions spell out when the model should not use the tool, and they prohibit guessing identifiers.
  • Grounding with Enums: Binding currency to a strict Enum rather than accepting any string makes the grammar compiler limit token choice to "USD", "EUR" or "GBP" and nothing else.
  • Validation Errors the Agent Can Act On: If validate_invoice_format fails, the ValueError it raises says more than "Regex mismatch". It explains why validation failed and names the exact tool (lookup_vendor_invoices) that will supply the missing information.

Self-Healing Tool Loops with Structured Error Feedback

A tool call can fail because of a Pydantic ValidationError, an HTTP 422 Unprocessable Entity returned by a downstream microservice, or database lock contention. In none of these cases is it acceptable for the whole agent workflow to go down. The tool execution harness should catch the exception and convert it into a compact, structured observation that steers the model toward correcting itself.

Building a Correction Harness with Limits

In production, a tool executor runs every function call through a deterministic middleware layer:

  1. Intercepting Validation Failures: When the arguments the model produced do not pass Pydantic validation, the harness catches the ValidationError, removes the verbose internal Python file paths, and writes back to the tool role message only the field path, the bad value and the instructional error text.
  2. Translating Downstream HTTP Errors: The LLM context window is no place for 200-line Java stack traces or raw HTML 502 Bad Gateway pages coming back from internal services. When an internal API answers with HTTP 503 (Service Unavailable) or 429 (Rate Limit Exceeded), the Python harness should quietly run exponential backoff with jitter at the infrastructure level, without involving the LLM at all. Pass an error to the LLM only when fixing it takes reasoning, such as an HTTP 404 Record Not Found or an HTTP 400 Invalid Date Range.
  3. Breaking the Circuit After Repeated Failures: Keep an error counter per tool, (tool_name, error_type), in the workflow state. When the agent hits the identical validation error two times running, stop the retry loop at once. Letting an LLM retry a broken tool five times burns thousands of tokens and makes context pollution worse.

Handling Large Tool Registries with Dynamic Routing and Pruning

An enterprise platform may offer hundreds of internal API endpoints spread across ticketing, deployment, ERP and CRM systems. Loading 150 JSON Schema definitions into every LLM call’s system prompt leads to three serious problems:

  • Every turn spends 15,000 to 30,000 input tokens before the user has said anything.
  • Latency to the first token (TTFT) goes up.
  • Tool selection becomes less accurate as attention is spread across similar schemas.

A Two-Stage Dynamic Tool Router keeps tool selection accuracy above 99% even over large API catalogs:

  • Stage 1: Top-K Pruning via Semantic Tool Retrieval: Keep an in-memory index of vector embeddings built from each tool’s name, short description and example queries that should select it. For each incoming task, run a hybrid search (dense embedding plus BM25 keyword) over the registry in under 10ms, pull back only the handful of best-matching tool schemas (5 to 8), and attach just those to the inference request.
  • Stage 2: Tool Binding Scoped by the State Machine: In workflows with many steps, choose which tools to bind from the lifecycle’s current state. In the VERIFICATION phase of an incident response workflow, for instance, expose only read-only diagnostic tools (query_prometheus_metrics, fetch_pod_logs). The orchestrator should add mutating tools such as rollback_helm_release and restart_deployment to the model’s active list only once the state has moved to REMEDIATION_APPROVED.

Idempotency, Timeouts and Output Sanitization

A correct tool choice with valid arguments is still not enough. The execution layer has to shield the downstream enterprise systems as well as the LLM context window upstream.

Making Mutating Tool Calls Idempotent

Any time an agent calls a tool that changes state, such as updating an inventory count, opening a Jira ticket or charging a card, the execution harness should add a deterministic Idempotency-Key header to the outgoing API request on its own.

Never leave idempotency key generation to the LLM; models are very poor at producing hashes that are deterministic or unique in a hash-based sense. Compute the key in your TypeScript or Python middleware instead: take the canonicalized JSON arguments together with tool_name, step_index and workflow_run_id, and hash them with SHA-256:

IdempotencyKey = SHA256(run_id || step_id || tool_name || canonical_json(args))

When a brief network glitch makes the orchestrator replay the step, the downstream API gateway sees the same SHA-256 signature and hands back the cached result from the first execution, so the side effect is not repeated.

Projecting Output and Protecting the Context Window

Enterprise GraphQL and REST APIs often send back oversized payloads full of nested relational objects, audit histories, base64-encoded thumbnails and hundreds of metadata fields. Feeding a raw 40KB JSON payload into the tool message sends token costs soaring right away and crowds important system instructions out of the range the model actually attends to.

Every raw API response should pass through a Response Sanitization Filter before it reaches the agent’s context window:

  1. Field Allowlisting (Projection): Reduce the response to just the fields the agent needs, with a JMESPath query or a response model in Pydantic.
  2. Pagination and Truncation: When a database query tool comes back with 500 rows, send the LLM only the first 10 and add a metadata note: {"showing_rows": "1-10 of 500", "instruction": "Refine your search filters if the target record is not listed."}
  3. Offloading Artifacts: When a tool downloads a document or produces a large dataset, save the raw payload under a Redis key or in an external object store and give the agent only a small reference handle, such as dataset_ref: "redis://tmp/query_8821". Downstream analysis or code-execution tools can then read the data by reference, and megabytes never have to pass through LLM tokens.

Common Questions (FAQs)

1. What separates constrained decoding from the plain JSON mode offered by LLM APIs?

Plain JSON mode only ensures the model emits some valid JSON object (even {}), so required fields can still be missing, types can be wrong and keys can be invented. With constrained decoding (Strict Structured Outputs), your exact JSON Schema becomes a context-free grammar mask applied at the token sampler, which means every enum constraint, nested object structure and required key in the schema is strictly respected while the output is generated.

2. How many tools should one agent have bound at the same time, at most?

Empirical benchmarks on frontier models show argument precision and tool selection accuracy starting to fall off noticeably once more than 12 to 15 different function schemas are bound together. If your application needs dozens of tools, either divide them among specialized domain worker agents or use a semantic tool router that filters dynamically and binds just the 5 to 8 most relevant tools for each turn.

3. Should an agent be permitted to write raw SQL inside a tool call?

Giving an agent the ability to send arbitrary raw SQL to a production database creates a high-severity reliability and security risk even with read-only credentials, both because of expensive full-table scans and because of prompt manipulation paths. Where you can, offer parameterized domain tools such as get_orders_by_date_range(start_date, end_date, status) backed by indexed SQL templates compiled in advance. Where text-to-SQL cannot be avoided, check the generated query with an AST (abstract syntax tree) validator such as sqlglot before execution, and reject system catalog reads, unauthorized joins and missing LIMIT clauses.

4. How can parallel tool calls be handled safely when some tools depend on others?

Modern LLMs are able to produce several tool calls in one turn (parallel function calling). For independent reads, such as pulling a user’s support tickets, recent orders and profile at once, this cuts latency sharply, but it falls apart when Tool B needs Tool A’s output. Where steps must run in sequence, either turn off parallel tool calling (parallel_tool_calls=False) for that node or merge the dependent read-then-mutate steps into one atomic composite tool in your backend code.

5. What can engineering teams do about indirect prompt manipulation that arrives through tool outputs?

When a tool pulls in untrusted external data, for example by reading an inbound customer email, scraping a web page or querying public social media posts, instructions hidden in that data may try to take over the agent’s next tool call. Reduce the risk by stripping control characters, wrapping untrusted tool output in explicit XML boundary delimiters, and applying an orchestrator-level security policy that prevents any high-privilege mutation tool from running straight after an untrusted external retrieval unless a deterministic validator or a human approval gate clears it first.

Technical Sources and References

  1. Structured Outputs and Context-Free Grammars (OpenAI Platform docs): Describes the architecture that converts JSON Schemas into context-free grammars so token sampling stays deterministic during function calling. ([https://platform.openai.com/docs/guides/structured-outputs](https://platform.openai.com/docs/guides/structured-outputs))
  2. Validators and Strict Mode Serialization (official Pydantic V2 docs): An engineering reference on custom field validation hooks and fast, Rust-backed schema validators in Python. ([https://docs.pydantic.dev/latest/concepts/validators/](https://docs.pydantic.dev/latest/concepts/validators/))
  3. Draft 2020-12 of the JSON Schema Specification: The core specification used to define, validate and annotate JSON data structures in distributed software systems. ([https://json-schema.org/specification](https://json-schema.org/specification))
  4. Gorilla Project at UC Berkeley (LLMs Connected with Massive APIs): Academic research and benchmarks, including the Berkeley Function-Calling Leaderboard, that measure hallucination rates, AST evaluation and tool selection accuracy over very large API registries. ([https://gorilla.cs.berkeley.edu/](https://gorilla.cs.berkeley.edu/))
  5. The Idempotency-Key HTTP Header Field (IETF draft): A standard architectural specification for avoiding duplicate state mutations over unreliable networks and in automated retry pipelines. ([https://datatracker.ietf.org/doc/html/draft-ietf-httpapi-idempotency-key-header](https://datatracker.ietf.org/doc/html/draft-ietf-httpapi-idempotency-key-header))

Similar Posts