Troubleshooting Guide for LLM Tool Calling Output Anomalies

    When LLMs output tool calls as plain text instead of structured results, the issue is often misdiagnosed as a model or prompt problem. This guide explains how incompatible chat templates and inference engine parsers cause these anomalies, and provides actionable steps to troubleshoot, modify, and verify your tool calling pipeline.

    Tool calling output anomalies typically manifest when the model explicitly mentions the function and parameters to call, but the server fails to generate a structured tool calling result, returning the entire content as a standard text response instead. On the business side, this appears as unexecuted functions and parameters missing from the call chain, with logs showing only what looks like a code block. This issue is often misdiagnosed as insufficient model capability or weak prompt design. In reality, the most common root cause is that the chat template injected during inference and the built-in tool parser of the inference engine use two incompatible sets of output conventions.

    Symptoms and Impact

    In a conversational interface with tool calling enabled, a standard request usually contains three parts: system and user messages, the names and parameter schemas of available tools, and the calling format the model should follow. The expected result is not a descriptive text suggesting “you can call this function,” but rather a callable structure that can be directly consumed by the program, such as the function name, an arguments object, and a call termination marker.

    When an anomaly occurs, the generated text often contains segments similar to the following:

    1. I will call the query interface.
    2. ```json
    3. {"name":"lookup","arguments":{"id":"42"}}
    1. While this content is human-readable, it is often invalid for the parser. The parser does not "understand" arbitrary Markdown; it only matches against pre-agreed markers, delimiters, or special token sequences. When the match fails, the engine falls back to the plain text channel. Consequently, the tool list is effectively ignored, and downstream orchestration, permission verification, and result backfilling are never triggered. For agent-based applications, this causes multi-step tasks to fail at the very first step, and the error is difficult to distinguish from standard business return codes.
    2. ## Do Not Mix Two Output Conventions
    3. Common tool calling outputs in the industry generally fall into two categories.
    4. The first is the native model convention. During training or post-training, the model learns to output function names and parameters between specific special tokens. These tokens are not decorative elements for the user; they are control symbols in the tokenizer's vocabulary. The parser splits by token boundaries to reliably distinguish between "normal narration" and "a function call."
    5. The second is the free-text convention. The prompt requires the model to describe the call using code blocks, fixed prefixes/suffixes, or some JSON wrapping. This approach is simple to implement and suitable for models without native tool tokens, but it must be scanned entirely by a compatible parser. Once the runtime switches to a parser that only recognizes special tokens, the JSON inside the code block is treated merely as body text.
    6. These two conventions can work independently, but they cannot each do half the work in a single generation. If the template injects tool definitions on one hand while using natural language to command the model to "please output using three backticks and json," the model will prioritize the more explicit formatting instruction in the template and abandon the native tokens. The parser still scans in native mode, resulting in a situation where "generation looks successful, but parsing inevitably fails."
    7. ## Why Custom Templates are Prone to Pitfalls
    8. The responsibilities of a chat template are usually limited to a few tasks: assembling role messages, inserting the tool list, declaring the call timing, and preserving the model's original start and end markers. It is not responsible for inventing a new serialization dialect.
    9. During the adaptation process for new hardware or new runtimes, teams often copy a generic template and modify it manually. Common deviations include:
    10. - Stuffing tool definitions into the system prompt, then appending hard instructions like "must output Markdown code blocks."
    11. - Deleting or rewriting the start and end call markers the model originally relied on, leaving only natural language explanations.
    12. - Changing compact JSON into mixed text with comments and explanations for readability.
    13. - Providing both a correct example and an alternative "can also use code blocks" example in the template, causing the model to randomly choose one.
    14. Matching on the parser side is usually deterministic: it either hits the calling interval or treats the entire segment as text. It does not perform fuzzy error correction, nor does it automatically promote a tool call just because valid JSON appears in the text. Therefore, extra format instructions in the template do not enhance robustness; they actively create mismatches.
    15. Another easily overlooked point is the runtime image. Accelerators, inference engines, tokenizers, and chat templates are often bundled in the same image. If the image only adapts operators or weight loading but retains the template and parser combination of another model, it might handle normal Q&A perfectly while systemically failing at tool calling. In this case, simply modifying a prompt is insufficient. You must align the template, parser, and tokenizer vocabulary back to the same contract and rebuild the adaptation image to prevent the old template from being loaded by default paths.
    16. ## Troubleshooting Sequence
    17. It is recommended to troubleshoot based on the data plane rather than guessing and modifying prompts.
    18. 1. Fix a minimal request: one user message, one unambiguous tool, and a set of required parameters. Turn off sampling randomness for easier comparison.
    19. 2. Save the model's raw generation, not the final message rewritten by the gateway. Confirm whether the failure occurs before or after parsing.
    20. 3. Compare the template rendering results to check if there are format instructions, example code blocks, or rewritten special markers outside of the tool list.
    21. 4. Ensure that the parser mode matches the calling protocol used during model training, rather than matching the "more universally-looking" JSON code blocks.
    22. 5. Run a control test using the same weights in a reference environment with an unmodified template. If the reference environment can parse but the adapted environment cannot, the problem lies in the template or the image, not the weights themselves.
    23. Logs should retain both the fully rendered prompt and the raw generation simultaneously. Logging only "parse failed" without the raw generated text makes it impossible to distinguish later whether the model failed to output according to the protocol, or whether the protocol itself was altered by the template.
    24. ## Modification Principles
    25. The goal of the fix is to restore the contract, not to add another layer of complex prompting.
    26. - Only inject tool information as a list: name, purpose, parameter schema, and required fields. Do not append instructions like "please output in a certain code block."
    27. - Preserve the model's native call start and end markers; do not translate them into natural language.
    28. - Delete examples that conflict with the parser's regex or token rules. If examples must exist, they must be structurally identical word-for-word to the parser's positive examples.
    29. - Keep parameter values as objects parseable by standard JSON. Do not insert comments, trailing commas, or Chinese punctuation.
    30. - Publish template changes together with the parser version. Updating only one will cause intermittent failures during rolling upgrades.
    31. After modifications, the same minimal request should yield a structured call instead of text. Additionally, perform three types of regression tests: no false triggers when tools are absent; function names must fall within the whitelist when multiple tools are present; missing parameter fields should return a clear validation error rather than treating half a JSON block as body text.
    32. A schematic template boundary can be written as:
    33. ```text
    34. [System message and user message]
    35. [Tool list: name, description, parameter schema]
    36. [Model's native call start marker]
    37. {function name and parameters}
    38. [Model's native call end marker]

    The markers here should come from the model’s existing protocol, not temporarily invented Markdown fences. If the runtime only provides a free-text parser, the entire chain should be switched to a free-text protocol, and the parsing rules must correspond exactly to the template examples. You cannot retain a native token parser.

    Pre-launch Checks

    Before publishing the adapted image, verify at least the following: whether the tokenizer recognizes the call control symbols; whether the default template path points to the new template; whether the parser is enabled in tandem with the template; and whether the three paths—normal chat, streaming output, and tool calling—pass respectively. In streaming scenarios, also ensure that the parser submits the tool call to the business side only after the calling interval is closed, preventing half-baked JSON from being prematurely spit out as text.

    For monitoring, it is recommended to distinguish two types of metrics: generation success rate and tool parsing success rate. If the former is high and the latter is low, it is almost certainly a protocol mismatch, not a computing power or memory issue. Alarm thresholds can be set by API dimension to avoid being diluted by normal Q&A traffic.

    Conclusion

    When tool calls are output as plain text, the essence is a divergence between the generation protocol and the parsing protocol. The extra format instructions written into custom templates cause the model to deviate from native special tokens; unable to match, the parser can only degrade the call into body text. The correct approach is to only inject the tool list, restore the original markers, delete non-standard output requirements, and manage the template, parser, and runtime image as a single deliverable. Only then can tool calls re-enter the executable chain rather than remaining stuck on a seemingly correct piece of text.