Function Calling and Structured Output: Schemas, Strict Mode, Retries

By Updated

What is function calling?

Function calling is an API mechanism where the application passes function schemas to the model, and the model returns a function name plus JSON arguments that follow the schema. The model executes nothing: your code makes the call. Structured output is a related mechanism that makes the model's answer itself match a JSON Schema.

TL;DR

  • -Function calling returns a function call, structured output returns an answer as JSON. Use the first for actions and the second for data extraction.
  • -Without strict mode, the schema only hints at the format. Strict mode (strict at Anthropic and OpenAI, VALIDATED in Gemini, a beta at DeepSeek) constrains generation to the schema, but it doesn't guarantee that the model calls a function or that the values make sense.
  • -Vendors accept different JSON Schema subsets: Claude returns 400 on oneOf, recursion and numeric bounds, OpenAI rejects allOf and not, Gemini silently ignores minLength.
  • -In the author's test on November 29, 2026 (6 models, 360 responses, a simple schema), four of the six models made no errors in any mode. The differences showed up on Qwen3 Coder and Mistral Small 3.2.
  • -A setup that works: strict mode, Pydantic validation at the boundary, at most 2-3 retries that include the error text, and an executor that rejects unknown function names.

Function calling returns a function call, structured output returns an answer as JSON that follows a schema. In the first case, the model names a function and its arguments, and your code executes it. In the second, the JSON is the result. Use function calling for actions (create an order, query a database) and structured output for data extraction and classification.

Both mechanisms rest on JSON Schema, and without strict mode both only ask the model to follow the format. With strict mode, generation is constrained by the schema, but checking what the values mean is still your job. A reliable setup has four parts: strict, validation at the application boundary, a bounded retry, and an executor that doesn’t trust the function name in the response.

Vendor requirements were checked against the documentation on November 29, 2026. The author ran the test the same day through OpenRouter, and the Pydantic code was executed on version 2.14.4 and Python 3.13.

Function calling vs structured output

Function callingStructured output
What the model returnsa function name and argumentsresponse text that is valid against the schema
What happens nextcode runs the function and returns the result to the modelcode parses the JSON, the conversation can end there
Typical taskan action, a data lookup, an agent stepfield extraction, classification, a report
Can the model skip the formatyes, with auto it may answer in textno, except for refusals and cutoffs
Claudetools, tool_useoutput_config.format
OpenAItools, function_calltext.format or response_format
GeminifunctionDeclarations, functionCallresponse_json_schema

Google’s documentation draws the same line: structured output formats the final response, function calling is for when the model needs to ask you to perform a task. You can use a function as a way to get JSON, but then you also depend on whether the model decides to call it. In the test below, that decision failed more often than the format did.

How the call loop works

  1. The application sends messages and a list of functions with schemas.
  2. The model answers with text or with calls.
  3. Code checks the name and arguments and runs the function.
  4. The result goes back with the call ID.
  5. The loop repeats until the model answers in text or you hit the step limit.

The schema is the same everywhere, only the wrapper differs:

Anthropic            {"name", "description", "strict", "input_schema": {...}}
OpenAI Responses     {"type": "function", "name", "strict", "parameters": {...}}
Chat Completions     {"type": "function", "function": {"name", "strict", "parameters": {...}}}
Gemini               {"functionDeclarations": [{"name", "description", "parameters": {...}}]}

OpenAI, DeepSeek and OpenRouter all understand the Chat Completions format, but not every model is available in it: per the OpenAI documentation, GPT-6 Astra and GPT-6.1 Sol require the Responses API for tool calling.

Two things get lost when you assemble the history by hand. One is the ID: tool_use_id at Anthropic, call_id at OpenAI, tool_call_id in Chat Completions. The other is reasoning. OpenAI requires you to return reasoning items along with the results, and Gemini 3 requires thought signatures and answers 400 if they’re missing (thought signatures). SDKs handle this for you if you put the model’s whole response into the history.

