LLM Function Calling and Tool Use: JSON Mode, Structured Outputs, and Parallel Tool Calls

LLM Function Calling and Tool Use: JSON Mode, Structured Outputs, and Parallel Tool Calls

Every production agentic system sits on top of a deceptively simple contract: an autoregressive language model reads a natural-language goal, selects an external tool from a catalog of JSON Schemas, and emits a syntactically valid, type-safe payload that deterministic code can execute. Early implementations relied on prompt engineering ("respond only in valid JSON, no markdown backticks") and brittle regex parsers that broke on unescaped quotes or hallucinated parameter names. Modern tool-use stacks combine fine-tuned control tokens, Context-Free Grammar (CFG) constrained decoding, parallel tool-call dispatch, and self-correcting Pydantic validation loops to achieve 99.9%+ reliability in production.

How Function Calling Works Under the Hood

An LLM does not "execute" functions; it predicts tokens conditioned on a serialized tool specification injected into the system prompt and restricted at inference time by a token-level state machine. When a client sends a list of tools to OpenAI's Responses/Chat API, Anthropic's Messages API, or Google's Gemini API, the serving runtime serializes those JSON Schemas into a compact TypeScript-like or XML declaration block inside the system context and activates post-training control tokens (such as <|tool_call|>, <tool_use>, or function_call).

There is a critical architectural distinction between legacy JSON Mode (response_format: { "type": "json_object" }) and modern Constrained Structured Outputs (strict: true, Outlines FSM, XGrammar, or Guidance):

  • JSON Mode only guarantees that the emitted token sequence parses via JSON.parse(). It does not enforce adherence to a specific schema: the model can still omit required keys, output a string where an integer was requested, or invent hallucinated fields.
  • CFG / Finite-State Machine (FSM) Constrained Decoding compiles the target JSON Schema into a pushdown automaton or context-free grammar over the model's subword vocabulary $V$ before generation starts. At every autoregressive decoding step $t$, the grammar engine determines the set of valid continuation tokens $V_{\text{valid}}(s_t) \subseteq V$ from the current parser state $s_t$ and applies a logit mask before the softmax:

$$\tilde{z}_{t, i} = \begin{cases} z_{t, i} & \text{if token } i \in V_{\text{valid}}(s_t) \\ -\infty & \text{otherwise} \end{cases}$$

