decision: fix JSON state prompts for MLX decision models (#18974)

* renderers: add Python json.dumps serializer

* decision: render JSON states like the publishers' json.dumps
This commit is contained in:
Jeffrey Morgan authored and GitHub committed 2026-10-13 12:43:30 -07:00
1 parent 7a5ae12ead
commit c185cf5dc5
9 files changed
+283 -204

No files matched your search

+4 -92
View File
@@ -5,13 +5,13 @@ import (
"encoding/json"
"fmt"
"maps"
"math"
"slices"
"strconv"
"strings"
"github.com/ollama/ollama/internal/orderedmap"
"github.com/ollama/ollama/llm"
"github.com/ollama/ollama/model/renderers"
)
// encodeClef preserves the reference encoder's JSON and segment boundaries,
@@ -50,7 +50,7 @@ func encodeClef(req Request, c *Compiled) error {
if option.Description != nil {
semantics["description"] = option.Description
}
raw, err := clefJSON(semantics)
raw, err := renderers.PythonJSONCompact(semantics)
if err != nil {
return err
}
@@ -162,6 +162,7 @@ func clefValue(raw json.RawMessage) (any, error) {
return value, err
}
// encoding/json sorts map keys, as Clef's reference does.
func clefContent(raw json.RawMessage) (string, error) {
value, err := clefValue(raw)
if err != nil {
@@ -170,94 +171,5 @@ func clefContent(raw json.RawMessage) (string, error) {
if s, ok := value.(string); ok {
return s, nil
}
return clefJSON(value)
}
// clefJSON matches Python's json.dumps(ensure_ascii=False, sort_keys=True,
// separators=(",", ":")), including its integer/float distinction.
// encoding/json sorts map keys, but its number and Unicode escaping rules
// differ from the reference and would change the model's input tokens.
func clefJSON(value any) (string, error) {
switch v := value.(type) {
case nil:
return "null", nil
case bool:
return strconv.FormatBool(v), nil
case string:
var b strings.Builder
b.WriteByte('"')
for _, r := range v {
switch r {
case '"', '\\':
b.WriteByte('\\')
b.WriteRune(r)
case '\b':
b.WriteString(`\b`)
case '\f':
b.WriteString(`\f`)
case '\n':
b.WriteString(`\n`)
case '\r':
b.WriteString(`\r`)
case '\t':
b.WriteString(`\t`)
default:
if r < 0x20 {
fmt.Fprintf(&b, `\u%04x`, r)
} else {
b.WriteRune(r)
}
}
}
b.WriteByte('"')
return b.String(), nil
case json.Number:
if !strings.ContainsAny(string(v), ".eE") {
if v == "-0" {
return "0", nil
}
return string(v), nil
}
n, err := v.Float64()
if math.IsInf(n, 0) {
if n < 0 {
return "-Infinity", nil
}
return "Infinity", nil
}
if err != nil {
return "", err
}
if a := math.Abs(n); a >= 1e16 || (a != 0 && a < 1e-4) {
return strconv.FormatFloat(n, 'e', -1, 64), nil
}
s := strconv.FormatFloat(n, 'f', -1, 64)
if !strings.ContainsRune(s, '.') {
s += ".0"
}
return s, nil
case []any:
parts := make([]string, len(v))
for i, child := range v {
text, err := clefJSON(child)
if err != nil {
return "", err
}
parts[i] = text
}
return "[" + strings.Join(parts, ",") + "]", nil
case map[string]any:
parts := make([]string, 0, len(v))
for _, key := range slices.Sorted(maps.Keys(v)) {
name, _ := clefJSON(key)
text, err := clefJSON(v[key])
if err != nil {
return "", err
}
parts = append(parts, name+":"+text)
}
return "{" + strings.Join(parts, ",") + "}", nil
default:
return "", fmt.Errorf("unsupported JSON value %T", value)
}
return renderers.PythonJSONCompact(value)
}
+10 -42
View File
@@ -1,7 +1,6 @@
package decision
import (
"bytes"
"encoding/json"
"fmt"
"strings"
@@ -9,7 +8,7 @@ import (
"github.com/ollama/ollama/model/renderers"
)
func decisionPrompts(context string, fields []compiledField, renderer string) ([]string, error) {
func decisionPrompts(state json.RawMessage, context string, fields []compiledField, renderer string) ([]string, error) {
var prompts []string
if renderer == "tev1" {
for _, f := range fields {
@@ -39,11 +38,12 @@ func decisionPrompts(context string, fields []compiledField, renderer string) ([
}
options = append(options, option{c.Code, fmt.Sprint(c.Value), description})
}
prompt, err := promptJSON(struct {
State string `json:"state"`
Question string `json:"question"`
Options []option `json:"options"`
}{context, f.Description, options})
// Tev1 was trained with object states nested in the payload.
prompt, err := renderers.PythonJSON(struct {
State json.RawMessage `json:"state"`
Question string `json:"question"`
Options []option `json:"options"`
}{state, f.Description, options}, 0)
if err != nil {
return nil, err
}
@@ -52,17 +52,17 @@ func decisionPrompts(context string, fields []compiledField, renderer string) ([
return prompts, nil
}
data, err := promptJSON(struct {
data, err := renderers.PythonJSON(struct {
Context string `json:"context"`
Schema []compiledField `json:"schema"`
}{context, fields})
}{context, fields}, 0)
if err != nil {
return nil, err
}
// Nimble escapes chat delimiters in both the schema and the requested name.
escape := strings.NewReplacer("<", `\u003c`, ">", `\u003e`)
for _, f := range fields {
name, err := promptJSON(f.Name)
name, err := renderers.PythonJSON(f.Name, 0)
if err != nil {
return nil, err
}
@@ -70,35 +70,3 @@ func decisionPrompts(context string, fields []compiledField, renderer string) ([
}
return prompts, nil
}
// Both publishers serialize prompts with Python's json.dumps(ensure_ascii=False).
func promptJSON(v any) (string, error) {
var b bytes.Buffer
enc := json.NewEncoder(&b)
enc.SetEscapeHTML(false)
if err := enc.Encode(v); err != nil {
return "", err
}
data := renderers.AddJSONSpaces(bytes.TrimSuffix(b.Bytes(), []byte{'\n'}))
var out strings.Builder
for i := 0; i < len(data); i++ {
// encoding/json always escapes these two runes. Leave literal backslash
// sequences alone by consuming each escape as a unit.
if data[i] == '\\' && i+1 < len(data) {
if bytes.HasPrefix(data[i:], []byte(`\u2028`)) {
out.WriteRune('\u2028')
i += 5
continue
}
if bytes.HasPrefix(data[i:], []byte(`\u2029`)) {
out.WriteRune('\u2029')
i += 5
continue
}
out.WriteByte(data[i])
i++
}
out.WriteByte(data[i])
}
return out.String(), nil
}
+2 -6
View File
@@ -34,10 +34,6 @@ func TestPublisherPrompts(t *testing.T) {
}
})
}
got, err := promptJSON("\u2028\u2029\\u2028\\u2029")
if want := "\"\u2028\u2029\\\\u2028\\\\u2029\""; err != nil || got != want {
t.Fatalf("Unicode escaping = %q, %v; want %q", got, err, want)
}
}
func TestTevQuestions(t *testing.T) {
@@ -53,7 +49,7 @@ func TestTevQuestions(t *testing.T) {
descriptions := [][]string{{"Charges and refunds", "technical"}, {"No", "Yes"}, {"Routine", "Urgent", "Emergency"}}
for i, row := range compiled.Request.Rows {
var payload struct {
State string
State json.RawMessage
Question string
Options []struct{ Label, Key, Description string }
}
@@ -61,7 +57,7 @@ func TestTevQuestions(t *testing.T) {
t.Fatal(err)
}
f := compiled.fields[i]
if payload.State != `{"frames":["first","second"]}` || payload.Question != f.Description || len(payload.Options) != len(f.Choices) {
if string(payload.State) != `{"frames": ["first", "second"]}` || payload.Question != f.Description || len(payload.Options) != len(f.Choices) {
t.Fatalf("question %d was not compiled independently: %s", i, row.Prompt)
}
for j, option := range payload.Options {
+5 -51
View File
@@ -9,6 +9,7 @@ import (
"github.com/ollama/ollama/internal/orderedmap"
"github.com/ollama/ollama/llm"
"github.com/ollama/ollama/model/renderers"
)
// Strands Decider's pointer head reads each question independently. Its prompt
@@ -120,57 +121,10 @@ func strandsField(name string, q Question) (compiledField, error) {
return f, nil
}
const maxStrandsContentDepth = 64
// Match json.dumps(indent=2, ensure_ascii=False, sort_keys=False), preserving
// object order and Python's number formatting as well as literal Unicode.
func strandsContent(raw json.RawMessage) (string, error) {
if _, err := content(raw); err != nil {
return "", err
if raw = bytes.TrimSpace(raw); len(raw) > 0 && (raw[0] == '{' || raw[0] == '[') {
return renderers.PythonJSON(raw, 2)
}
dec := json.NewDecoder(bytes.NewReader(raw))
dec.UseNumber()
var render func(int) (string, error)
render = func(depth int) (string, error) {
// Bound both recursion and indentation expansion of nested request data.
if depth > maxStrandsContentDepth {
return "", fmt.Errorf("content nesting exceeds %d levels", maxStrandsContentDepth)
}
token, err := dec.Token()
if err != nil {
return "", err
}
if delim, ok := token.(json.Delim); ok {
var parts []string
for dec.More() {
prefix := strings.Repeat(" ", depth+1)
if delim == '{' {
key, err := dec.Token()
if err != nil {
return "", err
}
quoted, _ := clefJSON(key)
prefix += quoted + ": "
}
value, err := render(depth + 1)
if err != nil {
return "", err
}
parts = append(parts, prefix+value)
}
end, err := dec.Token()
if err != nil {
return "", err
}
if len(parts) == 0 {
return fmt.Sprint(delim.String(), end), nil
}
return delim.String() + "\n" + strings.Join(parts, ",\n") + "\n" + strings.Repeat(" ", depth) + fmt.Sprint(end), nil
}
if depth == 0 {
return strings.TrimSpace(token.(string)), nil
}
return clefJSON(token)
}
return render(0)
text, err := content(raw)
return strings.TrimSpace(text), err
}
-4
View File
@@ -97,10 +97,6 @@ func TestStrandsChoiceWithoutDescriptions(t *testing.T) {
}
func TestStrandsContent(t *testing.T) {
depth := maxStrandsContentDepth + 1
if _, err := strandsContent(json.RawMessage(strings.Repeat("[", depth) + "0" + strings.Repeat("]", depth))); err == nil {
t.Fatal("accepted excessive content nesting")
}
for _, tt := range []struct{ input, want string }{
{`" text\n"`, "text"},
{`[]`, "[]"},
+3 -4
View File
@@ -14,6 +14,7 @@ import (
"github.com/ollama/ollama/api"
"github.com/ollama/ollama/internal/orderedmap"
"github.com/ollama/ollama/llm"
"github.com/ollama/ollama/model/renderers"
)
type compiledField struct {
@@ -116,7 +117,7 @@ func Compile(req Request, encoding string) (*Compiled, error) {
}
c.fields = append(c.fields, f)
}
prompts, err := decisionPrompts(context, c.fields, encoding)
prompts, err := decisionPrompts(req.State, context, c.fields, encoding)
if err != nil {
return nil, err
}
@@ -157,9 +158,7 @@ func content(raw json.RawMessage) (string, error) {
err := json.Unmarshal(raw, &s)
return s, err
case '{', '[':
var b bytes.Buffer
err := json.Compact(&b, raw)
return b.String(), err
return renderers.PythonJSON(raw, 0)
default:
return "", fmt.Errorf("must be a string, object, or array")
}
+4 -4
View File
@@ -77,7 +77,7 @@ func TestCompile(t *testing.T) {
if got := payload.Schema[0].Choices; got[0].Value != "billing" || got[1].Value != "technical" || got[1].Description != nil {
t.Fatalf("choice order or null description changed: %+v", got)
}
if payload.Schema[1].Description != `{"rule":"Explicit refund request?","notes":["Only facts"]}` {
if payload.Schema[1].Description != `{"rule": "Explicit refund request?", "notes": ["Only facts"]}` {
t.Fatalf("structured instructions changed: %q", payload.Schema[1].Description)
}
want := []string{"A", "B"}
@@ -109,7 +109,7 @@ func TestStructuredStateFrames(t *testing.T) {
t.Fatal(err)
}
for _, row := range compiled.Request.Rows {
if !strings.Contains(row.Prompt, `"context": "{\"frames\":[\"first\",\"second\"],\"position\":7}"`) {
if !strings.Contains(row.Prompt, `"context": "{\"frames\": [\"first\", \"second\"], \"position\": 7}"`) {
t.Fatalf("structured state was not preserved in the text prompt: %q", row.Prompt)
}
}
@@ -232,8 +232,8 @@ func TestInvalidRequests(t *testing.T) {
func TestContent(t *testing.T) {
for _, tt := range []struct{ input, want string }{
{` "line\nquoted \"text\"" `, "line\nquoted \"text\""},
{` {"z": 9007199254740993, "a": 1e999} `, `{"z":9007199254740993,"a":1e999}`},
{` [1.0, 1e6, -0, "€"] `, `[1.0,1e6,-0,"€"]`},
{` {"z": 9007199254740993, "a": 1e999} `, `{"z": 9007199254740993, "a": Infinity}`},
{` [1.0, 1e6, -0, "€"] `, `[1.0, 1000000.0, 0, "€"]`},
} {
got, err := content(json.RawMessage(tt.input))
if err != nil || got != tt.want {
+142 -1
View File
@@ -1,6 +1,13 @@
package renderers
import "encoding/json"
import (
"bytes"
"encoding/json"
"fmt"
"math"
"strconv"
"strings"
)
// marshalWithSpaces marshals v to JSON and adds a space after each ':' and ','
// that appears outside of string values. This matches the formatting expected
@@ -48,3 +55,137 @@ func AddJSONSpaces(b []byte) []byte {
}
return out
}
const maxPythonJSONDepth = 64
// PythonJSON renders v like Python's json.dumps(v, ensure_ascii=False),
// indented by indent spaces if indent > 0.
func PythonJSON(v any, indent int) (string, error) {
sep := ", "
if indent > 0 {
sep = ","
}
return pythonJSON(v, indent, sep, ": ")
}
// PythonJSONCompact renders v like json.dumps(v, ensure_ascii=False, separators=(",", ":")).
func PythonJSONCompact(v any) (string, error) {
return pythonJSON(v, 0, ",", ":")
}
func pythonJSON(v any, indent int, sep, colon string) (string, error) {
b, err := json.Marshal(v)
if err != nil {
return "", err
}
dec := json.NewDecoder(bytes.NewReader(b))
dec.UseNumber()
var render func(int) (string, error)
render = func(depth int) (string, error) {
if depth > maxPythonJSONDepth {
return "", fmt.Errorf("JSON nesting exceeds %d levels", maxPythonJSONDepth)
}
token, err := dec.Token()
if err != nil {
return "", err
}
delim, ok := token.(json.Delim)
if !ok {
return pythonScalar(token)
}
var parts []string
for dec.More() {
var part string
if indent > 0 {
part = "\n" + strings.Repeat(" ", indent*(depth+1))
}
if delim == '{' {
key, err := dec.Token()
if err != nil {
return "", err
}
quoted, _ := pythonScalar(key)
part += quoted + colon
}
value, err := render(depth + 1)
if err != nil {
return "", err
}
parts = append(parts, part+value)
}
end, err := dec.Token()
if err != nil {
return "", err
}
closing := fmt.Sprint(end)
if indent > 0 && len(parts) > 0 {
closing = "\n" + strings.Repeat(" ", indent*depth) + closing
}
return delim.String() + strings.Join(parts, sep) + closing, nil
}
return render(0)
}
func pythonScalar(token json.Token) (string, error) {
switch v := token.(type) {
case nil:
return "null", nil
case bool:
return strconv.FormatBool(v), nil
case string:
var b strings.Builder
b.WriteByte('"')
for _, r := range v {
switch r {
case '"', '\\':
b.WriteByte('\\')
b.WriteRune(r)
case '\b':
b.WriteString(`\b`)
case '\f':
b.WriteString(`\f`)
case '\n':
b.WriteString(`\n`)
case '\r':
b.WriteString(`\r`)
case '\t':
b.WriteString(`\t`)
default:
if r < 0x20 {
fmt.Fprintf(&b, `\u%04x`, r)
} else {
b.WriteRune(r)
}
}
}
b.WriteByte('"')
return b.String(), nil
case json.Number:
if !strings.ContainsAny(string(v), ".eE") {
if v == "-0" {
return "0", nil
}
return string(v), nil
}
n, err := v.Float64()
if math.IsInf(n, 0) {
if n < 0 {
return "-Infinity", nil
}
return "Infinity", nil
}
if err != nil {
return "", err
}
if a := math.Abs(n); a >= 1e16 || (a != 0 && a < 1e-4) {
return strconv.FormatFloat(n, 'e', -1, 64), nil
}
s := strconv.FormatFloat(n, 'f', -1, 64)
if !strings.ContainsRune(s, '.') {
s += ".0"
}
return s, nil
default:
return "", fmt.Errorf("unsupported JSON value %T", token)
}
}
+113
View File
@@ -1,6 +1,10 @@
package renderers
import (
"encoding/json"
"math"
"reflect"
"strings"
"testing"
"github.com/google/go-cmp/cmp"
@@ -343,3 +347,112 @@ func TestMarshalWithSpaces(t *testing.T) {
})
}
}
func TestPythonJSON(t *testing.T) {
// Expected values come from Python's json.dumps(ensure_ascii=False).
tests := []struct {
name string
input string
indent int
want string
}{
{"null", `null`, 0, "null"},
{"booleans", `[true,false]`, 0, "[true, false]"},
{"integers", `[0,-7,-0,12345678901234567890123]`, 0, "[0, -7, 0, 12345678901234567890123]"},
{"floats", `[1.0,1.50,0.1,-0.0,123456789.123456789]`, 0, "[1.0, 1.5, 0.1, -0.0, 123456789.12345679]"},
{"exponent spellings", `[1e6,1E6,1e+6,2.5E-3]`, 0, "[1000000.0, 1000000.0, 1000000.0, 0.0025]"},
{"exponent thresholds", `[1e15,1e16,9999999999999998.0,1e-4,9.999e-5,1e-5]`, 0, "[1000000000000000.0, 1e+16, 9999999999999998.0, 0.0001, 9.999e-05, 1e-05]"},
{"float limits", `[5e-324,1.7976931348623157e308,1e999,-1e999,1e-999,-1e-999]`, 0, "[5e-324, 1.7976931348623157e+308, Infinity, -Infinity, 0.0, -0.0]"},
{"control characters", `"\u0000\u001f\b\f\n\r\t"`, 0, "\"\\u0000\\u001f\\b\\f\\n\\r\\t\""},
{"quotes and backslashes", `"\"\\ \\u2028"`, 0, "\"\\\"\\\\ \\\\u2028\""},
{"characters encoding/json escapes", `"<>& \u003c\u003e\u0026 \u2028\u2029 \/"`, 0, "\"<>& <>& \u2028\u2029 /\""},
{"non-ASCII", `"café 中 € \u00e9 \ud83d\ude00 \u007f"`, 0, "\"café 中 € é 😀 \u007f\""},
{"empty containers", `[{},[],{"a":{}},[[]]]`, 0, "[{}, [], {\"a\": {}}, [[]]]"},
{"object order and nesting", `{"b":1,"a":[1,{"c":null}]}`, 0, "{\"b\": 1, \"a\": [1, {\"c\": null}]}"},
{"input whitespace", `{ "a" : [ 1 , 2 ] }`, 0, "{\"a\": [1, 2]}"},
{"escaped keys", `{"q\"k":1,"caf\u00e9":2}`, 0, "{\"q\\\"k\": 1, \"café\": 2}"},
{"indent 2", `{"z":{},"a":[1.0,[]]}`, 2, "{\n \"z\": {},\n \"a\": [\n 1.0,\n []\n ]\n}"},
{"indent 4", `[{"a":[1,2]}]`, 4, "[\n {\n \"a\": [\n 1,\n 2\n ]\n }\n]"},
{"indented scalar", `"text"`, 2, "\"text\""},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := PythonJSON(json.RawMessage(tt.input), tt.indent)
if err != nil {
t.Fatal(err)
}
if diff := cmp.Diff(got, tt.want); diff != "" {
t.Errorf("mismatch (-got +want):\n%s", diff)
}
})
}
}
func TestPythonJSONCompact(t *testing.T) {
for _, tt := range []struct {
input any
want string
}{
{json.RawMessage(`{"b":[1,{"d":2.0}],"a":"x, y: z"}`), `{"b":[1,{"d":2.0}],"a":"x, y: z"}`},
{map[string]any{"b": map[string]any{"z": 1, "y": json.Number("1e6")}, "a": nil}, `{"a":null,"b":{"y":1000000.0,"z":1}}`},
} {
got, err := PythonJSONCompact(tt.input)
if err != nil || got != tt.want {
t.Errorf("PythonJSONCompact = %q, %v; want %q", got, err, tt.want)
}
}
}
func TestPythonJSONGoValues(t *testing.T) {
got, err := PythonJSON(struct {
Note string `json:"note"`
State json.RawMessage `json:"state"`
Extra any `json:"extra,omitempty"`
}{"café & <i>", json.RawMessage(`{"z":1e6,"a":"<b>"}`), nil}, 0)
if want := `{"note": "café & <i>", "state": {"z": 1000000.0, "a": "<b>"}}`; err != nil || got != want {
t.Errorf("PythonJSON = %q, %v; want %q", got, err, want)
}
}
func TestPythonJSONErrors(t *testing.T) {
for i, input := range []any{
json.RawMessage(`{"a":}`),
json.RawMessage(`[1,]`),
json.RawMessage(`{} {}`),
json.RawMessage(``),
make(chan int),
math.NaN(),
} {
if got, err := PythonJSON(input, 0); err == nil {
t.Errorf("input %d: got %q, want error", i, got)
}
}
for _, depth := range []int{maxPythonJSONDepth, maxPythonJSONDepth + 1} {
_, err := PythonJSON(json.RawMessage(strings.Repeat("[", depth)+"0"+strings.Repeat("]", depth)), 2)
if (err == nil) != (depth <= maxPythonJSONDepth) {
t.Errorf("nesting %d: %v", depth, err)
}
}
}
func FuzzPythonJSON(f *testing.F) {
for _, seed := range []string{`{"z":1e6,"a":["café",true,null]}`, `[[],{}]`, `"\u2028\ud83d\ude00"`, `[-0,-0.0,1e-999,12345678901234567890]`, `{"a":1,"a":2}`} {
f.Add(seed)
}
f.Fuzz(func(t *testing.T, input string) {
var want any
if len(input) > 64<<10 || json.Unmarshal([]byte(input), &want) != nil {
return
}
for _, indent := range []int{0, 2} {
out, err := PythonJSON(json.RawMessage(input), indent)
if err != nil {
continue
}
var got any
if err := json.Unmarshal([]byte(out), &got); err != nil || !reflect.DeepEqual(got, want) {
t.Fatalf("%q rendered as %q", input, out)
}
}
})
}