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

> Function calling vs structured output: which JSON Schema subset Claude, OpenAI, Gemini and DeepSeek accept, what strict mode guarantees, and Pydantic retries.
> Author: Roman Belov · Published: 2026-10-04 · Source: https://futurecraft.pro/blog/function-calling-structured-output/

**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 calling | Structured output |
|---|---|---|
| What the model returns | a function name and arguments | response text that is valid against the schema |
| What happens next | code runs the function and returns the result to the model | code parses the JSON, the conversation can end there |
| Typical task | an action, a data lookup, an agent step | field extraction, classification, a report |
| Can the model skip the format | yes, with `auto` it may answer in text | no, except for refusals and cutoffs |
| Claude | `tools`, `tool_use` | `output_config.format` |
| OpenAI | `tools`, `function_call` | `text.format` or `response_format` |
| Gemini | `functionDeclarations`, `functionCall` | `response_json_schema` |

[Google's documentation](https://aistudio.google.com/docs/structured-output?generate-content=true) 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:

```text
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](https://developers.openai.com/api/docs/guides/function-calling), 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](https://aistudio.google.com/docs/thought-signatures?generate-content=true)). 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](https://futurecraft.pro/blog/claude-api-developer-guide/), and the choice between your own functions and a separate server is covered in [MCP vs API](https://futurecraft.pro/blog/mcp-vs-api/).

## JSON Schema: what each vendor supports

| | Claude | OpenAI | Gemini (`generateContent`) | DeepSeek (strict, beta) |
|---|---|---|---|---|
| All fields in `required` | not needed, but up to 24 optional ones per request | required | not needed | required |
| `additionalProperties: false` | required | required | not needed | required |
| `anyOf` | yes | yes, but not at the root | yes | yes |
| `oneOf` / `allOf` / `not` | no / with caveats / no | not listed / no / no | not listed | not listed |
| Recursion | no | yes | yes, the reference must be optional | yes, via `$ref` |
| `minimum`, `maximum` | no, 400 | yes | yes | yes |
| `minLength`, `maxLength` | no, 400 | not in the supported list | silently ignored | not supported |
| `minItems`, `maxItems` | only `minItems` 0 or 1 | yes | yes | not supported |

Sources: [Claude](https://platform.claude.com/docs/en/build-with-claude/structured-outputs), [OpenAI](https://developers.openai.com/api/docs/guides/structured-outputs), [Gemini](https://aistudio.google.com/docs/structured-output), [DeepSeek](https://api-docs.deepseek.com/guides/tool_calls). 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:

```python
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](https://platform.claude.com/docs/en/agents-and-tools/tool-use/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 call | Specific function | One call per turn |
|---|---|---|---|
| Claude | `any` | `tool` + name | `disable_parallel_tool_use` inside `tool_choice` |
| OpenAI | `required` | object with the name | `parallel_tool_calls: false` |
| Gemini | `ANY` | `ANY` + `allowed_function_names` | no separate parameter in the mode descriptions |
| DeepSeek | `required` | object with the name | ignored in Responses |

On Claude Opus 5.5, Sonnet 5.5, Fable 5.2 and Fable 5.1, the values `any` and `tool` [return 400](https://platform.claude.com/docs/en/api/errors#forced-tool-use-not-supported) 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](https://api-docs.deepseek.com/api/create-chat-completion) 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](https://openrouter.ai/docs/guides/features/structured-outputs) 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](https://futurecraft.pro/blog/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" prompt | `json_schema` strict | function | function strict |
|---|---|---|---|---|
| Claude Haiku 5.5 | 15 (7 fenced) | 15 | 15 | 15 |
| GPT-6 Luna | 15 | 15 | 15 | 15 |
| DeepSeek V4.1 Flash 1017 | 15 (9 fenced) | 15 | 15 | 15 |
| Gemini 3.7 Flash | 15 (14 fenced) | 15 | 15 | 15 |
| Qwen3 Coder | 15 (5 fenced) | 15 | 12 (3: date format) | 12 (3: date format) |
| Mistral Small 3.2 24B | 12 (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

| Symptom | Cause | What to do |
|---|---|---|
| 400 on `tool_choice` with Claude | the model doesn't accept `any` and `tool` | `auto` + `strict`, or structured output |
| Claude stopped calling in parallel | results in different messages | one message, results before text |
| 400 on Gemini 3 history | thought signature lost | return response parts unchanged |
| 400 about the schema | `oneOf`, recursion, bounds (Claude), `allOf` (OpenAI), complexity (Gemini) | simplify, move bounds to the description and code |
| An optional field is rejected by OpenAI | in strict all fields are required | `required` and a type with `null` |
| Truncated JSON | low token limit, reasoning used part of it | check the stop reason, raise the limit |
| Empty DeepSeek response with `stop` | per the documentation, non-JSON is replaced with whitespace | the word json in the prompt, retry |
| A function outside the list is called | the executor trusts the name | check 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:

```python
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`):

```python
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:

```python
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](https://futurecraft.pro/blog/mcp-security-guide/), and the agent loop in the [AI agents guide](https://futurecraft.pro/blog/ai-agents-complete-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.
