From 738c987a251c80f5c2f49d743e45f1e58d440a16 Mon Sep 17 00:00:00 2001 From: William Kennedy Date: Mon, 26 Oct 2026 11:11:33 -0400 Subject: [PATCH] dsv41 support --- builtins.go | 27 +- eval.go | 70 +++-- jinja_test.go | 37 +++ parse.go | 12 +- requests_test.go | 52 ++++ scripts/render_python.py | 1 + testdata/requests/deepseek-v4.1-chat.json | 4 + testdata/requests/deepseek-v4.1-effort-1.json | 4 + .../requests/deepseek-v4.1-effort-100.json | 4 + testdata/requests/deepseek-v4.1-low.json | 4 + testdata/requests/deepseek-v4.1-max.json | 4 + testdata/requests/deepseek-v4.1-medium.json | 4 + testdata/requests/deepseek-v4.1-tools.json | 21 ++ testdata/templates/DeepSeek-V4.1-Flash.jinja | 252 ++++++++++++++++++ testdata/templates/SOURCES.md | 25 ++ 15 files changed, 492 insertions(+), 29 deletions(-) create mode 100644 testdata/requests/deepseek-v4.1-chat.json create mode 100644 testdata/requests/deepseek-v4.1-effort-1.json create mode 100644 testdata/requests/deepseek-v4.1-effort-100.json create mode 100644 testdata/requests/deepseek-v4.1-low.json create mode 100644 testdata/requests/deepseek-v4.1-max.json create mode 100644 testdata/requests/deepseek-v4.1-medium.json create mode 100644 testdata/requests/deepseek-v4.1-tools.json create mode 100644 testdata/templates/DeepSeek-V4.1-Flash.jinja create mode 100644 testdata/templates/SOURCES.md diff --git a/builtins.go b/builtins.go index af7edbd..f80164e 100644 --- a/builtins.go +++ b/builtins.go @@ -110,6 +110,17 @@ func builtinJoiner(args []Value, kwargs map[string]Value) (Value, error) { func builtinDict(args []Value, kwargs map[string]Value) (Value, error) { d := NewDict() dict := d.AsDict() + if len(args) > 1 { + return Undefined(), fmt.Errorf("dict: expected at most one positional argument") + } + if len(args) == 1 { + if !args[0].IsDict() { + return Undefined(), fmt.Errorf("dict: positional argument must be a mapping") + } + for _, key := range args[0].AsDict().Keys { + dict.Set(key, args[0].AsDict().Data[key]) + } + } for k, v := range kwargs { dict.Set(k, v) } @@ -736,8 +747,22 @@ func filterSort(args []Value, kwargs map[string]Value) (Value, error) { reverse = r.AsBool() } + attribute := "" + if a, ok := kwargs["attribute"]; ok { + attribute = printValue(a) + } + sort.SliceStable(items, func(i, j int) bool { - cmp := compareValues(items[i], items[j]) + left, right := items[i], items[j] + if attribute != "" { + if left.IsDict() { + left, _ = left.AsDict().Get(attribute) + } + if right.IsDict() { + right, _ = right.AsDict().Get(attribute) + } + } + cmp := compareValues(left, right) if reverse { return cmp > 0 } diff --git a/eval.go b/eval.go index 0870836..b57ba32 100644 --- a/eval.go +++ b/eval.go @@ -369,13 +369,15 @@ func (e *evaluator) execCall(n *callNode) error { args = append(args, av) } - kwargs := map[string]Value{"caller": caller} - for _, kw := range callEx.kwargs { - v, err := e.evalExpr(kw.value) - if err != nil { - return err - } - kwargs[kw.name] = v + kwargs, err := e.evalKeywordArgs(callEx.kwargs) + if err != nil { + return err + } + if kwargs == nil { + kwargs = make(map[string]Value) + } + if _, ok := kwargs["caller"]; !ok { + kwargs["caller"] = caller } result, err := fn.AsCallable().Fn(args, kwargs) @@ -889,19 +891,42 @@ func (e *evaluator) evalCallExpr(n *callExpr) (Value, error) { args[i] = v } - var kwargs map[string]Value - if len(n.kwargs) > 0 { - kwargs = make(map[string]Value, len(n.kwargs)) - for _, kw := range n.kwargs { - v, err := e.evalExpr(kw.value) - if err != nil { - return Undefined(), err + kwargs, err := e.evalKeywordArgs(n.kwargs) + if err != nil { + return Undefined(), err + } + + return fn.AsCallable().Fn(args, kwargs) +} + +func (e *evaluator) evalKeywordArgs(keywords []kwarg) (map[string]Value, error) { + if len(keywords) == 0 { + return nil, nil + } + kwargs := make(map[string]Value, len(keywords)) + for _, kw := range keywords { + v, err := e.evalExpr(kw.value) + if err != nil { + return nil, err + } + if kw.name != "" { + if _, exists := kwargs[kw.name]; exists { + return nil, fmt.Errorf("duplicate keyword argument: %s", kw.name) } kwargs[kw.name] = v + continue + } + if !v.IsDict() { + return nil, fmt.Errorf("keyword argument expansion requires a mapping") + } + for _, key := range v.AsDict().Keys { + if _, exists := kwargs[key]; exists { + return nil, fmt.Errorf("duplicate keyword argument: %s", key) + } + kwargs[key] = v.AsDict().Data[key] } } - - return fn.AsCallable().Fn(args, kwargs) + return kwargs, nil } func callableName(ex expr) string { @@ -951,16 +976,9 @@ func (e *evaluator) evalFilter(n *filterExpr) (Value, error) { args[i+1] = v } - var kwargs map[string]Value - if len(n.kwargs) > 0 { - kwargs = make(map[string]Value, len(n.kwargs)) - for _, kw := range n.kwargs { - v, err := e.evalExpr(kw.value) - if err != nil { - return Undefined(), err - } - kwargs[kw.name] = v - } + kwargs, err := e.evalKeywordArgs(n.kwargs) + if err != nil { + return Undefined(), err } return filterVal.AsCallable().Fn(args, kwargs) diff --git a/jinja_test.go b/jinja_test.go index 670f53b..e231e10 100644 --- a/jinja_test.go +++ b/jinja_test.go @@ -1236,6 +1236,43 @@ func TestRender_Beam_BuiltinBash(t *testing.T) { } } +// TestDeepSeekV41Primitives covers the Jinja operations used by the upstream +// template without coupling their regression coverage to its full prompt. +func TestDeepSeekV41Primitives(t *testing.T) { + tests := []struct { + name string + input string + want string + wantErr bool + }{ + {"copy mapping", `{% set a = {'x': 1} %}{% set b = dict(a, x=2) %}{{ a.x }} {{ b.x }}`, "1 2", false}, + {"dynamic keyword", `{% set key = 'x' %}{{ dict({'a': 1}, **{key: 2}).x }}`, "2", false}, + {"macro keyword", `{% macro show(x) %}{{ x }}{% endmacro %}{{ show(**{'x': 3}) }}`, "3", false}, + {"filter keyword", `{{ ['a', 'b'] | join(**{'d': '-'}) }}`, "a-b", false}, + {"invalid expansion", `{{ dict(**[]) }}`, "", true}, + {"duplicate expansion", `{{ dict(x=1, **{'x': 2}) }}`, "", true}, + {"invalid copy", `{{ dict(1) }}`, "", true}, + {"too many copies", `{{ dict({}, {}) }}`, "", true}, + {"stable attribute sort", `{{ [{'n': 2, 's': 'a'}, {'n': 1, 's': 'b'}, {'n': 2, 's': 'c'}] | sort(attribute='n') | join(attribute='s') }}`, "bac", false}, + {"reverse attribute sort", `{{ [{'n': 1, 's': 'a'}, {'n': 2, 's': 'b'}] | sort(attribute='n', reverse=true) | join(attribute='s') }}`, "ba", false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + tmpl, err := jinja.Compile(tt.input) + if err != nil { + t.Fatalf("compile: %v", err) + } + got, err := tmpl.Render(nil) + if (err != nil) != tt.wantErr { + t.Fatalf("render: got error %v, want error %v", err, tt.wantErr) + } + if !tt.wantErr && got != tt.want { + t.Errorf("got %q, want %q", got, tt.want) + } + }) + } +} + func TestRegression(t *testing.T) { for name, content := range chatTemplates { t.Run(name, func(t *testing.T) { diff --git a/parse.go b/parse.go index 677264d..11783b3 100644 --- a/parse.go +++ b/parse.go @@ -806,7 +806,15 @@ func (p *exprParser) parseCallArgs() ([]expr, []kwarg, error) { for p.peek().kind != tokRParen && p.peek().kind != tokEOF { // Check for kwarg: name=value - if p.peek().kind == tokName && p.pos+1 < len(p.tokens) && p.tokens[p.pos+1].kind == tokOp && p.tokens[p.pos+1].val == "=" { + if p.peek().kind == tokPower { + p.advance() + val, err := p.parseExpression() + if err != nil { + return nil, nil, err + } + // An empty name denotes a mapping expanded into keyword arguments. + kwargs = append(kwargs, kwarg{value: val}) + } else if p.peek().kind == tokName && p.pos+1 < len(p.tokens) && p.tokens[p.pos+1].kind == tokOp && p.tokens[p.pos+1].val == "=" { name := p.advance().val p.advance() // skip = val, err := p.parseExpression() @@ -866,7 +874,7 @@ func parseTemplate(segs []segment) ([]node, error) { // present on that side: // // - lstrip_blocks: strip spaces and tabs (not newlines) from the start of -// the line up to the tag. +// the line up to the tag. // - trim_blocks: strip a single newline immediately after the tag. // // Without these defaults, every block tag in a real chat template would diff --git a/requests_test.go b/requests_test.go index 6af1f7f..af6b1af 100644 --- a/requests_test.go +++ b/requests_test.go @@ -5,6 +5,7 @@ import ( "encoding/json" "errors" "fmt" + "maps" "os" "os/exec" "path/filepath" @@ -53,6 +54,12 @@ func TestRequestsAgainstTemplates(t *testing.T) { req := requests[reqName] t.Run(reqName, func(t *testing.T) { data := buildRenderData(req) + // Model-specific fixture controls must not affect unrelated templates. + if byTemplate, ok := req["chat_template_kwargs"].(map[string]any); ok { + if kwargs, ok := byTemplate[templateName].(map[string]any); ok { + maps.Copy(data, kwargs) + } + } var got string result, err := tmpl.Render(data) @@ -62,6 +69,51 @@ func TestRequestsAgainstTemplates(t *testing.T) { got = result } + if templateName == "DeepSeek-V4.1-Flash" && strings.HasPrefix(reqName, "deepseek-v4.1-") { + if err != nil { + t.Fatalf("render valid V4.1 request: %v", err) + } + if reqName == "deepseek-v4.1-tools" { + for _, fragment := range []string{ + "Reasoning Effort: 75 (range 1-100, the higher the value, the more thorough the reasoning)", + "I should use the tools.", + "\n\n<|DSML| calls>\n<|DSML| invoke name=\"analyze\">\n", + `<|DSML| parameter name="city" string="true">Paris`, + `<|DSML| parameter name="count" string="false">2`, + `<|DSML| parameter name="options" string="false">{"enabled": true, "tags": ["a", "b"]}`, + "first result\n\nsecond result", + } { + if !strings.Contains(got, fragment) { + t.Errorf("rendered V4.1 output missing %q", fragment) + } + } + } + thinking := reqName != "deepseek-v4.1-chat" + budgets := map[string]int{ + "deepseek-v4.1-low": 50, + "deepseek-v4.1-medium": 62, + "deepseek-v4.1-tools": 75, + "deepseek-v4.1-max": 100, + "deepseek-v4.1-effort-1": 1, + "deepseek-v4.1-effort-100": 100, + } + if thinking { + prefix := fmt.Sprintf("<|begin▁of▁sentence|><|System|>Reasoning Effort: %d (range 1-100, the higher the value, the more thorough the reasoning)\n\n", budgets[reqName]) + if !strings.HasPrefix(got, prefix) { + t.Errorf("reasoning effort: got %q, want prefix %q", got, prefix) + } + } else if strings.Contains(got, "Reasoning Effort:") { + t.Error("chat mode unexpectedly includes a reasoning budget") + } + ending := "<|Assistant|>" + if thinking { + ending = "<|Assistant|>" + } + if !strings.HasSuffix(got, ending) { + t.Errorf("generation prefix: got %q, want suffix %q", got, ending) + } + } + if templateName == "DeepSeek-V4-Flash" && reqName == "kronk-req-deepseek" { for _, fragment := range []string{ `<|DSML|invoke name="get_weather">`, diff --git a/scripts/render_python.py b/scripts/render_python.py index 2785036..864f571 100644 --- a/scripts/render_python.py +++ b/scripts/render_python.py @@ -166,6 +166,7 @@ def main() -> int: tpl_src = tpl_path.read_text() for req_name, req in parsed_requests.items(): ctx = build_context(req) + ctx.update(req.get("chat_template_kwargs", {}).get(tpl_name, {})) out[f"{tpl_name}/{req_name}"] = render_one(env, tpl_src, ctx) json.dump(out, sys.stdout) diff --git a/testdata/requests/deepseek-v4.1-chat.json b/testdata/requests/deepseek-v4.1-chat.json new file mode 100644 index 0000000..a39f45e --- /dev/null +++ b/testdata/requests/deepseek-v4.1-chat.json @@ -0,0 +1,4 @@ +{ + "chat_template_kwargs": {"DeepSeek-V4.1-Flash": {"enable_thinking": false, "reasoning_effort": "high"}}, + "messages": [{"role": "user", "content": "Hello."}] +} diff --git a/testdata/requests/deepseek-v4.1-effort-1.json b/testdata/requests/deepseek-v4.1-effort-1.json new file mode 100644 index 0000000..a4bc93c --- /dev/null +++ b/testdata/requests/deepseek-v4.1-effort-1.json @@ -0,0 +1,4 @@ +{ + "chat_template_kwargs": {"DeepSeek-V4.1-Flash": {"thinking_mode": "thinking", "reasoning_effort": 1}}, + "messages": [{"role": "user", "content": "Hello."}] +} diff --git a/testdata/requests/deepseek-v4.1-effort-100.json b/testdata/requests/deepseek-v4.1-effort-100.json new file mode 100644 index 0000000..bdeebd6 --- /dev/null +++ b/testdata/requests/deepseek-v4.1-effort-100.json @@ -0,0 +1,4 @@ +{ + "chat_template_kwargs": {"DeepSeek-V4.1-Flash": {"thinking_mode": "thinking", "reasoning_effort": 100}}, + "messages": [{"role": "user", "content": "Hello."}] +} diff --git a/testdata/requests/deepseek-v4.1-low.json b/testdata/requests/deepseek-v4.1-low.json new file mode 100644 index 0000000..d8acd5e --- /dev/null +++ b/testdata/requests/deepseek-v4.1-low.json @@ -0,0 +1,4 @@ +{ + "chat_template_kwargs": {"DeepSeek-V4.1-Flash": {"enable_thinking": true, "reasoning_effort": "low"}}, + "messages": [{"role": "user", "content": "Hello."}] +} diff --git a/testdata/requests/deepseek-v4.1-max.json b/testdata/requests/deepseek-v4.1-max.json new file mode 100644 index 0000000..78ea30a --- /dev/null +++ b/testdata/requests/deepseek-v4.1-max.json @@ -0,0 +1,4 @@ +{ + "chat_template_kwargs": {"DeepSeek-V4.1-Flash": {"thinking_mode": "thinking", "reasoning_effort": "max"}}, + "messages": [{"role": "user", "content": "Hello."}] +} diff --git a/testdata/requests/deepseek-v4.1-medium.json b/testdata/requests/deepseek-v4.1-medium.json new file mode 100644 index 0000000..efcae15 --- /dev/null +++ b/testdata/requests/deepseek-v4.1-medium.json @@ -0,0 +1,4 @@ +{ + "chat_template_kwargs": {"DeepSeek-V4.1-Flash": {"thinking_mode": "thinking", "reasoning_effort": "medium"}}, + "messages": [{"role": "user", "content": "Hello."}] +} diff --git a/testdata/requests/deepseek-v4.1-tools.json b/testdata/requests/deepseek-v4.1-tools.json new file mode 100644 index 0000000..fd9217d --- /dev/null +++ b/testdata/requests/deepseek-v4.1-tools.json @@ -0,0 +1,21 @@ +{ + "chat_template_kwargs": {"DeepSeek-V4.1-Flash": {"thinking_mode": "thinking", "reasoning_effort": "high"}}, + "messages": [ + {"role": "system", "content": "Use tools when needed."}, + {"role": "user", "content": "Analyze these inputs."}, + { + "role": "assistant", + "content": "", + "reasoning_content": "I should use the tools.", + "tool_calls": [ + {"id": "first", "type": "function", "function": {"name": "analyze", "arguments": "{\"city\":\"Paris\"}"}}, + {"id": "second", "type": "function", "function": {"name": "analyze", "arguments": {"count": 2, "options": {"enabled": true, "tags": ["a", "b"]}}}} + ] + }, + {"role": "tool", "tool_call_id": "second", "content": "second result"}, + {"role": "tool", "tool_call_id": "first", "content": "first result"} + ], + "tools": [ + {"function": {"description": "Analyze an input.", "name": "analyze", "parameters": {"properties": {"city": {"type": "string"}, "count": {"type": "integer"}, "options": {"type": "object"}}, "type": "object"}}, "type": "function"} + ] +} diff --git a/testdata/templates/DeepSeek-V4.1-Flash.jinja b/testdata/templates/DeepSeek-V4.1-Flash.jinja new file mode 100644 index 0000000..eb12dd2 --- /dev/null +++ b/testdata/templates/DeepSeek-V4.1-Flash.jinja @@ -0,0 +1,252 @@ +{#- DeepSeek-V4.1 chat template, ported from encoding/encoding.py in the model repo. + Extra kwargs: thinking_mode ("thinking" | "chat", default "thinking"; enable_thinking=true/false is accepted + as an alias), drop_thinking (default true), reasoning_effort (int in [1, 100] or "low"/"medium"/"high"/"max", + default "high"). Assistant reasoning is read from reasoning_content, or from thinking as an alias. -#} +{%- set IMG = "<|deepseek_image|>" -%} +{%- set DSML = "|DSML|" -%} + +{%- if thinking_mode is not defined -%} + {%- set thinking_mode = "chat" if (enable_thinking is defined and enable_thinking is not none and not enable_thinking) else "thinking" -%} +{%- endif -%} +{%- if thinking_mode not in ["chat", "thinking"] -%} + {{- raise_exception("Invalid thinking_mode `" ~ thinking_mode ~ "`, should be \"chat\" or \"thinking\"") -}} +{%- endif -%} +{%- if drop_thinking is not defined -%}{%- set drop_thinking = true -%}{%- endif -%} +{%- if add_generation_prompt is not defined -%}{%- set add_generation_prompt = false -%}{%- endif -%} +{%- if tools is not defined -%}{%- set tools = none -%}{%- endif -%} + +{%- if reasoning_effort is not defined or reasoning_effort is none -%}{%- set reasoning_effort = "high" -%}{%- endif -%} +{%- set effort_map = {"low": 50, "medium": 62, "high": 75, "max": 100} -%} +{%- if reasoning_effort is string and reasoning_effort in effort_map -%} + {%- set budget = effort_map[reasoning_effort] -%} +{%- elif reasoning_effort is integer and 1 <= reasoning_effort <= 100 -%} + {%- set budget = reasoning_effort -%} +{%- else -%} + {{- raise_exception("Invalid reasoning effort: " ~ reasoning_effort ~ ", should be int within [1,100] or one of \"low\", \"medium\", \"high\", \"max\"") -}} +{%- endif -%} + +{#- Text of text/image blocks joined by blank lines; other block types are dropped. -#} +{%- macro joined_text(blocks) -%} + {%- set jt = namespace(parts=[]) -%} + {%- for b in blocks -%} + {%- if b.type == "text" -%} + {%- if IMG in (b.text or "") -%}{{- raise_exception("Text block contains image placeholder " ~ IMG ~ ". Images should be separate content blocks.") -}}{%- endif -%} + {%- set jt.parts = jt.parts + [b.text or ""] -%} + {%- elif b.type in ["image", "image_url"] -%} + {%- set jt.parts = jt.parts + [IMG] -%} + {%- endif -%} + {%- endfor -%} + {{- jt.parts | join("\n\n") -}} +{%- endmacro -%} + +{#- Splits/validates "ns::name" against an explicit namespace and returns the qualified name. -#} +{%- macro qualified_name(name, ns) -%} + {%- if ns is mapping -%}{%- set ns = ns.name -%}{%- endif -%} + {%- set parts = name.split("::", 1) -%} + {%- if parts | length == 2 -%} + {%- if ns is not none and ns != parts[0] -%}{{- raise_exception("Conflicting tool namespaces: " ~ ns ~ " != " ~ parts[0]) -}}{%- endif -%} + {%- set ns = parts[0] -%} + {%- set name = parts[1] -%} + {%- endif -%} + {%- if "::" in name -%}{{- raise_exception("Tool name must not contain '::': " ~ name) -}}{%- endif -%} + {%- if ns is not none and "::" in ns -%}{{- raise_exception("Tool namespace must not contain '::': " ~ ns) -}}{%- endif -%} + {{- name if ns is none else ns ~ "::" ~ name -}} +{%- endmacro -%} + +{%- macro render_tools(tool_list) -%} + {%- set ts = namespace(schemas=[]) -%} + {%- for tool in tool_list -%} + {%- set fn = tool.function if tool.function is defined else tool -%} + {%- set ns = tool.namespace if tool.namespace is defined and tool.namespace is not none else fn.get("namespace") -%} + {%- set schema = namespace(d={}) -%} + {%- for k, v in fn.items() if k != "namespace" -%}{%- set schema.d = dict(schema.d, **{k: v}) -%}{%- endfor -%} + {%- set schema.d = dict(schema.d, name=qualified_name(fn.name, ns)) -%} + {%- if ns is mapping and ns.description -%} + {%- set schema.d = dict(schema.d, description=ns.description ~ "\n" ~ (fn.description or "")) -%} + {%- endif -%} + {%- set ts.schemas = ts.schemas + [schema.d | tojson] -%} + {%- endfor -%} + {{- "## Tools\n\nYou have access to a set of tools to help answer the user's question. You can invoke tools by writing a \"<|DSML| calls>\" block like the following:\n\n<|DSML| calls>\n<|DSML| invoke name=\"$TOOL_NAME\">\n<|DSML| parameter name=\"$PARAMETER_NAME\" string=\"true|false\">$PARAMETER_VALUE\n...\n\n<|DSML| invoke name=\"$TOOL_NAME2\">\n...\n\n\n\nString parameters should be specified as is and set `string=\"true\"`. For all other types (numbers, booleans, arrays, objects), pass the value in JSON format and set `string=\"false\"`.\n\nIf thinking_mode is enabled (triggered by ), you MUST output your complete reasoning inside ... BEFORE any tool calls or final response.\n\nOtherwise, output directly after with tool calls or final response.\n\n### Available Tool Schemas\n\n" -}} + {{- ts.schemas | join("\n") -}} + {{- "\n\nYou MUST strictly follow the above defined tool name and parameter schemas to invoke tool calls.\n" -}} +{%- endmacro -%} + +{#- 1. Merge tool results (and consecutive user turns) into user messages made of content blocks. -#} +{%- set mns = namespace(list=[]) -%} +{%- for msg in messages -%} + {%- set content = msg.get("content") -%} + {%- set is_blocks = content is iterable and content is not string and content is not mapping -%} + {%- if content is string and IMG in content -%} + {{- raise_exception("Message content contains image special token " ~ IMG ~ ". Images should be provided as image content blocks.") -}} + {%- endif -%} + {%- set rc = msg.reasoning_content if msg.get("reasoning_content") is not none else msg.get("thinking") -%} + {%- if rc is string and IMG in rc -%} + {{- raise_exception("reasoning_content contains image special token " ~ IMG) -}} + {%- endif -%} + {%- set prev = mns.list[-1] if mns.list else none -%} + {%- if msg.role == "tool" -%} + {%- set tblock = {"type": "tool_result", "tool_use_id": msg.get("tool_call_id", ""), "content": joined_text(content) if is_blocks else msg.get("content", "")} -%} + {%- if prev is not none and prev.role == "user" -%} + {%- set mns.list = mns.list[:-1] + [dict(prev, content_blocks=prev.content_blocks + [tblock])] -%} + {%- else -%} + {%- set mns.list = mns.list + [{"role": "user", "content_blocks": [tblock]}] -%} + {%- endif -%} + {%- elif msg.role == "user" -%} + {%- set blocks = content if is_blocks else [{"type": "text", "text": content or ""}] -%} + {%- if prev is not none and prev.role == "user" and prev.get("task") is none -%} + {%- set mns.list = mns.list[:-1] + [dict(prev, content_blocks=prev.content_blocks + blocks)] -%} + {%- else -%} + {%- set mns.list = mns.list + [dict(msg, content_blocks=blocks)] -%} + {%- endif -%} + {%- else -%} + {%- set mns.list = mns.list + [msg] -%} + {%- endif -%} +{%- endfor -%} + +{#- Top-level tools attach to a leading system message, or to a new empty one. -#} +{%- if tools -%} + {%- if mns.list and mns.list[0].role == "system" -%} + {%- if not mns.list[0].get("tools") -%}{%- set mns.list = [dict(mns.list[0], tools=tools)] + mns.list[1:] -%}{%- endif -%} + {%- else -%} + {%- set mns.list = [{"role": "system", "content": "", "tools": tools}] + mns.list -%} + {%- endif -%} +{%- endif -%} + +{#- 2. Reorder tool results to match the tool_calls order of the preceding assistant message. -#} +{%- set sns = namespace(list=[], ids=[]) -%} +{%- for m in mns.list -%} + {%- if m.role == "assistant" and m.get("tool_calls") -%} + {%- set sns.ids = [] -%} + {%- for tc in m.tool_calls -%} + {%- set sns.ids = sns.ids + [tc.get("id") or tc.get("function", {}).get("id", "")] -%} + {%- endfor -%} + {%- set sns.list = sns.list + [m] -%} + {%- elif m.role == "user" and m.content_blocks -%} + {%- set tb = namespace(blocks=[]) -%} + {%- for b in m.content_blocks if b.type == "tool_result" -%} + {%- set order = namespace(idx=0) -%} + {%- for tc_id in sns.ids -%} + {%- if tc_id and tc_id == b.get("tool_use_id", "") -%}{%- set order.idx = loop.index0 -%}{%- endif -%} + {%- endfor -%} + {%- set tb.blocks = tb.blocks + [dict(b, _order=order.idx)] -%} + {%- endfor -%} + {%- if tb.blocks | length > 1 -%} + {%- set sorted_blocks = tb.blocks | sort(attribute="_order") -%} + {%- set rb = namespace(blocks=[], i=0) -%} + {%- for b in m.content_blocks -%} + {%- if b.type == "tool_result" -%} + {%- set rb.blocks = rb.blocks + [sorted_blocks[rb.i]] -%} + {%- set rb.i = rb.i + 1 -%} + {%- else -%} + {%- set rb.blocks = rb.blocks + [b] -%} + {%- endif -%} + {%- endfor -%} + {%- set sns.list = sns.list + [dict(m, content_blocks=rb.blocks)] -%} + {%- else -%} + {%- set sns.list = sns.list + [m] -%} + {%- endif -%} + {%- else -%} + {%- set sns.list = sns.list + [m] -%} + {%- endif -%} +{%- endfor -%} +{%- set msgs = sns.list -%} + +{#- Mid-conversation system messages count as user turns. Tools anywhere disable drop_thinking. -#} +{%- set state = namespace(last_user=-1, has_tools=false) -%} +{%- for m in msgs -%} + {%- if m.role == "user" or (m.role == "system" and loop.index0 > 0) -%}{%- set state.last_user = loop.index0 -%}{%- endif -%} + {%- if m.get("tools") -%}{%- set state.has_tools = true -%}{%- endif -%} +{%- endfor -%} +{%- set effective_drop = drop_thinking and not state.has_tools -%} +{%- set thinking = thinking_mode == "thinking" -%} + +{{- "<|begin▁of▁sentence|>" -}} +{#- 3. Render each message. -#} +{%- for m in msgs -%} + {%- set idx = loop.index0 -%} + {%- set content = m.get("content") -%} + {%- if content is iterable and content is not string and content is not mapping -%}{%- set content = joined_text(content) -%}{%- endif -%} + + {%- if idx == 0 -%} + {%- if thinking or m.role == "system" -%}{{- "<|System|>" -}}{%- endif -%} + {%- if thinking -%}{{- "Reasoning Effort: " ~ budget ~ " (range 1-100, the higher the value, the more thorough the reasoning)\n\n" -}}{%- endif -%} + {%- endif -%} + + {%- if m.role == "system" -%} + {%- if idx > 0 -%}{{- "<|System|>" -}}{%- endif -%} + {{- content or "" -}} + {%- if m.get("tools") -%}{{- "\n\n" ~ render_tools(m.tools) -}}{%- endif -%} + {%- if m.get("response_format") -%} + {{- "\n\n## Response Format:\n\nYou MUST strictly adhere to the following schema to reply:\n" ~ (m.response_format | tojson) -}} + {%- endif -%} + + {%- elif m.role == "user" -%} + {{- "<|User|>" -}} + {%- set up = namespace(parts=[]) -%} + {%- for b in m.content_blocks -%} + {%- if b.type == "text" -%} + {%- if IMG in (b.text or "") -%}{{- raise_exception("Text block contains image placeholder " ~ IMG ~ ". Images should be separate content blocks.") -}}{%- endif -%} + {%- set up.parts = up.parts + [b.text or ""] -%} + {%- elif b.type in ["image", "image_url"] -%} + {%- set up.parts = up.parts + [IMG] -%} + {%- elif b.type == "tool_result" -%} + {%- set tc = b.get("content", "") -%} + {%- if tc is iterable and tc is not string and tc is not mapping -%} + {%- set sub = namespace(parts=[]) -%} + {%- for s in tc -%} + {%- if s.type == "text" -%}{%- set sub.parts = sub.parts + [s.get("text", "")] -%} + {%- elif s.type in ["image", "image_url"] -%}{%- set sub.parts = sub.parts + [IMG] -%} + {%- else -%}{%- set sub.parts = sub.parts + ["[Unsupported " ~ s.type ~ "]"] -%} + {%- endif -%} + {%- endfor -%} + {%- set tc = sub.parts | join("\n\n") -%} + {%- endif -%} + {%- set up.parts = up.parts + ["" ~ tc ~ ""] -%} + {%- else -%} + {%- set up.parts = up.parts + ["[Unsupported " ~ b.type ~ "]"] -%} + {%- endif -%} + {%- endfor -%} + {{- up.parts | join("\n\n") -}} + + {%- elif m.role == "latest_reminder" -%} + {{- "<|latest_reminder|>" ~ content -}} + + {%- elif m.role == "assistant" -%} + {%- set prev_has_task = idx > 0 and msgs[idx - 1].get("task") is not none -%} + {%- if thinking and not prev_has_task and (not effective_drop or idx > state.last_user) -%} + {{- ((m.reasoning_content if m.get("reasoning_content") is not none else m.get("thinking")) or "") ~ "" -}} + {%- endif -%} + {{- content or "" -}} + {%- if m.get("tool_calls") -%} + {%- set tcs = namespace(lines=[]) -%} + {%- for tc in m.tool_calls -%} + {%- set fn = tc.function -%} + {%- set params = namespace(lines=[]) -%} + {%- set args = fn.arguments if fn.arguments is mapping else {"arguments": fn.arguments} -%} + {%- for k, v in args.items() -%} + {%- set params.lines = params.lines + ["<" ~ DSML ~ " parameter name=\"" ~ k ~ "\" string=\"" ~ ("true" if v is string else "false") ~ "\">" ~ (v if v is string else v | tojson) ~ ""] -%} + {%- endfor -%} + {%- set name = qualified_name(fn.name, tc.get("namespace") or fn.get("namespace")) -%} + {%- set tcs.lines = tcs.lines + ["<" ~ DSML ~ " invoke name=\"" ~ name ~ "\">\n" ~ params.lines | join("\n") ~ "\n"] -%} + {%- endfor -%} + {{- "\n\n<" ~ DSML ~ " calls>\n" ~ tcs.lines | join("\n") ~ "\n" -}} + {%- endif -%} + {%- if not m.get("wo_eos", false) -%}{{- "<|end▁of▁sentence|>" -}}{%- endif -%} + + {%- else -%} + {{- raise_exception("Unknown role: " ~ m.role) -}} + {%- endif -%} + + {#- Transition tokens, only when the next message is an assistant/latest_reminder turn or this is the last one. -#} + {%- if loop.last or msgs[idx + 1].role in ["assistant", "latest_reminder"] -%} + {%- set task = m.get("task") -%} + {%- if task is not none -%} + {%- set task_tokens = {"action": "<|action|>", "query": "<|query|>", "authority": "<|authority|>", "domain": "<|domain|>", "title": "<|title|>", "read_url": "<|read_url|>"} -%} + {%- if task not in task_tokens -%}{{- raise_exception("Invalid task: '" ~ task ~ "'") -}}{%- endif -%} + {%- if task == "action" -%}{{- "<|Assistant|>" ~ ("" if thinking else "") -}}{%- endif -%} + {{- task_tokens[task] -}} + {%- elif (m.role == "user" or (m.role == "system" and idx > 0)) and (add_generation_prompt or not loop.last) -%} + {{- "<|Assistant|>" ~ ("" if thinking and (not effective_drop or idx >= state.last_user) else "") -}} + {%- endif -%} + {%- endif -%} +{%- endfor -%} diff --git a/testdata/templates/SOURCES.md b/testdata/templates/SOURCES.md new file mode 100644 index 0000000..1e3af16 --- /dev/null +++ b/testdata/templates/SOURCES.md @@ -0,0 +1,25 @@ +# Chat template sources + +## DeepSeek-V4.1-Flash + +`DeepSeek-V4.1-Flash.jinja` is an unmodified copy of the actual model-repository +template (not llama.cpp's minimal stand-in): + +- Repository: https://huggingface.co/deepseek-ai/DeepSeek-V4.1-Flash +- Revision: `314113f8a7dadb388215396ba5fbee2c610a04d6` +- File: https://huggingface.co/deepseek-ai/DeepSeek-V4.1-Flash/blob/314113f8a7dadb388215396ba5fbee2c610a04d6/chat_template.jinja + +The upstream template describes itself as a port of that repository's +`encoding/encoding.py`. It differs substantially from the existing V4 fixture: +spaced DSML `calls`/`invoke`/`parameter` tags, a system token, numeric reasoning +budgets, and tool-result merging/reordering, among other changes. + +The synthetic `deepseek-v4.1-*.json` requests exercise Go/Python Jinja2 parity, +not model execution or full model/encoder compatibility. `chat_template_kwargs` +is keyed by template name and overrides that template's neutral render defaults +in both engines (other templates still run against the requests with their +existing defaults). Efforts +cover low/medium/high/max and integer endpoints 1/100; chat mode and both thinking +control spellings are covered. The tool-history request includes JSON-encoded +arguments (normalized to a mapping as in Kronk), object arguments with string and +non-string parameters, retained reasoning, and out-of-order tool results.