top of page

Claude API "compiled grammar is too large" error: strict tool and schema limits, and how to fix it

4 hours ago
10 min read

Updated: 11 minutes ago

Claude API compiled grammar is too large error: strict tool and schema limits and fixes. Data Studios original cover

Last verified: November 29, 2026


Developers who ask the Claude API for guaranteed JSON, or who mark their tools as strict, sometimes get a request rejected before Claude writes a single word. The API answers with a 400 error saying the compiled grammar is too large and suggesting simpler tool schemas or fewer strict tools. Nothing is wrong with the prompt or the API key. The cause is the size of the schemas sent with the request, which Anthropic turns into a grammar that has to stay under fixed complexity limits.


In most cases the fix is to mark fewer tools as strict and cut optional parameters. Anthropic's documentation sets three explicit limits per request (20 strict tools, 24 optional parameters and 16 parameters with union types, counted across all strict schemas together) plus an internal cap on grammar size that can be reached even when each of those numbers is respected. Anthropic lists structured outputs as available on all Claude models, so the error can appear with any of them, on the Claude API directly and through platforms that forward strict tools, such as Amazon Bedrock and gateways used by agent frameworks, and it has appeared in public bug reports from September to November 2026 as teams added more tools to their agents.


··········


⁣⁣⁣⁣⁣⁣⁣⁣⁣⁣⁣⁣

THE CLAUDE API GRAMMAR ERROR: EXACT MESSAGE AND WHERE IT APPEARS.


The message reported in GitHub issues and pull requests across several projects is the same everywhere, sometimes prefixed with the name of the field that carries the schema. It arrives as an invalid_request_error with HTTP status 400, so retrying the identical request never helps.


output_config.format.schema: Invalid schema: The compiled grammar is too large, which would cause performance issues. Simplify your tool schemas or reduce the number of strict tools.

Anthropic's structured outputs page describes the same condition with different wording. It says that when the complexity limits are exceeded, "you'll receive a 400 error with the message "Schema is too complex for compilation."" The text developers see in practice, and search for, is the "compiled grammar is too large" version, which the documentation does not quote.


........


Where it shows up

How the error looks

Claude API (Messages), direct

400 invalid_request_error with the grammar message

Amazon Bedrock (Converse API)

BedrockException wrapping "The model returned the following errors: The compiled grammar is too large..."

Agent frameworks and SDKs

The framework's own exception with the API message inside, often non-retryable

Your own app

Whatever error text your code shows for a failed 400 request


........


··········


HOW CLAUDE STRUCTURED OUTPUTS TURN A SCHEMA INTO A GRAMMAR.


Claude has two features that force its output to match a JSON Schema. JSON outputs use the output_config.format parameter with type "json_schema" and constrain the text of the reply. Strict tool use adds "strict": true to a tool definition and constrains the tool name and the tool input. Anthropic explains that both work by compiling the schemas into a grammar that limits which tokens Claude can sample, a technique the strict tool use page calls grammar-constrained sampling. Larger schemas produce larger grammars, which take longer to compile, and the API enforces limits to keep compilation times under control.


The limits apply to the combined total across all strict schemas in a single request. Anthropic's own example is four strict tools with six optional parameters each: they reach the 24-parameter limit even though no single tool looks complex.


........


Limit (per request)

Value

What counts

Strict tools

20

Tools with strict: true; non-strict tools do not count

Optional parameters

24

Every parameter not listed in required, across all strict tool schemas and the JSON output schema

Parameters with union types

16

Parameters using anyOf or type arrays such as ["string", "null"], across all strict schemas

Internal grammar size

Not published

Optional parameters, unions, nesting and tool count combined

Compilation timeout

180 seconds

Schemas that pass the explicit checks but compile to a very large grammar


........


The internal limit is the one that surprises people. The documentation says schema complexity "doesn't reduce to a single dimension": optional parameters, union types, nested objects and the number of tools interact, and the compiled grammar can grow disproportionately. A request can therefore fail with all three published numbers satisfied. Anthropic also notes that each optional parameter "roughly doubles a portion of the grammar's state space", and that union types are especially expensive because they create exponential compilation cost.


Compiled grammars are cached for 24 hours from last use, so only the first request with a new schema pays the compilation delay. The cache is invalidated when the schema structure changes or, when JSON outputs and tool use are combined, when the set of tools changes. Changing only name or description fields does not invalidate it.


··········


CAUSES OF THE CLAUDE "COMPILED GRAMMAR IS TOO LARGE" ERROR.


The causes below come from Anthropic's documentation and from bug reports in which developers or maintainers identified what triggered the error and what removed it.


