Why Large Language Models Can Call Tools: Mechanisms and Optimization

    This article explains how tool calling actually works in large language models and why newer models sometimes generate invalid tool calls on unfamiliar schemas. It breaks down in-band signalling, the four-step request pipeline, and three overlapping causes of schema violations, then offers practical engineering fixes such as constrained decoding, narrow schema design, actionable error feedback, defensive normalization, layered evaluation, and observability. The goal is to turn tool-calling reliability into a measurable, repeatable system capability rather than a matter of luck.

    1. It Started With a Counterintuitive Observation

    Many developers working on AI Agent engineering have recently run into something that seems backwards: a new generation of general-purpose large models has clearly improved at reasoning, yet when connected to in-house or third-party-style editing tools, it produces more non-compliant calls, not fewer.

    The pattern looks like this: when the model calls a “batch text replacement” tool, the replacement content is usually correct and the path is mostly right, but it invents several fields that do not exist and appends them to the end of the parameter object. The tool’s parameter validation layer then rejects the payload as invalid and asks for a retry. What is more telling is that this mainly happens on the latest flagship models, while the previous generation almost never does it.

    This is worth digging into because it exposes a fact that is easy to overlook: a model that “can call tools” does not necessarily “understand your interface.” It behaves more like a highly skilled format imitator, and what it imitates, in what style, and with how much tolerance depends on the tool ecosystem it saw during training and alignment.

    2. What Tool Calling Really Is: Text Generation With In-Band Signals

    To understand the observation above, you first need a key insight: tool calling is not magic, and the model does not actually execute a function internally. It relies on a fairly primitive but extremely effective mechanism called in-band signalling.

    For a request with tools, the server typically assembles one large prompt containing three parts:

    • Conversation history (transcript): the prior turns between the user and the assistant;
    • System prompt: role definition, behavioral constraints, and output style;
    • Tool schema: each tool’s name, description, and parameter schema.

    Once serialized, the tool definitions are usually embedded in the prompt as structured text, and special markers are used during generation to distinguish a “tool call” from ordinary text. Because models saw large amounts of such samples during pre-training and post-training, they learned to emit marked content at the right moment, semantically equivalent to “I want to call this tool with these arguments.”

    A representative payload looks like this:

    1. {
    2. "path": "src/utils/text.py",
    3. "edits": [
    4. { "oldText": "old value", "newText": "new value" }
    5. ]
    6. }

    What the model actually emits internally may be a span of text wrapped in special markers, which the client then parses back into a structured object. The specific markers and serialization formats differ across vendors and are not public, so the community can only infer the general shape from the output.

    The whole path can be summarized in four steps:

    1. Assembly: combine history, system prompt, and tool schemas into a single prompt;
    2. Generation: the model autoregressively produces marked text;
    3. Parsing and validation: the host program (harness) parses the payload and validates it against the schema;
    4. Feedback: the execution result or error message is appended to the history as a new observation for the next turn.

    Once you understand these four steps, it becomes clear that a “non-compliant call” is not the model getting dumber. It is a mismatch between the generation distribution and the strictness of validation.

    3. Why Newer Models Are More Likely to Add Extra Fields

    Abstract the problem one level up and you get three overlapping causes.

    First, ecological bias in the training distribution. When a model is heavily optimized on a particular built-in tool ecosystem, what it sees is that ecosystem’s specific calling style: field naming conventions, optional parameters, fault-tolerance strategies, and even some redundant keys that are tolerated. The model internalizes these statistical regularities as priors, so once it moves to a schema with a different style and stricter constraints, it “habitually” writes a few extra fields.

    Second, over-expression driven by stronger capability. A more capable model tends to express intent more completely and more “safely,” adding information it thinks might be useful when uncertain. In natural language this is a strength, but under strict schema validation, an extra key is a fatal error.

    Third, differences in validation strictness. A lenient harness trims fields, maps aliases, or fills in defaults before validation, “rescuing” a non-compliant payload; a strict harness rejects it outright. The same model output can have very different success rates across harnesses. This means evaluation conclusions depend heavily on the tool ecosystem, not purely on model capability.

    It is worth stressing that this article does not evaluate any specific product; it only discusses general mechanisms. The more robust engineering conclusion is that tool-calling stability is a system property determined jointly by the model, the prompt, the schema design, and the validation strategy.

    4. Making It Reliable: Practical Engineering Steps

    1. Replace “Praying After the Fact” With Constrained Decoding

    If the inference side supports structured output or schema-constrained decoding, enable it first, so that non-compliant tokens are blocked during sampling. This is the most effective way to eliminate extra fields at the source, and it is more reliable than any prompt trick.

    2. Keep the Schema Narrow and Clear

    • Use as few fields as possible, with names that map one-to-one to their meaning;
    • Mark required and optional fields explicitly, and avoid a large set of options that invites the model to improvise;
    • Provide a short example for complex structures; the example itself is the strongest constraint;
    • Version the schema, and update the prompt and evaluation set whenever it changes.

    3. Feed Back Actionable Correction Signals on Validation Failure

    The error message should not just say “invalid parameter.” It should point to the specific path and expected type so the model can make a targeted fix on the next turn:

    1. Parameter validation failed: edits[0] contains an undefined field "contextLines".
    2. Only these fields are allowed: oldText, newText. Please output only JSON that conforms to the schema.

    Combined with a fallback of “retry at most N times, then degrade to a full-file write,” this can significantly reduce the failure rate.

    4. Do Defensive Normalization at the Harness Layer

    Handle common deviations in a controlled way: field trimming, alias mapping, lenient type conversion, and whitespace normalization. Note that normalization must be auditable so that genuine semantic errors are not masked.

    5. Make Evaluation Layered, and Reject a Single Leaderboard

    Split evaluation into three layers to pinpoint where a problem belongs:

    • Schema compliance: only whether it passes validation, not content quality;
    • Task correctness: whether the edit actually hits the target;
    • End-to-end: whether a multi-turn tool chain converges.

    Also run scores separately on “native-style schemas” and “non-native-style schemas” so that the leniency of a single ecosystem does not mislead you.

    6. Observability First

    For every tool call, record the raw generated text, the parse result, validation errors, the number of retries, and whether it ultimately succeeded. Without these logs, any optimization is guesswork. You can combine a logging service, monitoring and alerting, and object storage to retain and analyze the full trace.

    5. A Checklist for Your Team

    • Is schema-constrained decoding enabled?
    • Is the tool schema narrow enough, and does it include a minimal example?
    • Are validation errors locatable and actionable?
    • Is there field normalization and a retry fallback?
    • Does evaluation cover non-native-style schemas with layered statistics?
    • Are complete call-chain logs retained?

    6. Conclusion

    Large models can call tools because they are trained to generate structured text under specific marker conventions, which the host program parses, validates, and executes. The so-called “newer models are worse on unfamiliar schemas” is essentially a mismatch between the training distribution and validation strictness, not a loss of capability. For engineering teams, the right response is not to swap models, but to move constraints forward into the decoding stage, turn correction into a closed loop, and make evaluation layered. When all four are in place, tool-calling stability no longer depends on luck; it becomes a measurable, regression-testable, deliverable system capability.