AiCredits
Structured Output

JSON Mode vs Function Calling: Reliable Structured Output

JSON mode and function calling solve different halves of the structured output problem. Learn when each fails, and the validation loop that survives production.

Published 2026-11-17 Updated 2026-11-17 9 min

Two promises, not one

Both JSON mode and function calling get sold as "structured output", but they fix different halves of the problem. JSON mode fixes syntax: the model returns something json.loads() can parse. Function calling fixes shape: the model is told a named object with named fields exists, and is nudged into filling it. Neither fixes semantics. Nothing stops a model from putting a string where you wanted an integer, or inventing a line item that was never on the page.

That distinction decides your architecture. If you're going to validate the output against a schema library anyway, JSON mode is the simpler and cheaper path. If you want the model to choose between actions — extract, escalate, ask a clarifying question — function calling is the only one that scales past a single object type.

What JSON mode actually guarantees

With response_format={"type": "json_object"} you get two things: the reply parses as JSON, and the model is steered toward emitting JSON even when the prompt is vague. You do not get your schema. The model has never seen your Pydantic class unless you paste it in — and even then it treats the schema as advice, not a constraint. Note also that many OpenAI-compatible APIs require the literal word "json" to appear in your messages before the flag takes effect, so a system prompt that names JSON is doing double duty.

The recipe that actually holds is: schema in the prompt, validation after the call, and a repair turn that feeds the validation error back to the model. That third step is what people skip, and it's the one that turns a demo into something you can put behind a queue.

import json, os
from typing import Literal
from openai import OpenAI
from pydantic import BaseModel, ValidationError

client = OpenAI(
    api_key=os.environ["AICREDITS_API_KEY"],
    base_url="https://api.aicreditsapi.com/v1",
)

class LineItem(BaseModel):
    sku: str
    qty: int
    unit: Literal["each", "kg", "box"]

class Invoice(BaseModel):
    vendor: str
    currency: Literal["USD", "EUR", "GBP"]
    items: list[LineItem]
    total_cents: int | None

SYSTEM = (
    "Extract invoice data. Reply with one JSON object only — no prose, no fences. "
    "It must validate against this JSON Schema:\n"
    + json.dumps(Invoice.model_json_schema(), indent=2)
)

def extract_invoice(document: str, attempts: int = 3) -> Invoice:
    messages = [
        {"role": "system", "content": SYSTEM},
        {"role": "user", "content": document},
    ]
    for _ in range(attempts):
        resp = client.chat.completions.create(
            model="deepseek-v4-flash",
            messages=messages,
            response_format={"type": "json_object"},
            temperature=0,
            max_tokens=2048,
        )
        choice = resp.choices[0]
        raw = choice.message.content or ""

        if choice.finish_reason == "length":
            raise RuntimeError("Truncated output: raise max_tokens or chunk the document.")

        try:
            return Invoice.model_validate_json(raw)
        except (ValidationError, ValueError) as err:
            messages.append({"role": "assistant", "content": raw})
            messages.append({
                "role": "user",
                "content": f"That failed validation:\n{err}\nReturn the corrected JSON object only.",
            })
    raise RuntimeError("No schema-valid JSON after retries")

What function calling gives you instead

Tools move the schema out of the prompt and into the request body. You declare record_invoice with a JSON Schema for its parameters, force it with tool_choice, and read the result back from arguments. Because the model is optimising against a named interface rather than prose, it tends to respect field names and required fields more faithfully — useful when your schema has ten fields and three of them are easy to confuse.

The catch: arguments is a string, not an object. It can be empty, it can omit required keys, and it can be valid JSON that still fails your Literal and int constraints. Parse and validate exactly as you would in JSON mode. The schema lowers the error rate; it does not eliminate it.

tools = [{
    "type": "function",
    "function": {
        "name": "record_invoice",
        "description": "Record structured invoice data extracted from a document.",
        "parameters": Invoice.model_json_schema(),
    },
}]

def extract_invoice_via_tool(document: str) -> Invoice:
    resp = client.chat.completions.create(
        model="deepseek-v4-flash",
        messages=[
            {"role": "system", "content": "Extract invoice data by calling record_invoice. "
                                          "Never invent a field you cannot see."},
            {"role": "user", "content": document},
        ],
        tools=tools,
        tool_choice={"type": "function", "function": {"name": "record_invoice"}},
        temperature=0,
    )
    msg = resp.choices[0].message
    if not msg.tool_calls:
        raise ValueError(f"Model returned text instead of a call: {msg.content!r}")
    raw = msg.tool_calls[0].function.arguments or "{}"
    return Invoice.model_validate_json(raw)