........


Cause

How to check

Fix

More than 20 strict tools in one request

Count tools with strict: true, including those added by your framework

Keep strict only on the tools where a malformed input breaks something

More than 24 optional parameters across all strict schemas

Count properties missing from each required list, summed over every strict tool and the output schema

Make parameters required and let Claude fill a default value

More than 16 union-type parameters

Search the schemas for anyOf and for type arrays like ["string", "null"]

Replace unions with a single type or an enum where possible

Deep nesting with optional fields

Look for objects inside objects whose fields are optional

Flatten the structure

A framework sets strict on every tool

Log the raw request body and look for "strict": true on tools you never marked

Change the framework setting or upgrade to a fixed version

Large generated output schema

Convert your Zod or Pydantic model to JSON Schema and count optional fields

Remove optional and fallback fields, or split the schema

Combined size over the internal cap

All published limits respected but the error persists

Reduce strict tools further, or split work across requests


........


Several reports show the last cause in practice. In one open-source project merged on October 12, 2026, ten strict tools were enough to trigger the error on Claude Opus 5.5 and Sonnet 5.5, and the fix was to remove strict from three of them, bringing the count back to seven while leaving their schemas unchanged. In another, closed on November 16, 2026, the application sent strict on every tool and one large request schema compiled past the limit; the maintainer stopped sending strict to Anthropic and kept validating inputs in the application instead.


··········


[[ADPLUS_300x250_1]]

STEP-BY-STEP FIXES FOR CLAUDE STRICT TOOLS AND JSON SCHEMAS.


Anthropic lists four strategies to apply in order. The steps below follow that order and add the checks that make each one measurable.


1. Capture the exact request your code sends. Frameworks often rewrite tool definitions, so log the final JSON body (tools, input_schema, output_config) rather than reading your own source code.


2. Count the three published quantities across the whole request: strict tools, optional parameters and union-type parameters. The script below is an illustrative helper written for this page (Anthropic does not provide one); it walks the request body and adds up the same things the limits describe.


# Illustrative helper: counts what Anthropic's published limits measure
def count_schema(schema, totals):
    if not isinstance(schema, dict):
        return
    props = schema.get("properties", {})
    required = set(schema.get("required", []))
    for name, sub in props.items():
        if name not in required:
            totals["optional"] += 1
        if "anyOf" in sub or isinstance(sub.get("type"), list):
            totals["unions"] += 1
        count_schema(sub, totals)
    if isinstance(schema.get("items"), dict):
        count_schema(schema["items"], totals)
    for branch in schema.get("anyOf", []):
        count_schema(branch, totals)

def count_request(body):
    totals = {"strict_tools": 0, "optional": 0, "unions": 0}
    for tool in body.get("tools", []):
        if tool.get("strict"):
            totals["strict_tools"] += 1
            count_schema(tool.get("input_schema", {}), totals)
    fmt = body.get("output_config", {}).get("format", {})
    if fmt.get("type") == "json_schema":
        count_schema(fmt.get("schema", {}), totals)
    return totals  # compare with 20 / 24 / 16

3. Mark only critical tools as strict. Anthropic's advice is to reserve strict tool use for tools "where schema violations cause real problems" and rely on Claude's natural adherence for simpler ones. Non-strict tools do not count toward the 20-tool limit, and their schemas stay out of the grammar. Read-only lookups are usually the first candidates to lose strict; tools that write to a database or send messages are the ones to keep.


4. Reduce optional parameters. Move parameters into required wherever a sensible default exists and describe that default in the parameter description, so Claude provides it explicitly. Avoid turning an optional parameter into a required one with a type array such as ["string", "null"], because that trades one optional parameter for one union parameter, which Anthropic describes as the more expensive kind.


5. Simplify nested structures. Deeply nested objects with optional fields compound the problem, so flatten them where possible: a single object with prefixed field names compiles to a smaller grammar than three layers of optional sub-objects.


6. Split the work. If an agent needs many strict tools, divide them across separate requests or subagents, each with a smaller toolset. The same applies to a very large JSON output schema, which can often be produced in two passes.


7. Retest after every change, keeping in mind that the first request with a new schema includes compilation time and later identical requests use the 24-hour cache. If valid schemas keep failing after these steps, Anthropic's documentation points to its support channel.


For reference, this is how Anthropic's quick start defines a strict tool. Note the required list and "additionalProperties": False on the object schema; the unit parameter is the only optional one.