A function description is as much a part of the interface as the schema. Say what the function does, when not to call it, and what format the arguments take. OpenAI suggests fewer than 20 functions at the start of a turn, Google 10-20 active ones. A full Python example of the loop is in the Claude API guide, and the choice between your own functions and a separate server is covered in MCP vs API.

JSON Schema: what each vendor supports

ClaudeOpenAIGemini (generateContent)DeepSeek (strict, beta)
All fields in requirednot needed, but up to 24 optional ones per requestrequirednot neededrequired
additionalProperties: falserequiredrequirednot neededrequired
anyOfyesyes, but not at the rootyesyes
oneOf / allOf / notno / with caveats / nonot listed / no / nonot listednot listed
Recursionnoyesyes, the reference must be optionalyes, via $ref
minimum, maximumno, 400yesyesyes
minLength, maxLengthno, 400not in the supported listsilently ignorednot supported
minItems, maxItemsonly minItems 0 or 1yesyesnot supported

Sources: Claude, OpenAI, Gemini, DeepSeek. The OpenAI column is for regular models: the list is shorter for fine-tuned ones.

There are complexity limits too. Claude allows up to 20 strict functions per request, 24 optional parameters and 16 parameters with anyOf or a list of types, counted across all schemas. OpenAI allows up to 5,000 properties and 10 nesting levels. Gemini publishes no exact numbers, and a schema that is too complex returns 400 INVALID_ARGUMENT.

What to do with bounds

A constraint the vendor doesn’t accept moves into the field description, and code checks it. According to the documentation, Anthropic’s Python SDK (client.messages.parse) does this for you. If you send the schema by hand, one function is enough:

UNSUPPORTED = ("minimum", "maximum", "exclusiveMinimum", "exclusiveMaximum",
               "multipleOf", "minLength", "maxLength", "maxItems")

def portable(node):
    """Drops constraints Claude doesn't accept and writes them into description."""
    if isinstance(node, list):
        return [portable(x) for x in node]
    if not isinstance(node, dict):
        return node
    out, notes = {}, []
    for key, value in node.items():
        if key in UNSUPPORTED and not isinstance(value, dict):
            notes.append(f"{key}={value}")
        elif key in ("properties", "$defs"):
            out[key] = {name: portable(sub) for name, sub in value.items()}
        else:
            out[key] = portable(value)
    if notes:
        out["description"] = f"{out.get('description', '')} ({', '.join(notes)})".strip()
    if out.get("type") == "object":
        out["additionalProperties"] = False
    return out

It doesn’t fix recursion, oneOf or minItems above 1. The function was checked on the Order schema from the Pydantic section: the bounds 1 and 9 disappeared from passengers, and (maximum=9, minimum=1) appeared in the description. No request with this schema was sent to Claude.

Dictionaries with arbitrary keys won’t pass either. Per the Anthropic documentation, for a dict field the model can only return {}. Use an array of key and value pairs instead.

What strict mode guarantees

  • Claude. strict: true on a function constrains argument generation with a grammar compiled from the schema (strict tool use). output_config.format does the same for the response. The first request with a new schema is slower, and the compiled grammar is cached for 24 hours from last use.
  • OpenAI. The API rejects an unsuitable schema with strict: true. If strict isn’t set, Responses tries to normalize the schema to strict, and on failure falls back to non-strict mode and shows strict: false. Chat Completions is non-strict by default.
  • Gemini. For the response you set response_json_schema, for functions there are the VALIDATED mode (text or a schema-conforming call) and ANY (always a schema-conforming call). VALIDATED turns on by itself when functions are combined with built-in tools or structured output.
  • DeepSeek. Per the documentation, you need the https://api.deepseek.com/beta address and strict: true on every function, and an unsupported schema returns an error. In the author’s check on November 29, 2026, a schema with minLength produced no error, and on the regular address strict: true also passed silently. A missing error here doesn’t prove that strict mode is active.

