JSON grammar allows unescaped control characters inside strings
LocalAI version:
v5.0.1-349-g05eb448aa (commit 05eb448aada6274ed10ba37b9349e0a7149bea9e), with the changes from PR #13312 applied.
Environment, CPU architecture, OS, and Version:
- Architecture:
linux/amd64 - Container base: Ubuntu 24.04
- Host: Debian 13 LXC
- CPU: Intel Core i7-7700T
- GPU: AMD gfx906 (
1002:66a1), Vulkan backend
Describe the bug
When using response_format: { "type": "json_schema", ... }, LocalAI generates a grammar for the schema. The generated string rule appears to allow raw control characters (U+0000–U+001F) inside JSON strings.
The model can therefore return a literal newline inside a string value. The response is not valid JSON, even though constrained generation was requested, and clients such as Mealie reject it while parsing the response.
In pkg/functions/grammars/bnf_rules.go, the current rule contains:
[^"\\]
This does not exclude control characters. llama.cpp's JSON grammar excludes them with a rule equivalent to:
[^"\\\x7F\x00-\x1F]
To Reproduce
- Use a model that supports grammar-constrained generation.
- Send a chat completion request with
response_format.typeset tojson_schema, and a schema containing string fields. - Use a prompt that encourages multiline text in one of those fields.
- Inspect the returned
message.contentfor literal newline characters inside a JSON string, rather than escaped\n.
Example request shape:
{
"model": "YOUR_MODEL",
"messages": [
{
"role": "user",
"content": "Return a recipe. Put a line break in the description."
}
],
"response_format": {
"type": "json_schema",
"json_schema": {
"name": "example",
"schema": {
"type": "object",
"properties": {
"description": { "type": "string" }
},
"required": ["description"]
}
}
}
}
The issue was observed with gemma-4-e4b-it-qat-mtp through the OpenAI-compatible /v1/chat/completions endpoint.
Expected behavior
The generated grammar should prohibit unescaped control characters inside JSON strings, so the model either escapes them (for example, as \n) or produces valid JSON without them. The returned content should parse as JSON.
Logs
The consuming application reported:
Invalid JSON: control character (\u0000-\u001F) found while parsing a string at line 2 column 0
LocalAI's logs showed that a grammar was generated and used (Grammar provided from Go layer), so the request was constrained; nevertheless, the response contained a raw line break inside a string.
Additional context
This was observed after applying PR #13312, which preserves $defs in json_schema response formats and allows grammar generation for the affected schema. That PR fixes the earlier “no definitions found in the schema” failure, but it does not appear to address raw control characters in JSON string values.