response = client.messages.create(
    model="claude-opus-5-5",
    max_tokens=1024,
    messages=[{"role": "user", "content": "What's the weather like in San Francisco?"}],
    tools=[
        {
            "name": "get_weather",
            "description": "Get the current weather in a given location",
            "strict": True,  # Enable strict mode
            "input_schema": {
                "type": "object",
                "properties": {
                    "location": {
                        "type": "string",
                        "description": "The city and state, e.g. San Francisco, CA",
                    },
                    "unit": {
                        "type": "string",
                        "enum": ["celsius", "fahrenheit"],
                        "description": "The unit of temperature, either 'celsius' or 'fahrenheit'",
                    },
                },
                "required": ["location"],
                "additionalProperties": False,
            },
        }
    ],
)

··········


FRAMEWORKS AND GATEWAYS THAT SEND STRICT CLAUDE TOOLS FOR YOU.


Many of the reports come from developers who never wrote "strict": true themselves. Their framework added it, or forwarded it to a platform with the same limits. The status below is what each project's maintainers wrote in their own issue trackers.


........


Framework or gateway

What triggered the error

Status reported by maintainers

Agno 2.6.4

parser_model setups still forced every agent tool into strict mode (repro with 15 tools)

A maintainer wrote it "has been fixed for both agents and teams and will be out with the next release"

LiteLLM with Bedrock Converse

20+ strict tools on Claude Sonnet 4.6 rejected by Bedrock

A first fix was closed as superseded by a change that "retries once without strict under drop_params"

TanStack AI via OpenRouter

Large nested Zod output schema with many optional and fallback fields

Open; an agreed design adds an automatic fallback to a forced-tool path

Vercel AI SDK

8 strict tools failed on direct Anthropic but passed through AI Gateway

Closed: a maintainer found both paths now return the same error


........


When the error appears only after upgrading a framework or adding a feature such as structured output parsing, compare the raw request bodies of the old and new versions. A jump in the number of strict tools is the most common difference in these reports.


··········


⁣⁣⁣⁣⁣⁣⁣⁣⁣⁣⁣⁤

WHAT ANTHROPIC DOCUMENTS ABOUT CLAUDE GRAMMAR LIMITS AND WHAT DEVELOPERS REPORT.


Documented by Anthropic: the three explicit limits, the existence of an internal grammar-size limit, the 180-second compilation timeout, the 24-hour grammar cache and what invalidates it, the four strategies for reducing complexity, and that JSON outputs and strict tool use share the same JSON Schema limitations. Anthropic also states that changing output_config.format invalidates any prompt cache for that conversation thread, which matters for cost when you edit schemas between turns.


Reported by developers and not documented: the exact wording "The compiled grammar is too large"; failures with as few as seven to ten strict tools, well under 20, in at least two projects; and the observation in one project that the error appeared with web search enabled and the same strict tools, which its maintainer handled by telling users to turn web search off. One developer also suspected that long description fields enlarge the grammar. Anthropic has not confirmed that, and its documentation only says that changing descriptions does not invalidate the grammar cache, so trimming descriptions belongs after the documented steps, as an experiment.


Anthropic does not publish the internal size threshold, and none of the public issues contains a staff answer giving one. The practical consequence is that the published numbers are ceilings, and a request well below them can still fail when unions, nesting and optional fields pile up.


··········


KEEPING CLAUDE SCHEMAS UNDER THE LIMIT AFTER CHANGES.


The strict budget belongs to the whole request. A new tool added by one team can push an agent that worked yesterday over the limit, because the optional-parameter and union counts are summed across everything strict in the same call. A test that builds the full request for each agent configuration and runs the counting helper above catches most of these regressions before deployment; one project pinned its maximum number of strict tools in a test for exactly this reason.


It also helps to keep a single owner for the output schema. Generated schemas from Zod or Pydantic grow silently as fields are added, and fields marked optional "just in case" are the most expensive kind for the grammar. Finally, after any schema change, expect the first request to be slower while the new grammar compiles, and expect prompt caching to restart if you changed output_config.format.



··········


CLAUDE GRAMMAR ERROR: WHAT TO CHANGE FIRST.


The "compiled grammar is too large" response is a size problem in the schemas attached to a request, and it is solved by sending less to the grammar compiler. Removing strict from tools that do not need it is the fastest change and the one that resolved most of the public reports; cutting optional parameters, avoiding union types and flattening nested objects come next. Frameworks are a frequent hidden source, so the raw request body is the first thing to inspect. Because Anthropic keeps the internal threshold unpublished, the safest working assumption is to stay clearly below 20 strict tools, 24 optional parameters and 16 unions, and to test the full request every time a tool or schema changes.


··········


FOLLOW US FOR MORE.


·····


DATA STUDIOS


·····


datastudios.org


bottom of page