What no vendor gives you:

  1. Meaning. A departure date can be valid and wrong.
  2. The call itself. With auto, the model may answer in text.
  3. Completeness. On a refusal, Claude returns stop_reason: "refusal" and code 200, on a cutoff max_tokens. OpenAI sends a refusal part or status: "incomplete". In both cases the JSON may not match the schema.
  4. Enum case in Claude. The documentation warns that Conversation topic 3 may come back as Conversation Topic 3 with no error at all. Compare case-insensitively.

Forced tool choice and parallel calls

Mandatory callSpecific functionOne call per turn
Claudeanytool + namedisable_parallel_tool_use inside tool_choice
OpenAIrequiredobject with the nameparallel_tool_calls: false
GeminiANYANY + allowed_function_namesno separate parameter in the mode descriptions
DeepSeekrequiredobject with the nameignored in Responses

On Claude Opus 5.5, Sonnet 5.5, Fable 5.2 and Fable 5.1, the values any and tool return 400 with the message tool_choice: type "tool" and "any" are not supported for this model. The replacement is auto with strict and a direct instruction in the prompt, or structured output. Haiku 5.5 and Opus 5 accept a forced call but skip thinking.

DeepSeek has a similar restriction: a forced choice together with reasoning returned 400 “Thinking mode does not support this tool_choice” in the author’s check. The documentation says the same: turn reasoning off first.

With parallel calls, the most common mistake on Claude is returning each tool_result as a separate message. The documentation says this “teaches” Claude to avoid parallel calls. Send one user message with all the results, and text only after them. You can run the calls in any order, but functions with side effects are better run sequentially.

OpenRouter: one request, different providers

Through a gateway, strictness depends on who served the request. The OpenRouter documentation says so directly: some providers guarantee the schema, others translate it into their own format or treat it as a strong hint. Support is defined per endpoint, not per model.

That gives two rules. Set provider: {"require_parameters": true}, otherwise the request may go to a provider that ignores an unknown parameter. And pass tools in every request of the loop, including the one that returns the result. A live check of require_parameters is described in the OpenRouter guide.

Test: six models, four modes

The task: extract an order from a short text into a schema with an enum, a date or null, an integer and an array of objects. Five orders with traps (quotes and brackets in the text, a date in words, “one” as a word, a missing date), three repeats each, 360 responses in total. The order texts and prompts were mostly in Russian. Each cell shows the number of fully correct responses out of 15: parsing, fields, types, enum, date format and values were checked (customer name and city were not compared). Reasoning was disabled where the model allows it. tool_choice was not set. Taken on November 29, 2026 through OpenRouter, cost $0.11.

Model”Return only JSON” promptjson_schema strictfunctionfunction strict
Claude Haiku 5.515 (7 fenced)151515
GPT-6 Luna15151515
DeepSeek V4.1 Flash 101715 (9 fenced)151515
Gemini 3.7 Flash15 (14 fenced)151515
Qwen3 Coder15 (5 fenced)1512 (3: date format)12 (3: date format)
Mistral Small 3.2 24B12 (3: broken extras; 12 fenced)14 (1: wrong value)10 (5 with no call)12 (3 with no call)

“Fenced” means the JSON arrived inside a triple-backtick block. The script stripped the fence before parsing. A direct json.loads on such a response would have failed.

What follows from this, and what doesn’t:

  • On a simple schema, four of the six models made no errors at all, including with no strict mode of any kind. The test doesn’t show that strict helped them, it shows that the task is easy for them.
  • A fence appeared in at least 47 of 90 responses in prompt mode. Structured output solves that right away.
  • strict didn’t fix the date on Qwen3 Coder. In the schema, the field is described as a string or null, and the format is given only in description. A string in another format doesn’t violate that schema. The script didn’t save the values themselves, so the cause wasn’t established.
  • The main failure on Mistral Small is a missing call: the model answered in text and asked for details. Strict mode has no effect on that.
  • json_schema gave 89 correct out of 90, functions without strict 82, with strict 84. The whole difference comes from the two weak models.

