BerriAI/litellm · error · ValueError

unpack_defs: inlined schema exceeded the

Error message

unpack_defs: inlined schema exceeded the {max_inlined_bytes:,}-byte budget. Refusing to deep-copy further to prevent schema-bomb resource exhaustion.

What it means

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.

Solutions

  1. Simplify the tool schema: trim or flatten the Pydantic model so the inlined defs stay under the budget
  2. Split one large schema into several smaller tools
  3. Remove circular/self-references from the model (e.g. replace recursive models with plain dict fields)
  4. If your call site exposes it, raise max_inlined_bytes (check the unpack_defs caller for the knob) for trusted schemas

Example fix

# before: recursive model expands unboundedly when inlined
class Node(BaseModel):
    children: list["Node"] = []

# after: bounded, non-recursive schema
class Node(BaseModel):
    children: list[dict] = []
Defensive patterns

Strategy: validation

Validate before calling

import json

def estimate_inlined_schema_bytes(schema: dict, budget: int = 100_000) -> int:
    """Rough check: sum of $defs sizes that inlining would copy."""
    defs = {**schema.get("$defs", {}), **schema.get("definitions", {})}
    total = 0
    for ref_name, count in count_ref_usage(schema):
        target = defs.get(ref_name)
        if target is not None:
            total += count * len(json.dumps(target).encode())
    return total

def count_ref_usage(node, counts=None, stack=None):
    counts, stack = counts or {}, stack or []
    if isinstance(node, dict):
        ref = node.get("$ref")
        if isinstance(ref, str) and ref.startswith("#/$defs/"):
            name = ref.split("/")[-1]
            counts[name] = counts.get(name, 0) + 1
        for v in node.values():
            count_ref_usage(v, counts, stack)
    elif isinstance(node, list):
        for v in node:
            count_ref_usage(v, counts, stack)
    return counts

# before the call:
# if estimate_inlined_schema_bytes(tool["function"]["parameters"]) > budget: simplify the tool

Try / catch

try:
    litellm.completion(model=model, messages=messages, tools=tools)
except ValueError as e:
    if str(e).startswith("unpack_defs: inlined schema exceeded"):
        # schema too large to inline: split or simplify the tool, then retry
        tools = split_tool_schema(tools)
    else:
        raise

Prevention

When it happens

Trigger: 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.

Common situations: 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.

Related errors


AI-assisted analysis of BerriAI/litellm@77b7c6c40c (2026-08-18). Data as JSON: /api/errors/943b6d8e6e8bbec4. Report an issue: GitHub.

Appendix: source

Thrown at litellm/litellm_core_utils/prompt_templates/common_utils.py:943

        if isinstance(node, dict):
            # --- Case 1: this node *is* a reference ---
            if "$ref" in node:
                ref_name = node["$ref"].split("/")[-1]

                # Check for circular reference in the resolution chain
                if ref_name in ref_chain:
                    # Circular reference detected - leave as-is to prevent infinite recursion
                    continue

                target_schema = active_defs.get(ref_name)
                # Unknown reference – leave untouched
                if target_schema is None:
                    continue

                if max_inlined_bytes is not None:
                    inlined_bytes += _estimate_json_bytes(target_schema)
                    if inlined_bytes > max_inlined_bytes:
                        raise ValueError(
                            f"unpack_defs: inlined schema exceeded the "
                            f"{max_inlined_bytes:,}-byte budget. Refusing to "
                            f"deep-copy further to prevent schema-bomb "
                            f"resource exhaustion."
                        )

                # Merge defs from the target to capture nested definitions
                child_defs = {
                    **active_defs,
                    **target_schema.get("$defs", {}),
                    **target_schema.get("definitions", {}),
                }

                # Replace the reference with resolved copy
                resolved = copy.deepcopy(target_schema)
                if parent is not None and key is not None:
                    if (
                        isinstance(parent, dict)

View on GitHub (pinned to 77b7c6c40c)