Side by side

AspectJSON modeFunction calling
Schema enforcementNone — valid JSON, any shapeSchema in the request steers the shape
Where the schema livesYour prompt texttools[].function.parameters
What you read backmessage.contenttool_calls[].function.arguments
Token overheadPrompt only, cacheableSchema resent on every request
Multi-action routingAwkwardNative
Failure signatureWrong shape, missing keysEmpty arguments, wrong tool, hallucinated fields
Best fitOne fixed object typeTyped extraction across several schemas

Failure modes worth pre-empting

  • Truncation. finish_reason == "length" means the JSON was cut mid-token and will never parse. Check it before blaming the model.

  • Top-level arrays. Many JSON modes want an object at the root. Wrap lists as {"items": [...]} rather than returning a bare array.

  • Empty arguments. A tool call with arguments == "" usually means the model found nothing to extract. Treat it as a refusal, not a parse error.

  • Markdown fences. Only a risk outside JSON mode, but keep a fence-stripping fallback if you ever call without response_format.

  • Temperature. 0 makes output steadier, not deterministic. Never assert on exact strings in tests.

  • Schema drift. Rename a field in code and you must rename it in the prompt. A stale schema produces confident garbage.

Make the schema do the work

Two schema tricks cut repair loops dramatically. First, use enums instead of free text wherever the domain allows: a currency typed as "USD" | "EUR" | "GBP" cannot invent "US$", and models honour enums well. Second, give genuinely uncertain fields a nullable escape hatch — total_cents: int | None — so the model has a legitimate way to say "not stated" instead of fabricating a number. Fabricated data costs far more to clean up than missing data.

Route on attempt count, not on vibes

deepseek-v4-flash handles the bulk of structured extraction well and should be your default — most documents are boring, and spending on extra reasoning for boring documents is waste. Reserve deepseek-v4-pro for records that fail validation twice, or for schemas with deep nesting and cross-field constraints where the stronger model earns its higher price. A simple ladder works: flash, flash, then pro on the third attempt.

Pricing is usage-based, off-peak calls cost less than peak, and cache hits on a stable system prompt are cheaper still — check aicreditsapi.com/deepseek-prices for current rates before you budget at volume. Both snippets above run unchanged against the AiCredits endpoint using the standard OpenAI SDK, and topping up takes a card or PayPal with no Chinese phone number or bank account required.

If you can't write the validator, you don't have a schema — you have a hope.

Frequently asked

Does JSON mode enforce my schema?

No. It guarantees parseable JSON, not your fields. Schema enforcement is your validator's job — Pydantic in Python, Zod in TypeScript — followed by a repair retry that shows the model the error.

Which is cheaper, JSON mode or function calling?

JSON mode, generally. The tool schema is resent with every request, adding input tokens per call, whereas a schema embedded in a stable system prompt can be served from cache. Function calling earns that overhead when you need several actions or stricter field adherence.

Can I combine JSON mode and function calling in one request?

You can send both, but in practice you get one kind of output back, so the parsing logic just becomes conditional for no benefit. Pick one mode per request path.

How many repair attempts should I allow?

Two. Past that the failure is usually structural — truncated input, a schema the model can't satisfy, or a document that genuinely lacks the fields. Escalate to deepseek-v4-pro or route to human review.

Do I still need to strip markdown fences?

Not in JSON mode. Keep a fence-stripping fallback if you ever fall back to a plain prompt, since prose-wrapped JSON is the classic plain-prompt failure.

Try Lint in 2 seconds

Wrote something? Paste it here for a free grammar check. No account needed.

More Tools →

Related Tools

Was this article helpful?

| Share on X Reddit Copy link

服务器宕机了?别等用户告诉你

Wakeless 梦哨 帮你 30 秒监控网站 / API / SSL 证书,宕机秒级告警到邮箱、飞书、Slack。免费档 30 个监控,永久免费,无需信用卡。

免费开始监控 →
💬
反馈意见 / Feedback ×