{"record":{"id":"943b6d8e6e8bbec4","repo":"BerriAI/litellm","slug":"unpack-defs-inlined-schema-exceeded-the-max-inli","errorCode":null,"errorMessage":"unpack_defs: inlined schema exceeded the {max_inlined_bytes:,}-byte budget. Refusing to deep-copy further to prevent schema-bomb resource exhaustion.","messagePattern":"unpack_defs: inlined schema exceeded the (.+?)-byte budget\\. Refusing to deep-copy further to prevent schema-bomb resource exhaustion\\.","errorType":"validation","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"litellm/litellm_core_utils/prompt_templates/common_utils.py","lineNumber":943,"sourceCode":"        if isinstance(node, dict):\n            # --- Case 1: this node *is* a reference ---\n            if \"$ref\" in node:\n                ref_name = node[\"$ref\"].split(\"/\")[-1]\n\n                # Check for circular reference in the resolution chain\n                if ref_name in ref_chain:\n                    # Circular reference detected - leave as-is to prevent infinite recursion\n                    continue\n\n                target_schema = active_defs.get(ref_name)\n                # Unknown reference – leave untouched\n                if target_schema is None:\n                    continue\n\n                if max_inlined_bytes is not None:\n                    inlined_bytes += _estimate_json_bytes(target_schema)\n                    if inlined_bytes > max_inlined_bytes:\n                        raise ValueError(\n                            f\"unpack_defs: inlined schema exceeded the \"\n                            f\"{max_inlined_bytes:,}-byte budget. Refusing to \"\n                            f\"deep-copy further to prevent schema-bomb \"\n                            f\"resource exhaustion.\"\n                        )\n\n                # Merge defs from the target to capture nested definitions\n                child_defs = {\n                    **active_defs,\n                    **target_schema.get(\"$defs\", {}),\n                    **target_schema.get(\"definitions\", {}),\n                }\n\n                # Replace the reference with resolved copy\n                resolved = copy.deepcopy(target_schema)\n                if parent is not None and key is not None:\n                    if (\n                        isinstance(parent, dict)","sourceCodeStart":925,"sourceCodeEnd":961,"githubUrl":"https://github.com/BerriAI/litellm/blob/77b7c6c40c0c5aa5fbcb1d6a1825ac39ca8829b8/litellm/litellm_core_utils/prompt_templates/common_utils.py#L925-L961","documentation":"litellm inlines $defs/definitions references in tool JSON schemas for providers that cannot resolve $ref. To stop a schema-bomb (a small schema whose recursive or repeated refs expand enormously when deep-copied), it accumulates an estimated byte count of every inlined def and raises once the running total exceeds max_inlined_bytes. The raise happens before the deep-copy, so the process is protected from unbounded memory growth.","triggerScenarios":"Calling a tool-calling provider with a function whose parameters schema contains $refs whose expansion exceeds the byte budget: a large nested Pydantic model exported via model_json_schema(), a schema referencing the same large def many times, or recursive/self-referencing models whose refs fan out during inlining.","commonSituations":"Auto-generating tool schemas from big Pydantic models; deeply nested Optional/List generics creating reference fan-out; upgrading litellm to a version that introduced this budget check on a previously-working schema.","solutions":["Simplify the tool schema: trim or flatten the Pydantic model so the inlined defs stay under the budget","Split one large schema into several smaller tools","Remove circular/self-references from the model (e.g. replace recursive models with plain dict fields)","If your call site exposes it, raise max_inlined_bytes (check the unpack_defs caller for the knob) for trusted schemas"],"exampleFix":"# before: recursive model expands unboundedly when inlined\nclass Node(BaseModel):\n    children: list[\"Node\"] = []\n\n# after: bounded, non-recursive schema\nclass Node(BaseModel):\n    children: list[dict] = []","handlingStrategy":"validation","validationCode":"import json\n\ndef estimate_inlined_schema_bytes(schema: dict, budget: int = 100_000) -> int:\n    \"\"\"Rough check: sum of $defs sizes that inlining would copy.\"\"\"\n    defs = {**schema.get(\"$defs\", {}), **schema.get(\"definitions\", {})}\n    total = 0\n    for ref_name, count in count_ref_usage(schema):\n        target = defs.get(ref_name)\n        if target is not None:\n            total += count * len(json.dumps(target).encode())\n    return total\n\ndef count_ref_usage(node, counts=None, stack=None):\n    counts, stack = counts or {}, stack or []\n    if isinstance(node, dict):\n        ref = node.get(\"$ref\")\n        if isinstance(ref, str) and ref.startswith(\"#/$defs/\"):\n            name = ref.split(\"/\")[-1]\n            counts[name] = counts.get(name, 0) + 1\n        for v in node.values():\n            count_ref_usage(v, counts, stack)\n    elif isinstance(node, list):\n        for v in node:\n            count_ref_usage(v, counts, stack)\n    return counts\n\n# before the call:\n# if estimate_inlined_schema_bytes(tool[\"function\"][\"parameters\"]) > budget: simplify the tool","typeGuard":null,"tryCatchPattern":"try:\n    litellm.completion(model=model, messages=messages, tools=tools)\nexcept ValueError as e:\n    if str(e).startswith(\"unpack_defs: inlined schema exceeded\"):\n        # schema too large to inline: split or simplify the tool, then retry\n        tools = split_tool_schema(tools)\n    else:\n        raise","preventionTips":["Keep tool parameter models shallow - prefer several small tools over one giant schema","Avoid recursive Pydantic models in tool schemas; replace self-references with dict","When generating schemas from Pydantic, strip optional nested defs you do not actually need","Track schema size in CI: fail builds whose tool schemas exceed your inlining budget"],"tags":["json-schema","tool-calling","resource-limits","defs"],"backgroundTag":"json-schema-inlining-budget-exceeded","analyzedSha":"77b7c6c40c0c5aa5fbcb1d6a1825ac39ca8829b8","analyzedAt":"2026-08-18T11:44:31.656Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}