Setting invalid tokens to $-\infty$ forces their softmax probability to $0.0$, making it mathematically impossible for the model to emit a syntax error, an undeclared key, or an out-of-enum string. Engines like XGrammar and Outlines pre-compute vocabulary bitmasks for deterministic state transitions (such as emitting {"status": "), incurring less than 40 microseconds of CPU overhead per token step.

Comparison of Frontier LLM Tool Calling & Structured Output APIs
Provider / Runtime Tool Declaration Key Strict Schema Guarantee Parallel Tool Calls Correlation ID Field
OpenAI (GPT-4o / o1) tools[].function strict: true (CFG mask) Yes (parallel_tool_calls) tool_call_id
Anthropic (Claude 3.5) tools[].input_schema Fine-tuned + token-constrained Yes (multiple tool_use blocks) tool_use.id
Google (Gemini 1.5 / 2.0) function_declarations response_schema (OpenAPI) Yes (multi-part functionCall) Name + index / call ID
vLLM / SGLang (Open-Weights) OpenAI-compatible tools XGrammar / Outlines FSM Yes (Llama-3.1 / Qwen2.5 template) tool_call_id

Schema Design: Required vs. Optional, Enums, and Nested Objects

Even when constrained decoding guarantees syntactic validity, poorly designed schemas degrade semantic accuracy — causing the model to pick the wrong tool or populate valid types with nonsensical values. Four schema engineering rules govern high-accuracy tool use:

  • Flat Top-Level Signatures Beat Deeply Nested Polymorphism: Deeply nested anyOf/oneOf unions increase the branching factor of the grammar automaton and confuse attention heads. Splitting one overloaded mega-tool (manage_database(action, payload)) into three explicit, narrowly scoped tools (create_table, run_readonly_sql, drop_index) improves tool selection accuracy by 12–18% on Berkeley Function-Calling Leaderboard (BFCL) evaluations.
  • Strict Mode Requires All Fields in required: In OpenAI's strict: true CFG mode, every property defined in properties must be listed in required, and additionalProperties must be set to false. Optional fields are represented by making their type nullable (e.g., "type": ["string", "null"]) rather than omitting the key, which eliminates branching ambiguity in the FSM state graph.
  • Constrain Free-Text Strings with enum and Semantic Descriptions: Never expose a raw string parameter when the downstream API accepts a closed set of values. Replacing "environment": {"type": "string"} with "environment": {"type": "string", "enum": ["staging", "eu-prod", "us-prod"]} forces the logit mask to select one of the three valid token sequences.
  • Put Reasoning Fields First in the Key Order: Because autoregressive models generate JSON keys top-to-bottom and cannot revise earlier tokens, placing a "chain_of_thought_rationale": {"type": "string"} field before an "action_decision" enum gives the model token budget to deliberate before committing to the classification token.

Parallel Tool Calls and Multi-Step Orchestration

Without parallel tool calling, answering a query like "Compare the Q3 revenue, current P99 latency, and open incident count for the checkout service" requires three sequential LLM round-trips: call Tool A, wait for RTT, feed result, call Tool B, wait for RTT, feed result, call Tool C. At 800ms per LLM prefill+decode turn, sequential execution wastes 2.4 seconds on network serialization alone.

With parallel tool dispatch enabled, the LLM emits an array of independent tool invocations in a single assistant message, each tagged with a unique correlation ID (call_9f8a..., toolu_01Xz...). The host runtime executes all three I/O bound calls concurrently via asyncio.gather() and appends all three tool / tool_result messages matched by ID before invoking the LLM a second time to synthesize the final answer.

When should parallel tool calls be disabled (parallel_tool_calls: false)? Whenever tools have sequential state dependencies or non-idempotent side effects — for example, when Tool 2 requires the primary key returned by Tool 1, or when mutating database rows where concurrent execution could violate foreign-key ordering.

Strict JSON Mode and Pydantic Validation Pipelines

Constrained decoding enforces structural types (string, integer, boolean, enum), but it cannot enforce domain invariants such as "end_date must be chronologically after start_date" or "allocation_percentages must sum to 100.0." Pairing API-level strict schemas with Pydantic v2 custom validators (`@model_validator`) closes that gap:


import asyncio
import json
from datetime import date
from typing import Literal, List, Optional
from pydantic import BaseModel, Field, model_validator, ValidationError

class MetricQueryArgs(BaseModel):
    service_name: Literal["payments-api", "auth-gateway", "search-indexer"] = Field(
        description="Canonical microservice identifier from the service catalog."
    )
    start_date: date = Field(description="ISO-8601 start date (YYYY-MM-DD).")
    end_date: date = Field(description="ISO-8601 end date (YYYY-MM-DD), must be >= start_date.")
    percentile: Literal["p50", "p95", "p99"] = "p99"
    region: Optional[Literal["us-east-1", "eu-central-1", "ap-southeast-1"]] = None

    @model_validator(mode="after")
    def verify_date_window(self) -> "MetricQueryArgs":
        if self.end_date < self.start_date:
            raise ValueError(
                f"end_date ({self.end_date}) cannot precede start_date ({self.start_date})."
            )
        if (self.end_date - self.start_date).days > 90:
            raise ValueError("Query window cannot exceed 90 days; narrow start_date and end_date.")
        return self

async def execute_validated_tool_call(tool_call_id: str, raw_json_args: str) -> dict:
    """Validate LLM tool arguments with Pydantic v2 and return a structured tool_result."""
    try:
        parsed = MetricQueryArgs.model_validate_json(raw_json_args)
        # Execute deterministic backend call
        data = {"service": parsed.service_name, "metric": parsed.percentile, "value_ms": 42.8}
        return {
            "role": "tool",
            "tool_call_id": tool_call_id,
            "content": json.dumps({"status": "ok", "data": data}),
        }
    except ValidationError as exc:
        # Feed structured validation errors back to the LLM for self-correction
        return {
            "role": "tool",
            "tool_call_id": tool_call_id,
            "content": json.dumps({
                "status": "validation_error",
                "errors": exc.errors(include_url=False),
                "hint": "Correct the invalid arguments and invoke the tool again."
            }),
        }
      

Error Handling, Retries, and Fallback Strategies

In production agent loops, raising an unhandled exception when a tool call fails crashes the entire user session. Instead, tool failures belong inside the conversation trajectory as structured error observations so the model can recover autonomously:

  • Validation Reflection Loops (Max 2 Retries): When Pydantic or a downstream API rejects arguments (HTTP 400 / 422), return the exact field path and validator message inside the tool_result block with is_error: true. Across Claude 3.5 Sonnet and GPT-4o, feeding back the structured ValidationError resolves 96% of semantic constraint violations on the immediate next turn. Cap reflection retries at 2 per tool to prevent infinite token-burning loops.
  • Distinguish Transient Infrastructure Errors from Logic Errors: Never ask the LLM to "fix" an HTTP 503 Service Unavailable, a TCP timeout, or an HTTP 429 rate-limit error by changing its query arguments. Catch transient transport errors in the host executor, apply exponential backoff with full jitter ($t = \text{random}(0, \min(T_{\max}, b \cdot 2^{\text{attempt}}))$), and only surface a concise {"status": "service_temporarily_unavailable"} message to the LLM if the circuit breaker trips so it can switch to a fallback data source.
  • Idempotency Keys for Mutating Tools: Any tool that writes state (creating a ticket, charging an invoice, provisioning a cluster) must accept a deterministic idempotency token derived from the conversation ID and turn index, ensuring that network retries or duplicate model tool emissions never execute a side effect twice.