Limits: 15 responses per cell, one schema, and the provider wasn’t pinned, so different providers answered for the same model. This is not a reliability ranking. On the direct DeepSeek API, 15 provocative requests (number of seats in words, a class outside the enum) gave 15 valid calls both with strict and without it.

Common failures

SymptomCauseWhat to do
400 on tool_choice with Claudethe model doesn’t accept any and toolauto + strict, or structured output
Claude stopped calling in parallelresults in different messagesone message, results before text
400 on Gemini 3 historythought signature lostreturn response parts unchanged
400 about the schemaoneOf, recursion, bounds (Claude), allOf (OpenAI), complexity (Gemini)simplify, move bounds to the description and code
An optional field is rejected by OpenAIin strict all fields are requiredrequired and a type with null
Truncated JSONlow token limit, reasoning used part of itcheck the stop reason, raise the limit
Empty DeepSeek response with stopper the documentation, non-JSON is replaced with whitespacethe word json in the prompt, retry
A function outside the list is calledthe executor trusts the namecheck the name against a registry in code

The last row isn’t theoretical. In another test the author ran the same day, a function was removed from the list while the page text kept a harmless request to call it. Mistral Small 3.2 still returned that call in 13 cases out of 20, Qwen3 Coder in 2 of 20, Haiku 5.5, GPT-6 Luna and DeepSeek never did. Removing a function from the request isn’t enough. The executor has to do the rejecting.

Validation and retries with Pydantic

It’s convenient to keep the schema and the validation in one model:

from datetime import date
from typing import Literal
from pydantic import BaseModel, ConfigDict, Field

class Extra(BaseModel):
    model_config = ConfigDict(extra="forbid")
    code: Literal["bag", "meal", "seat"]
    qty: int = Field(ge=1, le=20)

class Order(BaseModel):
    model_config = ConfigDict(extra="forbid")
    customer: str = Field(min_length=2)
    departure_date: date | None = Field(description="YYYY-MM-DD or null")
    passengers: int = Field(ge=1, le=9)
    cabin: Literal["economy", "business"]
    extras: list[Extra] = Field(max_length=5)

Parse with model_validate_json(raw, strict=True). Without strict, Pydantic 2.14.4 coerces types: in the run, true in the passengers field became one passenger, "2" became 2, and the number 1811808000 became the date June 1, 2027. With strict=True all three cases raised an error. One hole remained: the string "1811808000" passed as a date even in strict mode. If that matters, add a pattern check.

A retry with the error text (the model above lives in models.py):

from pydantic import ValidationError
from models import Order

class GiveUp(Exception):
    pass

def extract(call_model, messages, max_attempts=3):
    for attempt in range(1, max_attempts + 1):
        raw, finish = call_model(messages)
        if finish == "refusal":
            raise GiveUp("the model refused to answer")
        if finish in ("max_tokens", "length"):
            raise GiveUp("response truncated: raise the token limit")
        try:
            return Order.model_validate_json(raw, strict=True), attempt
        except ValidationError as e:
            problems = "\n".join(f"{'.'.join(map(str, x['loc'])) or 'response'}: {x['msg']}"
                                 for x in e.errors())
            messages = messages + [
                {"role": "assistant", "content": raw.strip() or "(empty response)"},
                {"role": "user", "content": f"Fix the errors and return the whole JSON again:\n{problems}"},
            ]
    raise GiveUp(f"no valid response in {max_attempts} attempts")

call_model returns the text and the stop reason, whose values are named differently across vendors. The loop was checked on a stub instead of a model: a response with the date 01.06.2027 and 12 passengers was fixed on the second attempt, while three bad responses in a row, a cutoff and a refusal all end in an exception. The author didn’t measure the share of successful retries on live models.

For functions, the same check sits in the executor:

import json
from pydantic import ValidationError
from models import Order

orders = {}

