LocalAI icon indicating copy to clipboard operation
LocalAI copied to clipboard

response_format: json_schema` drops `$defs`, so schemas using `$ref` silently fall back to unconstrained output

Open toat opened this issue 2 weeks ago • 1 comments

LocalAI version:

Container image localai/localai:master-gpu-vulkan:

  • revision 886b772a6ba11ad9b64101fb802c9c1c5c63f72c (built 2026-11-19)
  • also reproduced on ce85d2905421dd2ec7d35ce8b526e8fb507bd366 (built 2026-10-30)

Environment, CPU architecture, OS, and Version:

Linux gfx906 7.0.14-26-pve #1 SMP PREEMPT_DYNAMIC PMX 7.0.14-26 (2026-10-22T18:45Z) x86_64 GNU/Linux
  • Debian 13 (trixie) LXC container on Proxmox VE, Docker 29.9.2
  • CPU: Intel Core i7-7700T (4 vCPU allocated)
  • GPU: AMD Radeon gfx906 (Vega 20, PCI ID 1002:66a1), Vulkan backend
  • Backend: llama-cpp, model Gemma 4 E4B (gemma-4-e4b-it-qat-mtp)

Describe the bug

When a chat completion uses response_format with type: json_schema and the schema contains a $ref to #/$defs/..., LocalAI fails to build the grammar and logs no definitions found in the schema. The request then proceeds without any grammar: the output is unconstrained free text and does not follow the schema. No error is returned to the client (HTTP 200).

This is the default schema shape produced by Pydantic and by the OpenAI Python SDK (response_format=<PydanticModel>) as soon as a model contains nested models, so many clients are affected.

The same schema with the $ref inlined works as expected (same model, same prompt).

As far as I can tell, the cause is in core/schema/openai.go:

type JsonSchema struct {
	Name   string         `json:"name"`
	Strict bool           `json:"strict"`
	Schema functions.Item `json:"schema"`
}

functions.Item only keeps type and properties, so the top-level $defs (as well as required and additionalProperties) is discarded during unmarshalling. Then in core/http/endpoints/openai/chat.go:

fs := &functions.JSONFunctionStructure{
	AnyOf: []functions.Item{d.JsonSchema.Schema},
}

JSONFunctionStructure.Defs is never set, so resolveReference() in pkg/functions/grammars/json_schema.go cannot find $defs and fails. The code is unchanged on master at the time of writing.

To Reproduce

  1. Run LocalAI with any llama.cpp chat model.
  2. Send this request:
curl http://localhost:8080/v1/chat/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $LOCALAI_API_KEY" \
  -d '{
    "model": "gemma-4-e4b-it-qat-mtp",
    "messages": [{"role": "user", "content": "Give me a tomato salad recipe with its ingredients."}],
    "response_format": {
      "type": "json_schema",
      "json_schema": {
        "name": "Recipe",
        "strict": true,
        "schema": {
          "type": "object",
          "properties": {
            "name": {"type": "string"},
            "ingredients": {"type": "array", "items": {"$ref": "#/$defs/Ingredient"}}
          },
          "required": ["name", "ingredients"],
          "additionalProperties": false,
          "$defs": {
            "Ingredient": {
              "type": "object",
              "properties": {"text": {"type": "string"}},
              "required": ["text"],
              "additionalProperties": false
            }
          }
        }
      }
    }
  }'
  1. The response is HTTP 200, but the content is free-form Markdown instead of JSON:
This classic tomato salad (often referred to as *Bruschetta Salad* or *Caprese Style* [...]) is incredibly fresh, healthy, and requires minimal effort.

Here is a recipe for a **Simple, Balsamic Tomato Salad**.

## 🍅 Simple Summer Tomato Salad
[...]
  1. Control: send the same request with {"$ref": "#/$defs/Ingredient"} replaced by the inline Ingredient object and $defs removed. The output is correctly constrained valid JSON, e.g. {"ingredients": [{"text": "Ripe tomatoes ..."}, ...], "name": "..."}.

Expected behavior

  • $ref to #/$defs/... is resolved against the root schema and the output is constrained by the grammar, as with the inlined schema.
  • If grammar generation fails for an explicit json_schema request, LocalAI should return an error (or at least make the fallback visible to the client) rather than silently generating unconstrained output.

Suggested fix: keep the full schema instead of decoding it into functions.Item (e.g. Schema map[string]any), and pass its $defs to JSONFunctionStructure.Defs.

Logs

Logged at default level (no --debug) for the request above:

ERROR Failed generating grammar error=no definitions found in the schema: map[anyOf:[map[properties:map[ingredients:map[items:map[$ref:#/$defs/Ingredient] type:array] name:map[type:string]] type:object]]] caller={caller.file="/build/core/http/endpoints/openai/chat.go"  caller.L=492 }

The schema printed in the error has already lost $defs, required and additionalProperties, which matches the functions.Item truncation described above.

Additional context

Real-world impact: Mealie v3.31.0 uses response_format=<PydanticModel> for AI recipe import. Its OpenAIRecipe schema references nested models through $defs, so recipe import always fails with LocalAI ("Recipe creation failed", with Pydantic validation errors such as ingredients.0 model_type and name missing).

Reproduced both directly against LocalAI and through a LiteLLM proxy.

toat avatar Nov 19 '26 10:11 toat

The $ref and $defs part is fixed on master by commit b79fd369a7 and will be in the next release. Still open: when grammar generation fails for a json_schema request, LocalAI still answers with unconstrained text instead of an error.

mudler-agent avatar Dec 01 '26 17:12 mudler-agent