def save_order(order: Order, key: str) -> dict:
    orders.setdefault(key, order)      # a repeat with the same key changes nothing
    return {"status": "saved", "order_key": key}

REGISTRY = {"save_order": (Order, save_order)}

def dispatch(name: str, arguments: str, key: str) -> dict:
    if name not in REGISTRY:
        return {"is_error": True, "content": f"unknown tool: {name}"}
    model, func = REGISTRY[name]
    try:
        args = model.model_validate_json(arguments, strict=True)
    except ValidationError as e:
        return {"is_error": True, "content": e.json(include_url=False, include_input=False)}
    return {"is_error": False, "content": json.dumps(func(args, key))}

The side effect happens only after validation. Take the idempotency key from your own system (a message number, an order draft): the call ID won’t do, because it changes when the response is generated again. In the run, an unknown name and invalid arguments returned an error and wrote nothing, and a double call with one key left one order.

Business rules (the date isn’t in the past, the city exists in your catalog, the customer is allowed to place the order) don’t fit in a schema, so regular code checks them. Permissions and untrusted input are covered in the MCP security guide, and the agent loop in the AI agents guide.

Summary

  1. The JSON is the result: structured output with a strict schema.
  2. The model has to do something: function calling with strict, and lock in the decision to call through tool_choice where the model accepts it.
  3. Write the schema for the strictest of your vendors: all fields required, additionalProperties: false, no recursion or oneOf, bounds in the description.
  4. Keep Pydantic validation, a function registry and a retry limit with any model. With a strong model on a simple schema they will hardly ever trigger, but they protect against refusals, cutoffs, a provider switch and a function name that isn’t yours.

Before choosing a model, run your own schema and your own texts at least 15-20 times in two modes. On a toy order the author saw no difference between strong models. On a nested schema with dozens of fields, the result may be different.

Frequently Asked Questions

What is the difference between function calling and structured output?
Function calling is for when the model has to ask the application to do something: it returns a function name and arguments. Structured output is for when schema-conforming JSON is the final answer, such as data extracted from an email. Both rely on JSON Schema, and some vendors let you use them in the same request.
What does strict mode guarantee, and what doesn't it?
It guarantees types, required fields and the set of allowed values in a completed response. It doesn't guarantee that the values are right, doesn't force the model to call a function, and doesn't help with refusals or token-limit cutoffs. Anthropic also warns that the letter case of enum values can differ from the schema.
What are the JSON Schema limits in Claude, OpenAI and Gemini?
According to the documentation as of November 29, 2026, Claude doesn't accept recursion, oneOf, not, numeric bounds or string lengths. OpenAI requires an object at the root and every field in required, and rejects allOf, not and if/then/else. Gemini accepts minimum and maximum, and ignores minLength and maxLength without an error.
How do I force the model to call a specific function?
Use tool_choice: required or a function name at OpenAI, ANY mode in Gemini, any or tool at Anthropic. On Claude Opus 5.5, Sonnet 5.5, Fable 5.2 and Fable 5.1 a forced choice returns 400, so use auto with strict and name the function in the prompt. At DeepSeek a forced choice doesn't work together with reasoning.
What should I do when the model returns invalid JSON?
Check the stop reason first: sending the same request again usually won't fix a refusal or a token-limit cutoff. If the response is complete, parse it with Pydantic, send the error text back to the model and ask for the whole JSON again. Cap it at two or three attempts, then fail with an error.
The model called several functions at once. How do I return the results?
Return a result for every call and link it to the call ID. At Anthropic, all tool_result blocks go into one user message, before any text, otherwise the model starts making parallel calls less often. At OpenAI, each result is a separate function_call_output item with its own call_id.
Does DeepSeek support structured output with a schema?
Not in Chat Completions: on November 29, 2026 a request with json_schema returned 400, and the documentation lists only text and json_object. In the Responses API, the json_schema format was accepted in the author's check, and the response matched the schema. Another option is strict on functions, which is in beta.