chen11003 commited on
Commit
0648c43
·
0 Parent(s):

initial commit

Browse files
.gitattributes ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.ot filter=lfs diff=lfs merge=lfs -text
18
+ *.parquet filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pickle filter=lfs diff=lfs merge=lfs -text
21
+ *.pkl filter=lfs diff=lfs merge=lfs -text
22
+ *.pt filter=lfs diff=lfs merge=lfs -text
23
+ *.pth filter=lfs diff=lfs merge=lfs -text
24
+ *.rar filter=lfs diff=lfs merge=lfs -text
25
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
26
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
28
+ *.tar filter=lfs diff=lfs merge=lfs -text
29
+ *.tflite filter=lfs diff=lfs merge=lfs -text
30
+ *.tgz filter=lfs diff=lfs merge=lfs -text
31
+ *.wasm filter=lfs diff=lfs merge=lfs -text
32
+ *.xz filter=lfs diff=lfs merge=lfs -text
33
+ *.zip filter=lfs diff=lfs merge=lfs -text
34
+ *.zst filter=lfs diff=lfs merge=lfs -text
35
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
README.md ADDED
@@ -0,0 +1,99 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: apache-2.0
3
+ base_model: IFM/K2-Horizon-0.9B
4
+ language:
5
+ - en
6
+ tags:
7
+ - decision-model
8
+ - jev
9
+ - classification
10
+ - calibration
11
+ - pointer-head
12
+ library_name: transformers
13
+ ---
14
+
15
+ # K2-Type-0.9B
16
+
17
+ A 0.9B decision model in the style of TypeSafe's Jev (K2-Horizon-0.9B backbone; 1.08B parameters stored, including the base model's unused language-model head). You send one **state** (text or JSON) and any number of typed
18
+ **questions**; it returns a probability for every option of every question from **one forward pass**. It never
19
+ generates text.
20
+
21
+ | Question type | You give | You get |
22
+ | --- | --- | --- |
23
+ | `noul` | a statement, optional definitions of `false` / `true` | P(true) |
24
+ | `choice` | 1-255 named options with optional descriptions | the best option, its confidence, all probabilities |
25
+ | `score` | 2-255 ordered levels | expected level, probability per level |
26
+
27
+ Questions share the state but cannot see each other (block-causal attention mask), so adding a question never changes
28
+ another's answer. Built on [IFM/K2-Horizon-0.9B](https://huggingface.co/IFM/K2-Horizon-0.9B).
29
+
30
+ ## Results
31
+
32
+ **JevBench public set** (231 items, [jevbench](https://github.com/fstandhartinger/jevbench) commit 26eb72d,
33
+ `typesafe` adapter against this repo's server, one H200, no network):
34
+
35
+ | Tier | Correct |
36
+ | --- | --- |
37
+ | standard (72, `original.jsonl`) | 66 |
38
+ | easy (48, `easy.jsonl`) | 47 |
39
+ | hard (111, `hard.jsonl`) | 63 |
40
+ | **Total** | **176 / 231 = 0.762** |
41
+
42
+ Brier 0.328, ECE 0.065; latency p50 27 ms, p95 60 ms per decision; mean 590 input tokens per decision.
43
+ For reference, public accuracy on the JevBench v1.4 board: Gemma 4 E2B + LoRA (system-one-open) 0.732, decider-2b
44
+ 0.710, kev 0.6B 0.667, kev 4B 0.662, Qwen3.5-4B entries 0.74-0.82, Jev 1.13.0 0.866. The official JevBench score also
45
+ uses sealed items; every listed system scores well below its public accuracy there.
46
+
47
+
48
+ **Snake**: the same weights play Snake from a text board (one choice + four yes/no questions per move):
49
+ 66 food per game on 12x12 on average (max 101).
50
+
51
+ ## Quickstart
52
+
53
+ ```bash
54
+ pip install -U huggingface_hub
55
+ hf download IFM/K2-Type-0.9B --local-dir K2-Type-0.9B && cd K2-Type-0.9B
56
+ pip install -r requirements.txt
57
+ python -m jev.serve --run . --port 8000 # from this repo's root; needs one CUDA GPU
58
+ ```
59
+
60
+ The first request after start-up takes a few seconds (CUDA warm-up); later requests take about 20-60 ms.
61
+
62
+ ```bash
63
+ curl -s localhost:8000/v1/systemone -H 'Content-Type: application/json' -d '{
64
+ "state": {"subject": "Charged twice", "body": "You billed my card twice for March. Refund one or I cancel."},
65
+ "questions": {
66
+ "queue": {"type": "choice", "instructions": "Which queue handles this?",
67
+ "criteria": {"billing": "Payments and refunds", "technical": "Bugs and login", "general": "Anything else"}},
68
+ "angry": {"type": "noul", "instructions": "The customer sounds angry."},
69
+ "urgency": {"type": "score", "instructions": "How urgent is it?", "criteria": ["Low", "Normal", "High", "Critical"]}
70
+ }}'
71
+ ```
72
+
73
+ The request and response follow TypeSafe's `/v1/systemone` wire format, so clients written for Jev or Kev work
74
+ unchanged. `GET /health` reports the model name and temperature.
75
+
76
+ This repository contains the weights and the minimal code needed to serve them (`jev/`: input encoding, the pointer
77
+ head, and the HTTP server). Training code and data are not released at this time.
78
+
79
+ Requires transformers >= 5.17 (remote code); tested on torch 2.8. Do not use the backbone for text generation: its weights were trained
80
+ for the decision head, and the language-model head is left from the base model. Use the `jev/` server.
81
+
82
+ ## How it works
83
+
84
+ - Input layout: `<state> ... | <q> question <opt> option </opt> ... <decide> | <q> ...`, using five reserved tokens of
85
+ the base tokenizer (`decision_config.json`).
86
+ - A pointer head (`pointer_head.safetensors`) scores each option's `</opt>` hidden state against the question's
87
+ `<decide>` hidden state; a softmax at temperature 1.478 gives the probabilities.
88
+ - Training, in short: full fine-tune on ~354k decision records (public classification/NLI/QA sets, Kev's decision
89
+ data, game positions with exact or search labels, and synthetic decision items written and blind-verified by a large
90
+ model), targets mixed with soft labels from a 7B teacher decision model; then 50 iterations of PPO on Snake; then a
91
+ temperature refit on held-out calibration data. Training data were checked against every Kev evaluation suite and
92
+ the 231 JevBench public items: no exact or containment overlap.
93
+
94
+ ## Limits
95
+
96
+ - One pass, no reasoning: multi-step arithmetic, date differences and very long documents (> 8192 tokens) are weak.
97
+ - Calibration is fitted on Kev's calibration suite; on other distributions probabilities can be over- or
98
+ under-confident (JevBench public ECE 0.065).
99
+ - Answers are bounded by the options you give; it cannot say "none of these" unless you offer that option.
chat_template.jinja ADDED
@@ -0,0 +1,1000 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {%- if tool_presentation is defined -%}
2
+ {{- raise_exception("Unsupported argument: tool_presentation. Use tool_presentation_format with one of: json, xml, markdown.") -}}
3
+ {%- endif -%}
4
+ {%- if tool_calling_format is defined -%}
5
+ {{- raise_exception("Unsupported argument: tool_calling_format. Use tool_call_format with one of: json, xml, xml_typed.") -}}
6
+ {%- endif -%}
7
+ {%- if tool_format is defined -%}
8
+ {{- raise_exception("Unsupported argument: tool_format. Use tool_call_format with one of: json, xml, xml_typed.") -}}
9
+ {%- endif -%}
10
+ {%- set tool_presentation_fmt = tool_presentation_format | default('markdown') -%}
11
+ {%- set tool_call_fmt = tool_call_format | default('xml') -%}
12
+ {%- if tool_presentation_fmt != 'json' and tool_presentation_fmt != 'xml' and tool_presentation_fmt != 'markdown' -%}
13
+ {{- raise_exception("Unsupported tool_presentation_format: '" ~ tool_presentation_fmt ~ "'. Supported formats: json, xml, markdown.") -}}
14
+ {%- endif -%}
15
+ {%- if tool_call_fmt != 'json' and tool_call_fmt != 'xml' and tool_call_fmt != 'xml_typed' -%}
16
+ {{- raise_exception("Unsupported tool_call_format: '" ~ tool_call_fmt ~ "'. Supported formats: json, xml, xml_typed.") -}}
17
+ {%- endif -%}
18
+
19
+ {#- Renderability state, computed during validate_tools (single walk, no extra -#}
20
+ {#- traversal at render time): ok = working flag for the tool being validated; -#}
21
+ {#- bad = pipe-delimited indices of tools that must render as verbatim JSON. -#}
22
+ {%- set RB = namespace(ok=true, bad='|') -%}
23
+
24
+ {%- macro value_contains_mapping(v) -%}
25
+ {%- if v is mapping -%}
26
+ true
27
+ {%- elif v is sequence and v is not string -%}
28
+ {%- set f = namespace(x='false') -%}
29
+ {%- for c in v -%}{%- if value_contains_mapping(c) == 'true' -%}{%- set f.x = 'true' -%}{%- endif -%}{%- endfor -%}
30
+ {{- f.x -}}
31
+ {%- else -%}
32
+ false
33
+ {%- endif -%}
34
+ {%- endmacro -%}
35
+
36
+ {#- $ref inlining state: defs = local $defs of the tool being rendered; seen = -#}
37
+ {#- pipe-delimited names already expanded for this tool (each def inlines at most -#}
38
+ {#- once; later references render by def name; cycles terminate immediately). -#}
39
+ {#- $ref-sibling annotations (description/default/...) merge OVER the def at -#}
40
+ {#- the inline site, so use-site annotations win and are never dropped. -#}
41
+ {%- set REFS = namespace(defs={}, seen='|') -%}
42
+
43
+ {%- macro render_compact_type_name(type_name, spec) -%}
44
+ {%- if type_name == "array" -%}
45
+ array[{%- if 'items' in spec -%}{{ render_compact_type(spec['items']) }}{%- else -%}any{%- endif -%}]
46
+ {%- elif type_name -%}
47
+ {{- type_name -}}
48
+ {%- else -%}
49
+ any
50
+ {%- endif -%}
51
+ {%- endmacro -%}
52
+
53
+ {%- macro render_compact_type(spec) -%}
54
+ {%- if spec is not mapping -%}
55
+ any
56
+ {%- elif spec.type is defined and spec.type is sequence and spec.type is not string and spec.type | length > 0 -%}
57
+ {%- for type_name in spec.type -%}{{ render_compact_type_name(type_name, spec) }}{%- if not loop.last -%}|{%- endif -%}{%- endfor -%}
58
+ {%- elif spec.type is defined and spec.type is sequence and spec.type is not string -%}
59
+ any
60
+ {%- elif spec.type -%}
61
+ {{- render_compact_type_name(spec.type, spec) -}}
62
+ {%- elif spec['$ref'] is string -%}
63
+ {{- spec['$ref'].split('/') | last -}}
64
+ {%- elif spec.oneOf -%}
65
+ oneOf[{%- for variant in spec.oneOf -%}{{ render_compact_type(variant) }}{%- if not loop.last -%}|{%- endif -%}{%- endfor -%}]
66
+ {%- elif spec.anyOf -%}
67
+ anyOf[{%- for variant in spec.anyOf -%}{{ render_compact_type(variant) }}{%- if not loop.last -%}|{%- endif -%}{%- endfor -%}]
68
+ {%- elif spec.properties -%}
69
+ object
70
+ {%- elif 'items' in spec -%}
71
+ array[{{ render_compact_type(spec['items']) }}]
72
+ {%- else -%}
73
+ any
74
+ {%- endif -%}
75
+ {%- endmacro -%}
76
+
77
+ {%- macro render_markdown_type_name(type_name, spec) -%}
78
+ {%- if type_name == "array" -%}
79
+ array of {% if 'items' in spec %}{{ render_markdown_type(spec['items']) }}{% else %}any{% endif %}
80
+ {%- elif type_name -%}
81
+ {{- type_name -}}
82
+ {%- else -%}
83
+ any
84
+ {%- endif -%}
85
+ {%- endmacro -%}
86
+
87
+ {%- macro render_markdown_type(spec) -%}
88
+ {%- if spec is sameas true -%}
89
+ True
90
+ {%- elif spec is sameas false -%}
91
+ False
92
+ {%- elif spec is not mapping -%}
93
+ any
94
+ {%- elif spec.type is defined and spec.type is sequence and spec.type is not string and spec.type | length > 0 -%}
95
+ {%- for type_name in spec.type -%}{{ render_markdown_type_name(type_name, spec) }}{% if not loop.last %} or {% endif %}{%- endfor -%}
96
+ {%- elif spec.type is defined and spec.type is sequence and spec.type is not string -%}
97
+ any
98
+ {%- elif spec.type -%}
99
+ {{- render_markdown_type_name(spec.type, spec) -}}
100
+ {%- elif spec['$ref'] is string -%}
101
+ {{- spec['$ref'].split('/') | last -}}
102
+ {%- elif spec.oneOf -%}
103
+ oneOf[{%- for variant in spec.oneOf -%}{{ render_markdown_type(variant) }}{% if not loop.last %} or {% endif %}{%- endfor -%}]
104
+ {%- elif spec.anyOf -%}
105
+ anyOf[{%- for variant in spec.anyOf -%}{{ render_markdown_type(variant) }}{% if not loop.last %} or {% endif %}{%- endfor -%}]
106
+ {%- elif spec.properties -%}
107
+ object
108
+ {%- elif 'items' in spec -%}
109
+ array of {{ render_markdown_type(spec['items']) }}
110
+ {%- else -%}
111
+ any
112
+ {%- endif -%}
113
+ {%- endmacro -%}
114
+
115
+ {%- macro render_xml_text(value) -%}
116
+ {{- value.split() | join(" ") -}}
117
+ {%- endmacro -%}
118
+
119
+ {%- macro render_python_string(value) -%}
120
+ '{{- value.split() | join(" ") | replace("\\", "\\\\") | replace("'", "\\'") -}}'
121
+ {%- endmacro -%}
122
+
123
+ {%- macro render_python_repr(value) -%}
124
+ {%- if value is string -%}
125
+ {{ render_python_string(value) }}
126
+ {%- elif value is sameas true -%}
127
+ True
128
+ {%- elif value is sameas false -%}
129
+ False
130
+ {%- elif value is none -%}
131
+ None
132
+ {%- elif value is mapping -%}
133
+ {{- "{" -}}
134
+ {%- for key, child in value | items -%}
135
+ {{ render_python_repr(key) }}: {{ render_python_repr(child) }}{%- if not loop.last -%}, {% endif -%}
136
+ {%- endfor -%}
137
+ {{- "}" -}}
138
+ {%- elif value is sequence -%}
139
+ {{- "[" -}}
140
+ {%- for child in value -%}
141
+ {{ render_python_repr(child) }}{%- if not loop.last -%}, {% endif -%}
142
+ {%- endfor -%}
143
+ {{- "]" -}}
144
+ {%- else -%}
145
+ {{- value -}}
146
+ {%- endif -%}
147
+ {%- endmacro -%}
148
+
149
+ {%- macro render_xml_value(value) -%}
150
+ {%- if value is string -%}{{ render_xml_text(value) }}{%- else -%}{{ render_python_repr(value) }}{%- endif -%}
151
+ {%- endmacro -%}
152
+
153
+ {%- macro render_xml_enum_value(value) -%}
154
+ {%- if value is string -%}"{{- value | replace("\\", "\\\\") | replace("\"", "\\\"") -}}"{%- else -%}"{{- render_python_repr(value) | replace("\\", "\\\\") | replace("\"", "\\\"") -}}"{%- endif -%}
155
+ {%- endmacro -%}
156
+
157
+ {%- macro render_xml_enum(values) -%}
158
+ {%- for value in values -%}{{ render_xml_enum_value(value) }}{%- if not loop.last -%}|{%- endif -%}{%- endfor -%}
159
+ {%- endmacro -%}
160
+
161
+ {%- macro render_xml_default_attr(value) -%}
162
+ {{- " default=" }}{%- if value is string -%}"{{- value | replace("\\", "\\\\") | replace("\"", "\\\"") -}}"{%- else -%}{{ render_xml_value(value) }}{%- endif -%}
163
+ {%- endmacro -%}
164
+
165
+ {%- macro render_xml_attr(name, value) -%}
166
+ {{- " " + name + "=" }}{%- if value == "" -%}""{%- else -%}{{ render_xml_value(value) }}{%- endif -%}
167
+ {%- endmacro -%}
168
+
169
+ {%- macro validate_schema(spec, path, lenient=false, classify=true, in_variant=false) -%}
170
+ {%- if spec is mapping -%}
171
+ {%- if not lenient -%}
172
+ {%- if spec.required is defined -%}
173
+ {%- if spec.required is string or spec.required is not sequence -%}
174
+ {{- raise_exception("Schema '" + path + "' has 'required' but it is not a list.") -}}
175
+ {%- endif -%}
176
+ {%- if spec.required | length > 0 and not spec.properties and not in_variant -%}
177
+ {{- raise_exception("Schema '" + path + "' has required fields but no properties object to define them.") -}}
178
+ {%- endif -%}
179
+ {%- if spec.properties -%}
180
+ {%- for required_name in spec.required -%}
181
+ {%- if required_name not in spec.properties -%}
182
+ {{- raise_exception("Schema '" + path + "' marks '" + required_name + "' as required, but that property is not defined in properties.") -}}
183
+ {%- endif -%}
184
+ {%- endfor -%}
185
+ {%- endif -%}
186
+ {%- endif -%}
187
+ {%- endif -%}
188
+ {#- renderability classification, piggybacking on this walk (no raises here): -#}
189
+ {#- constructs the pretty renderer does not fully handle flip RB.ok so the -#}
190
+ {#- tool falls back to verbatim JSON. Skipped entirely for json presentation. -#}
191
+ {%- if classify -%}
192
+ {%- for key, value in spec | items -%}
193
+ {%- if key == '$ref' -%}
194
+ {%- if value is not string -%}{%- set RB.ok = false -%}
195
+ {%- elif not (value.startswith('#/$defs/') or value.startswith('#/definitions/')) -%}{%- set RB.ok = false -%}{%- endif -%}
196
+ {%- elif key == '$defs' or key == 'definitions' -%}
197
+ {%- if value is mapping -%}
198
+ {%- for dk, dv in value | items -%}
199
+ {{- validate_schema(dv, path + ".$defs." + dk, true) -}}
200
+ {%- endfor -%}
201
+ {%- else -%}{%- set RB.ok = false -%}{%- endif -%}
202
+ {%- elif key == 'type' -%}
203
+ {%- if value is mapping -%}{%- set RB.ok = false -%}{%- endif -%}
204
+ {%- elif key == 'enum' -%}
205
+ {%- if value is string or value is mapping or value is not sequence -%}{%- set RB.ok = false -%}{%- endif -%}
206
+ {%- elif key == 'items' -%}
207
+ {#- any items shape renders: mapping structurally, others via repr detail -#}
208
+ {%- elif key == 'oneOf' or key == 'anyOf' -%}
209
+ {%- if value is mapping or value is string or value is not sequence -%}{%- set RB.ok = false -%}{%- endif -%}
210
+ {%- elif key == 'required' -%}
211
+ {%- if value and not spec.properties -%}{%- set RB.ok = false -%}{%- endif -%}
212
+ {%- elif ('|' ~ key ~ '|') in '|description|default|title|examples|properties|patternProperties|additionalProperties|returns|' -%}
213
+ {%- elif value is mapping -%}
214
+ {%- for uk, uv in value | items -%}
215
+ {%- if value_contains_mapping(uv) == 'true' -%}{%- set RB.ok = false -%}{%- endif -%}
216
+ {%- endfor -%}
217
+ {%- elif value is sequence and value is not string -%}
218
+ {%- if value_contains_mapping(value) == 'true' -%}{%- set RB.ok = false -%}{%- endif -%}
219
+ {%- endif -%}
220
+ {%- endfor -%}
221
+ {%- endif -%}
222
+ {%- if spec.properties -%}
223
+ {%- for child_name, child_spec in spec.properties | items -%}
224
+ {{- validate_schema(child_spec, path + "." + child_name, lenient, classify) -}}
225
+ {%- endfor -%}
226
+ {%- endif -%}
227
+ {%- if 'items' in spec -%}{{- validate_schema(spec['items'], path + "[]", lenient, classify) -}}{%- endif -%}
228
+ {%- if spec.oneOf -%}
229
+ {%- for variant in spec.oneOf -%}{{- validate_schema(variant, path + ".oneOf[" + (loop.index0 | string) + "]", lenient, classify, true) -}}{%- endfor -%}
230
+ {%- endif -%}
231
+ {%- if spec.anyOf -%}
232
+ {%- for variant in spec.anyOf -%}{{- validate_schema(variant, path + ".anyOf[" + (loop.index0 | string) + "]", lenient, classify, true) -}}{%- endfor -%}
233
+ {%- endif -%}
234
+ {%- if spec.additionalProperties is mapping -%}{{- validate_schema(spec.additionalProperties, path + ".additionalProperties", lenient, classify) -}}{%- endif -%}
235
+ {%- if spec.patternProperties is mapping -%}
236
+ {%- for pattern, pattern_spec in spec.patternProperties | items -%}
237
+ {{- validate_schema(pattern_spec, path + ".patternProperties[" + pattern + "]", lenient, classify) -}}
238
+ {%- endfor -%}
239
+ {%- endif -%}
240
+ {%- if spec.returns is mapping -%}{{- validate_schema(spec.returns, path + ".returns", lenient, classify) -}}{%- endif -%}
241
+ {%- endif -%}
242
+ {%- endmacro -%}
243
+
244
+ {%- macro validate_tools(tools_list, classify=true) -%}
245
+ {%- set RB.bad = '|' -%}
246
+ {%- for tool in tools_list -%}
247
+ {%- set fn = tool.function if tool.function is defined else tool -%}
248
+ {%- set RB.ok = true -%}
249
+ {%- if fn.parameters is defined and fn.parameters is string -%}
250
+ {{- raise_exception("tool.function.parameters must be a dict, not a JSON string. Parse it before passing to the template.") -}}
251
+ {%- endif -%}
252
+ {%- if fn.parameters is not defined or fn.parameters is none -%}
253
+ {%- if fn.arguments is defined -%}
254
+ {{- raise_exception("Tool '" + fn.name + "' has 'arguments' instead of 'parameters'. Rename 'arguments' to 'parameters'.") -}}
255
+ {%- else -%}
256
+ {{- raise_exception("Tool '" + fn.name + "' is missing required 'parameters' field. Each tool must have a 'parameters' dict with 'type', 'properties', and 'required' keys.") -}}
257
+ {%- endif -%}
258
+ {%- endif -%}
259
+ {{- validate_schema(fn.parameters, "tool." + fn.name + ".parameters", false, classify) -}}
260
+ {%- if classify -%}
261
+ {%- if fn.parameters is mapping -%}
262
+ {#- unknown container-valued keys at the parameters ROOT are never rendered -#}
263
+ {#- by the pretty path (root extras are dropped) -> verbatim fallback. -#}
264
+ {%- for rk, rv in fn.parameters | items -%}
265
+ {%- if rk not in ['type', 'description', 'enum', 'default', 'properties', 'required', 'optional', 'title', 'items', 'oneOf', 'anyOf', 'additionalProperties', 'patternProperties', 'returns', 'examples', '$defs', 'definitions', '$ref'] -%}
266
+ {%- if rv is mapping or (rv is sequence and rv is not string) -%}{%- set RB.ok = false -%}{%- endif -%}
267
+ {%- endif -%}
268
+ {%- endfor -%}
269
+ {%- else -%}
270
+ {%- set RB.ok = false -%}
271
+ {%- endif -%}
272
+ {%- endif -%}
273
+ {%- if fn.returns is mapping -%}{{- validate_schema(fn.returns, "tool." + fn.name + ".returns", false, classify) -}}{%- endif -%}
274
+ {%- if classify and fn.returns is not defined and fn.response is mapping -%}{{- validate_schema(fn.response, "tool." + fn.name + ".response", true) -}}{%- endif -%}
275
+ {#- unknown container-valued keys at the FUNCTION level are never rendered -> fallback. -#}
276
+ {%- if classify -%}
277
+ {%- for fk, fv in fn | items -%}
278
+ {%- if fk not in ['name', 'description', 'parameters', 'returns', 'response', 'type', 'function'] -%}
279
+ {%- if fv is mapping or (fv is sequence and fv is not string) -%}{%- set RB.ok = false -%}{%- endif -%}
280
+ {%- endif -%}
281
+ {%- endfor -%}
282
+ {%- endif -%}
283
+ {%- if not RB.ok -%}{%- set RB.bad = RB.bad ~ loop.index0 ~ '|' -%}{%- endif -%}
284
+ {%- endfor -%}
285
+ {%- endmacro -%}
286
+
287
+ {%- macro render_tools_json(tools_list) -%}
288
+ {{- "<ifm|tools>" }}
289
+ {%- for tool in tools_list %}
290
+ {{- "\n" }}
291
+ {{- tool | tojson }}
292
+ {%- endfor %}
293
+ {{- "\n</ifm|tools>" }}
294
+ {%- endmacro -%}
295
+
296
+ {%- macro render_xml_schema_attrs(spec, include_value_attrs) -%}
297
+ {%- if spec is mapping -%}
298
+ {%- set structural_keys = ["type", "description", "enum", "default", "properties", "required", "items", "oneOf", "anyOf", "additionalProperties", "patternProperties", "returns"] -%}
299
+ {%- if include_value_attrs and spec.enum -%}{{- " enum=" }}{{ render_xml_enum(spec.enum) }}{%- endif -%}
300
+ {%- if include_value_attrs and spec.default is defined -%}{{ render_xml_default_attr(spec.default) }}{%- endif -%}
301
+ {%- if spec.additionalProperties is defined and spec.additionalProperties is not mapping -%}{{ render_xml_attr("additionalProperties", spec.additionalProperties) }}{%- endif -%}
302
+ {%- if spec.patternProperties is defined and spec.patternProperties is not mapping -%}{{ render_xml_attr("patternProperties", spec.patternProperties) }}{%- endif -%}
303
+ {%- for key, value in spec | items -%}
304
+ {%- if key not in structural_keys -%}
305
+ {{ render_xml_attr(key, value) }}
306
+ {%- endif -%}
307
+ {%- endfor -%}
308
+ {%- endif -%}
309
+ {%- endmacro -%}
310
+
311
+ {%- macro xml_schema_has_children(spec, include_properties, include_description) -%}
312
+ {%- if spec is not mapping -%}
313
+ false
314
+ {%- elif (include_description and spec.description is defined) or (include_properties and spec.properties) or 'items' in spec or spec.oneOf or spec.anyOf or spec.additionalProperties is mapping or spec.patternProperties is mapping or spec.returns is defined -%}
315
+ true
316
+ {%- else -%}
317
+ false
318
+ {%- endif -%}
319
+ {%- endmacro -%}
320
+
321
+ {%- macro render_xml_schema_node(tag, spec, include_properties) -%}
322
+ {%- if spec is mapping and spec['$ref'] is string -%}
323
+ {%- set _r = spec['$ref'] -%}
324
+ {%- set _k = _r[8:] if _r.startswith('#/$defs/') else (_r[14:] if _r.startswith('#/definitions/') else none) -%}
325
+ {%- if _k is not none and ('|' + _k + '|') not in REFS.seen and REFS.defs[_k] is mapping -%}
326
+ {%- set spec = dict((REFS.defs[_k] | items | list) + (spec | items | rejectattr('0', 'equalto', '$ref') | list)) -%}
327
+ {%- set REFS.seen = REFS.seen + _k + '|' -%}
328
+ {%- if spec['$ref'] is string -%}
329
+ {%- set _r2 = spec['$ref'] -%}
330
+ {%- set _k2 = _r2[8:] if _r2.startswith('#/$defs/') else (_r2[14:] if _r2.startswith('#/definitions/') else none) -%}
331
+ {%- if _k2 is not none and REFS.defs[_k2] is mapping -%}
332
+ {%- set spec = dict((REFS.defs[_k2] | items | list) + (spec | items | rejectattr('0', 'equalto', '$ref') | list)) -%}
333
+ {%- set REFS.seen = REFS.seen + _k2 + '|' -%}
334
+ {%- endif -%}
335
+ {%- endif -%}
336
+ {%- endif -%}
337
+ {%- endif -%}
338
+ {%- if spec is mapping -%}
339
+ {{- "<" + tag + " type=" + render_compact_type(spec) }}{{ render_xml_schema_attrs(spec, true) }}
340
+ {%- if xml_schema_has_children(spec, include_properties, true) == 'true' -%}
341
+ {{- ">" }}{{ render_xml_schema_children(spec, include_properties, true) }}{{- "</" + tag + ">" }}
342
+ {%- else -%}
343
+ {{- "/>" }}
344
+ {%- endif -%}
345
+ {%- else -%}
346
+ {{- "<" + tag + ">" }}{{ render_xml_value(spec) }}{{- "</" + tag + ">" }}
347
+ {%- endif -%}
348
+ {%- endmacro -%}
349
+
350
+ {%- macro render_xml_pattern_property(pattern, spec) -%}
351
+ {%- if spec is mapping and spec['$ref'] is string -%}
352
+ {%- set _r = spec['$ref'] -%}
353
+ {%- set _k = _r[8:] if _r.startswith('#/$defs/') else (_r[14:] if _r.startswith('#/definitions/') else none) -%}
354
+ {%- if _k is not none and ('|' + _k + '|') not in REFS.seen and REFS.defs[_k] is mapping -%}
355
+ {%- set spec = dict((REFS.defs[_k] | items | list) + (spec | items | rejectattr('0', 'equalto', '$ref') | list)) -%}
356
+ {%- set REFS.seen = REFS.seen + _k + '|' -%}
357
+ {%- if spec['$ref'] is string -%}
358
+ {%- set _r2 = spec['$ref'] -%}
359
+ {%- set _k2 = _r2[8:] if _r2.startswith('#/$defs/') else (_r2[14:] if _r2.startswith('#/definitions/') else none) -%}
360
+ {%- if _k2 is not none and REFS.defs[_k2] is mapping -%}
361
+ {%- set spec = dict((REFS.defs[_k2] | items | list) + (spec | items | rejectattr('0', 'equalto', '$ref') | list)) -%}
362
+ {%- set REFS.seen = REFS.seen + _k2 + '|' -%}
363
+ {%- endif -%}
364
+ {%- endif -%}
365
+ {%- endif -%}
366
+ {%- endif -%}
367
+ {%- if spec is mapping -%}
368
+ {{- "<patternProperty" }}{{ render_xml_attr("pattern", pattern) }}{{- " type=" + render_compact_type(spec) }}{{ render_xml_schema_attrs(spec, true) }}
369
+ {%- if xml_schema_has_children(spec, true, true) == 'true' -%}
370
+ {{- ">" }}{{ render_xml_schema_children(spec, true, true) }}{{- "</patternProperty>" }}
371
+ {%- else -%}
372
+ {{- "/>" }}
373
+ {%- endif -%}
374
+ {%- else -%}
375
+ {{- "<patternProperty" }}{{ render_xml_attr("pattern", pattern) }}{{- ">" }}{{ render_xml_value(spec) }}{{- "</patternProperty>" }}
376
+ {%- endif -%}
377
+ {%- endmacro -%}
378
+
379
+ {%- macro render_xml_schema_children(spec, include_properties, include_description) -%}
380
+ {%- if include_description and spec.description is defined -%}{{- "<description>" }}{{ spec.description }}{{- "</description>" }}{%- endif -%}
381
+ {%- if include_properties and spec.properties -%}
382
+ {%- for child_name, child_spec in spec.properties | items -%}
383
+ {{- render_xml_param(child_name, child_spec, spec.required or []) }}
384
+ {%- endfor -%}
385
+ {%- endif -%}
386
+ {%- if 'items' in spec -%}{{ render_xml_schema_node("items", spec['items'], true) }}{%- endif -%}
387
+ {%- if spec.oneOf -%}
388
+ {{- "<oneOf>" }}
389
+ {%- for variant in spec.oneOf -%}{{ render_xml_schema_node("variant", variant, true) }}{%- endfor -%}
390
+ {{- "</oneOf>" }}
391
+ {%- endif -%}
392
+ {%- if spec.anyOf -%}
393
+ {{- "<anyOf>" }}
394
+ {%- for variant in spec.anyOf -%}{{ render_xml_schema_node("variant", variant, true) }}{%- endfor -%}
395
+ {{- "</anyOf>" }}
396
+ {%- endif -%}
397
+ {%- if spec.additionalProperties is mapping -%}{{ render_xml_schema_node("additionalProperties", spec.additionalProperties, true) }}{%- endif -%}
398
+ {%- if spec.patternProperties is mapping -%}
399
+ {{- "<patternProperties>" }}
400
+ {%- for pattern, pattern_spec in spec.patternProperties | items -%}{{ render_xml_pattern_property(pattern, pattern_spec) }}{%- endfor -%}
401
+ {{- "</patternProperties>" }}
402
+ {%- elif spec.patternProperties is defined -%}<patternProperties>{{ render_xml_value(spec.patternProperties) }}</patternProperties>{%- endif -%}
403
+ {%- if spec.returns is mapping -%}{{ render_xml_schema_node("returns", spec.returns, true) }}{%- elif spec.returns is defined -%}<returns>{{ render_xml_value(spec.returns) }}</returns>{%- endif -%}
404
+ {%- endmacro -%}
405
+
406
+ {%- macro render_xml_param(name, spec, required_list) -%}
407
+ {%- if spec is mapping and spec['$ref'] is string -%}
408
+ {%- set _r = spec['$ref'] -%}
409
+ {%- set _k = _r[8:] if _r.startswith('#/$defs/') else (_r[14:] if _r.startswith('#/definitions/') else none) -%}
410
+ {%- if _k is not none and ('|' + _k + '|') not in REFS.seen and REFS.defs[_k] is mapping -%}
411
+ {%- set spec = dict((REFS.defs[_k] | items | list) + (spec | items | rejectattr('0', 'equalto', '$ref') | list)) -%}
412
+ {%- set REFS.seen = REFS.seen + _k + '|' -%}
413
+ {%- if spec['$ref'] is string -%}
414
+ {%- set _r2 = spec['$ref'] -%}
415
+ {%- set _k2 = _r2[8:] if _r2.startswith('#/$defs/') else (_r2[14:] if _r2.startswith('#/definitions/') else none) -%}
416
+ {%- if _k2 is not none and REFS.defs[_k2] is mapping -%}
417
+ {%- set spec = dict((REFS.defs[_k2] | items | list) + (spec | items | rejectattr('0', 'equalto', '$ref') | list)) -%}
418
+ {%- set REFS.seen = REFS.seen + _k2 + '|' -%}
419
+ {%- endif -%}
420
+ {%- endif -%}
421
+ {%- endif -%}
422
+ {%- endif -%}
423
+ {{- "<param name=" + name + " type=" + render_compact_type(spec) }}
424
+ {%- if name in (required_list or []) -%}{{- " required=true" }}{%- endif -%}
425
+ {%- if spec.enum -%}{{- " enum=" }}{{ render_xml_enum(spec.enum) }}{%- endif -%}
426
+ {%- if spec.default is defined -%}{{ render_xml_default_attr(spec.default) }}{%- endif -%}
427
+ {{- render_xml_schema_attrs(spec, false) }}
428
+ {%- if spec.description or xml_schema_has_children(spec, true, false) == 'true' -%}
429
+ {{- ">" }}
430
+ {%- if spec.description -%}{{ spec.description }}{%- endif -%}
431
+ {{- render_xml_schema_children(spec, true, false) }}
432
+ {{- "</param>" }}
433
+ {%- else -%}
434
+ {{- "/>" }}
435
+ {%- endif -%}
436
+ {%- endmacro -%}
437
+
438
+ {%- macro render_tools_xml(tools_list) -%}
439
+ {{- "<ifm|tools>" }}
440
+ {%- for tool in tools_list -%}
441
+ {%- set fn = tool.function if tool.function is defined else tool -%}
442
+ {%- set REFS.defs = fn.parameters['$defs'] if (fn.parameters is mapping and fn.parameters['$defs'] is mapping) else (fn.parameters['definitions'] if (fn.parameters is mapping and fn.parameters['definitions'] is mapping) else {}) -%}
443
+ {%- set REFS.seen = '|' -%}
444
+ {%- set fnp = namespace(p=fn.parameters) -%}
445
+ {%- if fnp.p is mapping and fnp.p['$ref'] is string -%}
446
+ {%- set _r = fnp.p['$ref'] -%}
447
+ {%- set _k = _r[8:] if _r.startswith('#/$defs/') else (_r[14:] if _r.startswith('#/definitions/') else none) -%}
448
+ {%- if _k is not none and REFS.defs[_k] is mapping -%}
449
+ {%- set fnp.p = dict((REFS.defs[_k] | items | list) + (fnp.p | items | rejectattr('0', 'equalto', '$ref') | list)) -%}
450
+ {%- set REFS.seen = REFS.seen + _k + '|' -%}
451
+ {%- endif -%}
452
+ {%- endif -%}
453
+ {{- "\n<function name=" + fn.name + ">" }}
454
+ {%- if fn.description -%}
455
+ {{- "<description>" }}{{ fn.description }}{{- "</description>" }}
456
+ {%- endif -%}
457
+ {{- "<parameters>" }}
458
+ {%- if fnp.p and fnp.p.properties -%}
459
+ {%- for pname, pspec in fnp.p.properties | items -%}
460
+ {{- render_xml_param(pname, pspec, fnp.p.required or []) }}
461
+ {%- endfor -%}
462
+ {%- elif fnp.p is mapping and (fnp.p.oneOf or fnp.p.anyOf or 'items' in fnp.p) -%}
463
+ {{- render_xml_schema_children(fnp.p, true, false) }}
464
+ {%- endif -%}
465
+ {{- "</parameters>" }}
466
+ {%- set fn_ret = fn.returns if fn.returns is defined else fn.response -%}
467
+ {%- if fn_ret is mapping -%}{{ render_xml_schema_node("returns", fn_ret, true) }}{%- elif fn_ret is defined -%}<returns>{{ render_xml_value(fn_ret) }}</returns>{%- endif -%}
468
+ {{- "</function>" }}
469
+ {%- endfor -%}
470
+ {{- "\n</ifm|tools>" }}
471
+ {%- endmacro -%}
472
+
473
+ {%- macro render_markdown_literal(value) -%}
474
+ {%- if value is string and value == "" -%}""
475
+ {%- elif value is string -%}`{{ value | replace("\n", "\\n") }}`
476
+ {%- else -%}`{{ render_python_repr(value) }}`
477
+ {%- endif -%}
478
+ {%- endmacro -%}
479
+
480
+ {%- macro render_allowed_values(values) -%}
481
+ {%- for value in values -%}{{ render_markdown_literal(value) }}{% if not loop.last %}, {% endif %}{%- endfor -%}
482
+ {%- endmacro -%}
483
+
484
+ {%- macro render_markdown_value(value) -%}
485
+ {%- if value is string and value == "" -%}""{%- elif value is string -%}{{ value }}{%- else -%}{{ render_python_repr(value) }}{%- endif -%}
486
+ {%- endmacro -%}
487
+
488
+ {%- macro render_markdown_detail(indent, label, value) -%}
489
+ {{- "\n" + indent + " - " + label + ": " }}{{ render_markdown_value(value) }}
490
+ {%- endmacro -%}
491
+
492
+ {%- macro render_markdown_metadata_detail(label, value) -%}
493
+ {{- "\n- " + label + ": " }}{{ render_markdown_value(value) }}
494
+ {%- endmacro -%}
495
+
496
+ {%- macro render_markdown_schema_annotations(spec, indent, include_value_details) -%}
497
+ {%- if include_value_details and spec.description is defined -%}{{ render_markdown_detail(indent, "Description", spec.description | replace("\n", "\n" + indent + " ")) }}{%- endif -%}
498
+ {%- if include_value_details and spec.enum is defined -%}{{- "\n" + indent + " - Allowed values: " }}{{ render_allowed_values(spec.enum) }}{%- endif -%}
499
+ {%- if include_value_details and spec.default is defined -%}{{- "\n" + indent + " - Default: " }}{{ render_markdown_literal(spec.default) }}{%- endif -%}
500
+ {%- if spec.additionalProperties is defined -%}
501
+ {%- if spec.additionalProperties is mapping -%}
502
+ {{- "\n" + indent + " - Additional properties *(" + render_markdown_type(spec.additionalProperties) + ")*" }}
503
+ {{- render_markdown_schema_details(spec.additionalProperties, indent + " ", true) }}
504
+ {%- else -%}
505
+ {{ render_markdown_detail(indent, "Additional properties", spec.additionalProperties) }}
506
+ {%- endif -%}
507
+ {%- endif -%}
508
+ {%- endmacro -%}
509
+
510
+ {%- macro render_markdown_metadata_annotations(spec) -%}
511
+ {%- if spec.description is defined -%}{{ render_markdown_metadata_detail("Description", spec.description | replace("\n", "\n ")) }}{%- endif -%}
512
+ {%- if spec.enum is defined -%}{{- "\n- Allowed values: " }}{{ render_allowed_values(spec.enum) }}{%- endif -%}
513
+ {%- if spec.default is defined -%}{{- "\n- Default: " }}{{ render_markdown_literal(spec.default) }}{%- endif -%}
514
+ {%- if spec.additionalProperties is defined -%}
515
+ {%- if spec.additionalProperties is mapping -%}
516
+ {{- "\n- Additional properties *(" + render_markdown_type(spec.additionalProperties) + ")*" }}
517
+ {{- render_markdown_schema_details(spec.additionalProperties, "", true) }}
518
+ {%- else -%}
519
+ {{ render_markdown_metadata_detail("Additional properties", spec.additionalProperties) }}
520
+ {%- endif -%}
521
+ {%- endif -%}
522
+ {%- endmacro -%}
523
+
524
+ {%- macro render_markdown_schema_extras(spec, indent) -%}
525
+ {%- set rendered_keys = ["type", "description", "enum", "default", "properties", "required", "items", "oneOf", "anyOf", "additionalProperties", "patternProperties", "returns"] -%}
526
+ {%- for key, value in spec | items -%}
527
+ {%- if key not in rendered_keys -%}
528
+ {{- "\n" + indent + " - " + key + ": " }}{{ render_markdown_value(value) }}
529
+ {%- endif -%}
530
+ {%- endfor -%}
531
+ {%- endmacro -%}
532
+
533
+ {%- macro render_markdown_metadata_extras(spec) -%}
534
+ {%- set rendered_keys = ["type", "description", "enum", "default", "properties", "required", "items", "oneOf", "anyOf", "additionalProperties", "patternProperties", "returns"] -%}
535
+ {%- for key, value in spec | items -%}
536
+ {%- if key not in rendered_keys -%}
537
+ {{- "\n- " + key + ": " }}{{ render_markdown_value(value) }}
538
+ {%- endif -%}
539
+ {%- endfor -%}
540
+ {%- endmacro -%}
541
+
542
+ {%- macro markdown_schema_has_extra(spec) -%}
543
+ {%- set rendered_keys = ["type", "description", "enum", "default", "properties", "required", "items", "oneOf", "anyOf", "additionalProperties", "patternProperties", "returns"] -%}
544
+ {%- set found = namespace(value='false') -%}
545
+ {%- for key, value in spec | items -%}
546
+ {%- if key not in rendered_keys -%}{%- set found.value = 'true' -%}{%- endif -%}
547
+ {%- endfor -%}
548
+ {{- found.value -}}
549
+ {%- endmacro -%}
550
+
551
+ {%- macro markdown_parameter_schema_has_details(spec) -%}
552
+ {%- if spec.description is defined or spec.enum is defined or spec.default is defined or spec.additionalProperties is defined or spec.patternProperties is defined or 'items' in spec or spec.oneOf or spec.anyOf or spec.returns is defined or markdown_schema_has_extra(spec) == 'true' -%}
553
+ true
554
+ {%- else -%}
555
+ false
556
+ {%- endif -%}
557
+ {%- endmacro -%}
558
+
559
+ {%- macro render_markdown_schema_structure(spec, indent, include_properties) -%}
560
+ {%- if include_properties and spec.properties -%}
561
+ {%- for child_name, child_spec in spec.properties | items -%}
562
+ {{- render_markdown_param(child_name, child_spec, spec.required or [], indent + " ") }}
563
+ {%- endfor -%}
564
+ {%- endif -%}
565
+ {%- if 'items' in spec and spec['items'] is mapping -%}
566
+ {{- "\n" + indent + " - Items *(" + render_markdown_type(spec['items']) + ")*" }}
567
+ {{- render_markdown_schema_details(spec['items'], indent + " ", true) }}
568
+ {%- elif 'items' in spec -%}
569
+ {{ render_markdown_detail(indent, "Items", spec['items']) }}
570
+ {%- endif -%}
571
+ {%- if spec.oneOf -%}
572
+ {{- "\n" + indent + " - oneOf:" }}
573
+ {%- for variant in spec.oneOf -%}
574
+ {{- "\n" + indent + " - Variant " }}{{ loop.index }}{{- " *(" + render_markdown_type(variant) + ")*" }}
575
+ {{- render_markdown_schema_details(variant, indent + " ", true) }}
576
+ {%- endfor -%}
577
+ {%- endif -%}
578
+ {%- if spec.anyOf -%}
579
+ {{- "\n" + indent + " - anyOf:" }}
580
+ {%- for variant in spec.anyOf -%}
581
+ {{- "\n" + indent + " - Variant " }}{{ loop.index }}{{- " *(" + render_markdown_type(variant) + ")*" }}
582
+ {{- render_markdown_schema_details(variant, indent + " ", true) }}
583
+ {%- endfor -%}
584
+ {%- endif -%}
585
+ {%- if spec.patternProperties is mapping -%}
586
+ {{- "\n" + indent + " - Pattern properties:" }}
587
+ {%- for pattern, pattern_spec in spec.patternProperties | items -%}
588
+ {%- if pattern_spec is mapping -%}
589
+ {{- "\n" + indent + " - `" + pattern + "` *(" + render_markdown_type(pattern_spec) + ")*" }}
590
+ {{- render_markdown_schema_details(pattern_spec, indent + " ", true) }}
591
+ {%- else -%}
592
+ {{- "\n" + indent + " - `" + pattern + "`: " }}{{ render_markdown_value(pattern_spec) }}
593
+ {%- endif -%}
594
+ {%- endfor -%}
595
+ {%- elif spec.patternProperties is defined -%}
596
+ {{ render_markdown_detail(indent, "Pattern properties", spec.patternProperties) }}
597
+ {%- endif -%}
598
+ {%- if spec.returns is mapping -%}
599
+ {{- "\n" + indent + " - Returns *(" + render_markdown_type(spec.returns) + ")*" }}
600
+ {{- render_markdown_schema_details(spec.returns, indent + " ", true) }}
601
+ {%- elif spec.returns is defined -%}
602
+ {{ render_markdown_detail(indent, "Returns", spec.returns) }}
603
+ {%- endif -%}
604
+ {%- endmacro -%}
605
+
606
+ {%- macro render_markdown_schema_details(spec, indent, include_value_details) -%}
607
+ {%- if spec is mapping and spec['$ref'] is string -%}
608
+ {%- set _r = spec['$ref'] -%}
609
+ {%- set _k = _r[8:] if _r.startswith('#/$defs/') else (_r[14:] if _r.startswith('#/definitions/') else none) -%}
610
+ {%- if _k is not none and ('|' + _k + '|') not in REFS.seen and REFS.defs[_k] is mapping -%}
611
+ {%- set spec = dict((REFS.defs[_k] | items | list) + (spec | items | rejectattr('0', 'equalto', '$ref') | list)) -%}
612
+ {%- set REFS.seen = REFS.seen + _k + '|' -%}
613
+ {%- if spec['$ref'] is string -%}
614
+ {%- set _r2 = spec['$ref'] -%}
615
+ {%- set _k2 = _r2[8:] if _r2.startswith('#/$defs/') else (_r2[14:] if _r2.startswith('#/definitions/') else none) -%}
616
+ {%- if _k2 is not none and REFS.defs[_k2] is mapping -%}
617
+ {%- set spec = dict((REFS.defs[_k2] | items | list) + (spec | items | rejectattr('0', 'equalto', '$ref') | list)) -%}
618
+ {%- set REFS.seen = REFS.seen + _k2 + '|' -%}
619
+ {%- endif -%}
620
+ {%- endif -%}
621
+ {%- endif -%}
622
+ {%- endif -%}
623
+ {%- if spec is mapping -%}
624
+ {{- render_markdown_schema_annotations(spec, indent, include_value_details) }}
625
+ {{- render_markdown_schema_structure(spec, indent, true) }}
626
+ {{- render_markdown_schema_extras(spec, indent) }}
627
+ {%- elif spec is not sameas true and spec is not sameas false -%}
628
+ {{- "\n" + indent + " - Value: " }}{{ render_markdown_literal(spec) }}
629
+ {%- endif -%}
630
+ {%- endmacro -%}
631
+
632
+ {%- macro render_markdown_parameter_schema(spec) -%}
633
+ {%- if spec is mapping and spec['$ref'] is string -%}
634
+ {%- set _r = spec['$ref'] -%}
635
+ {%- set _k = _r[8:] if _r.startswith('#/$defs/') else (_r[14:] if _r.startswith('#/definitions/') else none) -%}
636
+ {%- if _k is not none and ('|' + _k + '|') not in REFS.seen and REFS.defs[_k] is mapping -%}
637
+ {%- set spec = dict((REFS.defs[_k] | items | list) + (spec | items | rejectattr('0', 'equalto', '$ref') | list)) -%}
638
+ {%- set REFS.seen = REFS.seen + _k + '|' -%}
639
+ {%- if spec['$ref'] is string -%}
640
+ {%- set _r2 = spec['$ref'] -%}
641
+ {%- set _k2 = _r2[8:] if _r2.startswith('#/$defs/') else (_r2[14:] if _r2.startswith('#/definitions/') else none) -%}
642
+ {%- if _k2 is not none and REFS.defs[_k2] is mapping -%}
643
+ {%- set spec = dict((REFS.defs[_k2] | items | list) + (spec | items | rejectattr('0', 'equalto', '$ref') | list)) -%}
644
+ {%- set REFS.seen = REFS.seen + _k2 + '|' -%}
645
+ {%- endif -%}
646
+ {%- endif -%}
647
+ {%- endif -%}
648
+ {%- endif -%}
649
+ {%- if spec is mapping -%}
650
+ {{- render_markdown_metadata_annotations(spec) }}
651
+ {%- if 'items' in spec and spec['items'] is mapping -%}
652
+ {{- "\n- Items *(" + render_markdown_type(spec['items']) + ")*" }}
653
+ {{- render_markdown_schema_details(spec['items'], "", true) }}
654
+ {%- elif 'items' in spec -%}
655
+ {{ render_markdown_metadata_detail("Items", spec['items']) }}
656
+ {%- endif -%}
657
+ {%- if spec.oneOf -%}
658
+ {{- "\n- oneOf:" }}
659
+ {%- for variant in spec.oneOf -%}
660
+ {{- "\n - Variant " }}{{ loop.index }}{{- " *(" + render_markdown_type(variant) + ")*" }}
661
+ {{- render_markdown_schema_details(variant, " ", true) }}
662
+ {%- endfor -%}
663
+ {%- endif -%}
664
+ {%- if spec.anyOf -%}
665
+ {{- "\n- anyOf:" }}
666
+ {%- for variant in spec.anyOf -%}
667
+ {{- "\n - Variant " }}{{ loop.index }}{{- " *(" + render_markdown_type(variant) + ")*" }}
668
+ {{- render_markdown_schema_details(variant, " ", true) }}
669
+ {%- endfor -%}
670
+ {%- endif -%}
671
+ {%- if spec.patternProperties is mapping -%}
672
+ {{- "\n- Pattern properties:" }}
673
+ {%- for pattern, pattern_spec in spec.patternProperties | items -%}
674
+ {%- if pattern_spec is mapping -%}
675
+ {{- "\n - `" + pattern + "` *(" + render_markdown_type(pattern_spec) + ")*" }}
676
+ {{- render_markdown_schema_details(pattern_spec, " ", true) }}
677
+ {%- else -%}
678
+ {{- "\n - `" + pattern + "`: " }}{{ render_markdown_value(pattern_spec) }}
679
+ {%- endif -%}
680
+ {%- endfor -%}
681
+ {%- elif spec.patternProperties is defined -%}
682
+ {{ render_markdown_metadata_detail("Pattern properties", spec.patternProperties) }}
683
+ {%- endif -%}
684
+ {%- if spec.returns is mapping -%}
685
+ {{- "\n- Returns *(" + render_markdown_type(spec.returns) + ")*" }}
686
+ {{- render_markdown_schema_details(spec.returns, "", true) }}
687
+ {%- elif spec.returns is defined -%}
688
+ {{ render_markdown_metadata_detail("Returns", spec.returns) }}
689
+ {%- endif -%}
690
+ {{- render_markdown_metadata_extras(spec) }}
691
+ {%- endif -%}
692
+ {%- endmacro -%}
693
+
694
+ {%- macro render_markdown_param(name, spec, required_list, indent) -%}
695
+ {%- if spec is mapping and spec['$ref'] is string -%}
696
+ {%- set _r = spec['$ref'] -%}
697
+ {%- set _k = _r[8:] if _r.startswith('#/$defs/') else (_r[14:] if _r.startswith('#/definitions/') else none) -%}
698
+ {%- if _k is not none and ('|' + _k + '|') not in REFS.seen and REFS.defs[_k] is mapping -%}
699
+ {%- set spec = dict((REFS.defs[_k] | items | list) + (spec | items | rejectattr('0', 'equalto', '$ref') | list)) -%}
700
+ {%- set REFS.seen = REFS.seen + _k + '|' -%}
701
+ {%- if spec['$ref'] is string -%}
702
+ {%- set _r2 = spec['$ref'] -%}
703
+ {%- set _k2 = _r2[8:] if _r2.startswith('#/$defs/') else (_r2[14:] if _r2.startswith('#/definitions/') else none) -%}
704
+ {%- if _k2 is not none and REFS.defs[_k2] is mapping -%}
705
+ {%- set spec = dict((REFS.defs[_k2] | items | list) + (spec | items | rejectattr('0', 'equalto', '$ref') | list)) -%}
706
+ {%- set REFS.seen = REFS.seen + _k2 + '|' -%}
707
+ {%- endif -%}
708
+ {%- endif -%}
709
+ {%- endif -%}
710
+ {%- endif -%}
711
+ {{- "\n" + indent + "- `" + name + "` *(" + render_markdown_type(spec) }}
712
+ {%- if name in (required_list or []) -%}{{- ", required" }}{%- endif -%}
713
+ {{- ")*" }}
714
+ {%- if spec.description -%}{{- " - " + spec.description | replace("\n", "\n" + indent + " ") }}{%- endif -%}
715
+ {%- if spec.enum -%}
716
+ {{- "\n" + indent + " - Allowed values: " }}{{ render_allowed_values(spec.enum) }}
717
+ {%- endif -%}
718
+ {%- if spec.default is defined -%}
719
+ {{- "\n" + indent + " - Default: " }}{{ render_markdown_literal(spec.default) }}
720
+ {%- endif -%}
721
+ {{- render_markdown_schema_details(spec, indent, false) }}
722
+ {%- endmacro -%}
723
+
724
+ {%- macro render_tools_markdown(tools_list) -%}
725
+ {{- "<ifm|tools>" }}
726
+ {%- for tool in tools_list -%}
727
+ {%- set fn = tool.function if tool.function is defined else tool -%}
728
+ {%- set REFS.defs = fn.parameters['$defs'] if (fn.parameters is mapping and fn.parameters['$defs'] is mapping) else (fn.parameters['definitions'] if (fn.parameters is mapping and fn.parameters['definitions'] is mapping) else {}) -%}
729
+ {%- set REFS.seen = '|' -%}
730
+ {%- set fnp = namespace(p=fn.parameters) -%}
731
+ {%- if fnp.p is mapping and fnp.p['$ref'] is string -%}
732
+ {%- set _r = fnp.p['$ref'] -%}
733
+ {%- set _k = _r[8:] if _r.startswith('#/$defs/') else (_r[14:] if _r.startswith('#/definitions/') else none) -%}
734
+ {%- if _k is not none and REFS.defs[_k] is mapping -%}
735
+ {%- set fnp.p = dict((REFS.defs[_k] | items | list) + (fnp.p | items | rejectattr('0', 'equalto', '$ref') | list)) -%}
736
+ {%- set REFS.seen = REFS.seen + _k + '|' -%}
737
+ {%- endif -%}
738
+ {%- endif -%}
739
+ {{- "\n## " + fn.name }}
740
+ {%- if fn.description -%}
741
+ {{- "\n" + fn.description }}
742
+ {%- endif -%}
743
+ {{- "\n\n**Parameters**" }}
744
+ {%- if fnp.p and fnp.p.properties -%}
745
+ {%- for pname, pspec in fnp.p.properties | items -%}
746
+ {{- render_markdown_param(pname, pspec, fnp.p.required or [], "") }}
747
+ {%- endfor -%}
748
+ {%- elif fnp.p is mapping and (fnp.p.oneOf or fnp.p.anyOf or 'items' in fnp.p) -%}
749
+ {{- render_markdown_parameter_schema(fnp.p) }}
750
+ {%- else -%}
751
+ {{- "\n- None" }}
752
+ {%- endif -%}
753
+ {%- set fn_ret = fn.returns if fn.returns is defined else fn.response -%}
754
+ {%- if fn_ret is mapping -%}
755
+ {{- "\n\n**Returns**" }}
756
+ {{- "\n- Return *(" + render_markdown_type(fn_ret) + ")*" }}
757
+ {{- render_markdown_schema_details(fn_ret, "", true) }}
758
+ {%- elif fn_ret is defined -%}
759
+ {{- "\n\n**Returns**\n- " }}{{ render_markdown_value(fn_ret) }}
760
+ {%- endif -%}
761
+ {%- if not loop.last -%}{{- "\n" }}{%- endif -%}
762
+ {%- endfor -%}
763
+ {{- "\n</ifm|tools>" }}
764
+ {%- endmacro -%}
765
+
766
+ {%- macro render_tool_presentation(tools_list, fmt) -%}
767
+ {%- if fmt == 'json' -%}
768
+ {{- render_tools_json(tools_list) }}
769
+ {%- elif RB.bad != '|' -%}
770
+ {#- some tool uses constructs the pretty renderers cannot represent (verdicts -#}
771
+ {#- computed during validate_tools): render the WHOLE toolset exactly as the -#}
772
+ {#- json presentation would, so the block stays uniform and model-familiar. -#}
773
+ {{- render_tools_json(tools_list) }}
774
+ {%- elif fmt == 'xml' -%}
775
+ {{- render_tools_xml(tools_list) }}
776
+ {%- elif fmt == 'markdown' -%}
777
+ {{- render_tools_markdown(tools_list) }}
778
+ {%- else -%}
779
+ {{- raise_exception("Unsupported tool_presentation_format: '" + fmt + "'. Supported formats: json, xml, markdown.") }}
780
+ {%- endif -%}
781
+ {%- endmacro -%}
782
+
783
+ {%- macro render_call_instructions(fmt) -%}
784
+ {%- if fmt == 'json' -%}
785
+ {{- "Wrap all tool calls in a single <ifm|tool_calls></ifm|tool_calls> block. For each call, emit one JSON object with the function name and arguments on the same line inside <ifm|tool_call></ifm|tool_call> tags:\n\n<ifm|tool_calls>\n<ifm|tool_call>{\"name\": <function-name>, \"arguments\": <args-json-object>}</ifm|tool_call>\n</ifm|tool_calls>" }}
786
+ {%- elif fmt == 'xml' -%}
787
+ {{- "Wrap all tool calls in a single <ifm|tool_calls></ifm|tool_calls> block. For each call, write the function name at the start of <ifm|tool_call>, followed by paired <ifm|arg_key> and <ifm|arg_value> tags for each argument:\n\n<ifm|tool_calls>\n<ifm|tool_call>$FUNCTION_NAME\n<ifm|arg_key>$PARAMETER_NAME</ifm|arg_key>\n<ifm|arg_value>$PARAMETER_VALUE</ifm|arg_value>\n...\n</ifm|tool_call>\n</ifm|tool_calls>\n\nString and scalar parameters should be written as plain text. Array and object parameters should be written as JSON literals." }}
788
+ {%- elif fmt == 'xml_typed' -%}
789
+ {{- "Wrap all tool calls in a single <ifm|tool_calls></ifm|tool_calls> block. For each call, write the function name at the start of <ifm|tool_call>, followed by <ifm|arg_key>, <ifm|arg_type>, and <ifm|arg_value> tags for each argument:\n\n<ifm|tool_calls>\n<ifm|tool_call>$FUNCTION_NAME\n<ifm|arg_key>$PARAMETER_NAME</ifm|arg_key>\n<ifm|arg_type>$ARGUMENT_TYPE</ifm|arg_type>\n<ifm|arg_value>$PARAMETER_VALUE</ifm|arg_value>\n...\n</ifm|tool_call>\n</ifm|tool_calls>\n\nUse the parameter type shown in the tool definition. If that type contains anyOf or oneOf, use the actual argument value type instead. String and scalar parameters should be written as plain text. Array and object parameters should be written as JSON literals." }}
790
+ {%- else -%}
791
+ {{- raise_exception("Unsupported tool_call_format: '" + fmt + "'. Supported formats: json, xml, xml_typed.") }}
792
+ {%- endif -%}
793
+ {%- endmacro -%}
794
+
795
+ {%- macro render_system_with_tools(tools_list, system_content, presentation_fmt, call_fmt) -%}
796
+ {{- "<|ifm|im_start|>system\n# Tools\nYou may call one or more tools to assist with the user query.\n\nAvailable tools are:\n\n" }}
797
+ {{- render_tool_presentation(tools_list, presentation_fmt) }}
798
+ {{- "\n\nWhen calling tools, you MUST follow the tool-call format below:\n\n" }}
799
+ {{- render_call_instructions(call_fmt) }}
800
+ {%- if system_content -%}
801
+ {{- "\n\n" + system_content }}
802
+ {%- endif -%}
803
+ {{- "<|ifm|im_end|>" }}
804
+ {%- endmacro -%}
805
+
806
+ {%- macro render_argument_value(value) -%}
807
+ {%- if value is string -%}{{- value -}}{%- else -%}{{- value | tojson -}}{%- endif -%}
808
+ {%- endmacro -%}
809
+
810
+ {%- macro render_value_type(value) -%}
811
+ {%- if value is none -%}null
812
+ {%- elif value is boolean -%}boolean
813
+ {%- elif value is integer -%}integer
814
+ {%- elif value is number -%}number
815
+ {%- elif value is string -%}string
816
+ {%- elif value is mapping -%}object
817
+ {%- elif value is sequence -%}array
818
+ {%- else -%}any
819
+ {%- endif -%}
820
+ {%- endmacro -%}
821
+
822
+ {%- macro schema_has_combinator(spec) -%}
823
+ {%- if spec.oneOf or spec.anyOf -%}
824
+ true
825
+ {%- elif spec.type is defined and spec.type is sequence and spec.type is not string and spec.type | length > 1 -%}
826
+ true
827
+ {%- elif spec.type == "array" and 'items' in spec -%}
828
+ {{- schema_has_combinator(spec['items']) -}}
829
+ {%- elif spec.properties -%}
830
+ {%- set found = namespace(value='false') -%}
831
+ {%- for child_name, child_spec in spec.properties | items -%}
832
+ {%- if schema_has_combinator(child_spec) == 'true' -%}
833
+ {%- set found.value = 'true' -%}
834
+ {%- endif -%}
835
+ {%- endfor -%}
836
+ {{- found.value -}}
837
+ {%- else -%}
838
+ false
839
+ {%- endif -%}
840
+ {%- endmacro -%}
841
+
842
+ {%- macro render_arg_type(tools_list, tool_name, arg_name, value) -%}
843
+ {%- set found = namespace(type='any') -%}
844
+ {%- for tool in tools_list -%}
845
+ {%- set fn = tool.function if tool.function is defined else tool -%}
846
+ {%- if fn.name == tool_name and fn.parameters and fn.parameters.properties and arg_name in fn.parameters.properties -%}
847
+ {%- set spec = fn.parameters.properties[arg_name] -%}
848
+ {%- if spec is mapping and spec['$ref'] is string -%}
849
+ {%- set _r = spec['$ref'] -%}
850
+ {%- set _k = _r[8:] if _r.startswith('#/$defs/') else (_r[14:] if _r.startswith('#/definitions/') else none) -%}
851
+ {%- set _d = fn.parameters['$defs'] if fn.parameters['$defs'] is mapping else fn.parameters['definitions'] -%}
852
+ {%- set spec = dict((_d[_k] | items | list) + (spec | items | rejectattr('0', 'equalto', '$ref') | list)) if (_k is not none and _d is mapping and _d[_k] is mapping) else spec -%}
853
+ {%- endif -%}
854
+ {%- if schema_has_combinator(spec) == 'true' -%}
855
+ {%- set found.type = render_value_type(value) -%}
856
+ {%- else -%}
857
+ {%- set found.type = render_compact_type(spec) -%}
858
+ {%- endif -%}
859
+ {%- endif -%}
860
+ {%- endfor -%}
861
+ {{- found.type -}}
862
+ {%- endmacro -%}
863
+
864
+ {%- macro render_tool_calls_block(tool_calls, fmt, tools_list) -%}
865
+ {{- "<ifm|tool_calls>" }}
866
+ {%- for raw_tool_call in tool_calls -%}
867
+ {%- set tool_call = raw_tool_call.function if raw_tool_call.function else raw_tool_call -%}
868
+ {%- if tool_call.arguments is string -%}
869
+ {{- raise_exception("tool_call.arguments must be a dict, not a JSON string. Parse it before passing to the template.") -}}
870
+ {%- endif -%}
871
+ {%- if fmt == 'json' -%}
872
+ {{- "\n<ifm|tool_call>{\"name\": \"" + tool_call.name + "\", \"arguments\": " }}{{ tool_call.arguments | tojson }}{{- "}</ifm|tool_call>" }}
873
+ {%- elif fmt == 'xml' or fmt == 'xml_typed' -%}
874
+ {{- "\n<ifm|tool_call>" + tool_call.name + "\n" }}
875
+ {%- for key, value in tool_call.arguments | items -%}
876
+ {{- "<ifm|arg_key>" + key + "</ifm|arg_key>\n" }}
877
+ {%- if fmt == 'xml_typed' -%}
878
+ {{- "<ifm|arg_type>" + render_arg_type(tools_list, tool_call.name, key, value) + "</ifm|arg_type>\n" }}
879
+ {%- endif -%}
880
+ {{- "<ifm|arg_value>" }}{{ render_argument_value(value) }}{{- "</ifm|arg_value>\n" }}
881
+ {%- endfor -%}
882
+ {{- "</ifm|tool_call>" }}
883
+ {%- else -%}
884
+ {{- raise_exception("Unsupported tool_call_format: '" + fmt + "'. Supported formats: json, xml, xml_typed.") -}}
885
+ {%- endif -%}
886
+ {%- endfor -%}
887
+ {{- "\n</ifm|tool_calls>" }}
888
+ {%- endmacro -%}
889
+
890
+ {%- macro render_tool_response_messages(raw_content) -%}
891
+ {%- if raw_content is string -%}
892
+ {{- '<|ifm|im_start|>tool\n' + raw_content + '<|ifm|im_end|>' }}
893
+ {%- elif raw_content is sequence and raw_content is not string and raw_content is not mapping -%}
894
+ {%- if raw_content | length == 0 -%}
895
+ {{- raise_exception("tool message content list must not be empty.") -}}
896
+ {%- endif -%}
897
+ {{- '<|ifm|im_start|>tool\n' -}}
898
+ {%- for item in raw_content -%}
899
+ {%- if not loop.first -%}{{- '\n' -}}{%- endif -%}
900
+ {%- if item is string -%}
901
+ {{- item -}}
902
+ {%- elif item is mapping and item.text is string -%}
903
+ {{- item.text -}}
904
+ {%- else -%}
905
+ {{- (item | tojson) -}}
906
+ {%- endif -%}
907
+ {%- endfor -%}
908
+ {{- '<|ifm|im_end|>' -}}
909
+ {%- else -%}
910
+ {{- '<|ifm|im_start|>tool\n' }}{{ raw_content | tojson }}{{- '<|ifm|im_end|>' }}
911
+ {%- endif -%}
912
+ {%- endmacro -%}
913
+
914
+ {%- set available_tools = tools if tools else [] -%}
915
+ {%- if (not available_tools) and messages[0].role == 'system' and messages[0].get('tools') -%}
916
+ {%- set available_tools = messages[0]['tools'] -%}
917
+ {%- endif -%}
918
+ {%- if available_tools -%}
919
+ {{- validate_tools(available_tools, tool_presentation_fmt != 'json') }}
920
+ {%- set system_content = '' -%}
921
+ {%- if messages[0].role == 'system' and messages[0].content -%}
922
+ {%- set system_content = messages[0].content -%}
923
+ {%- endif -%}
924
+ {{- render_system_with_tools(available_tools, system_content, tool_presentation_fmt, tool_call_fmt) }}
925
+ {%- else -%}
926
+ {%- if messages[0].role == 'system' -%}
927
+ {{- '<|ifm|im_start|>system\n' + messages[0].content + '<|ifm|im_end|>' }}
928
+ {%- endif -%}
929
+ {%- endif -%}
930
+
931
+ {%- for message in messages -%}
932
+ {%- if message.content is string -%}
933
+ {%- set content = message.content -%}
934
+ {%- else -%}
935
+ {%- set content = '' -%}
936
+ {%- endif -%}
937
+ {%- if (message.role == "user") or (message.role == "system" and not loop.first) -%}
938
+ {{- '<|ifm|im_start|>' + message.role + '\n' + content + '<|ifm|im_end|>' }}
939
+ {%- elif message.role == "assistant" -%}
940
+ {%- set thinking_content = '' -%}
941
+ {%- set think_tag = '' -%}
942
+ {%- if message.think is defined and message.think is string -%}
943
+ {%- set thinking_content = message.think -%}
944
+ {%- set think_tag = 'ifm|think' -%}
945
+ {%- elif message.think_fast is defined and message.think_fast is string -%}
946
+ {%- set thinking_content = message.think_fast -%}
947
+ {%- set think_tag = 'ifm|think_fast' -%}
948
+ {%- elif message.think_faster is defined and message.think_faster is string -%}
949
+ {%- set thinking_content = message.think_faster -%}
950
+ {%- set think_tag = 'ifm|think_faster' -%}
951
+ {%- else -%}
952
+ {%- if '</ifm|think>' in content -%}
953
+ {%- set thinking_content = content.split('</ifm|think>')[0].rstrip('\n').split('<ifm|think>')[-1].lstrip('\n') -%}
954
+ {%- set content = content.split('</ifm|think>')[-1].lstrip('\n') -%}
955
+ {%- set think_tag = 'ifm|think' -%}
956
+ {%- elif '</ifm|think_fast>' in content -%}
957
+ {%- set thinking_content = content.split('</ifm|think_fast>')[0].rstrip('\n').split('<ifm|think_fast>')[-1].lstrip('\n') -%}
958
+ {%- set content = content.split('</ifm|think_fast>')[-1].lstrip('\n') -%}
959
+ {%- set think_tag = 'ifm|think_fast' -%}
960
+ {%- elif '</ifm|think_faster>' in content -%}
961
+ {%- set thinking_content = content.split('</ifm|think_faster>')[0].rstrip('\n').split('<ifm|think_faster>')[-1].lstrip('\n') -%}
962
+ {%- set content = content.split('</ifm|think_faster>')[-1].lstrip('\n') -%}
963
+ {%- set think_tag = 'ifm|think_faster' -%}
964
+ {%- endif -%}
965
+ {%- endif -%}
966
+ {{- '<|ifm|im_start|>' + message.role }}
967
+ {% generation %}
968
+ {%- if think_tag -%}
969
+ {%- if thinking_content -%}
970
+ {{- '<' + think_tag + '>\n' + thinking_content + '\n</' + think_tag + '>\n' + content.lstrip('\n') }}
971
+ {%- else -%}
972
+ {{- '<' + think_tag + '>\n</' + think_tag + '>\n' + content.lstrip('\n') }}
973
+ {%- endif -%}
974
+ {%- else -%}
975
+ {{- content }}
976
+ {%- endif -%}
977
+ {%- if message.tool_calls -%}
978
+ {%- if content -%}
979
+ {{- '\n' }}
980
+ {%- endif -%}
981
+ {{- render_tool_calls_block(message.tool_calls, tool_call_fmt, available_tools) }}
982
+ {%- endif -%}
983
+ {{- '<|ifm|im_end|>' -}}
984
+ {%- endgeneration -%}
985
+ {%- elif message.role == "tool" -%}
986
+ {{- render_tool_response_messages(message.content) }}
987
+ {%- endif -%}
988
+ {%- endfor -%}
989
+ {%- if add_generation_prompt -%}
990
+ {%- set effort = reasoning_effort | default('high') -%}
991
+ {%- if effort == 'high' -%}
992
+ {{- '<|ifm|im_start|>assistant\n<ifm|think>\n' }}
993
+ {%- elif effort == 'medium' -%}
994
+ {{- '<|ifm|im_start|>assistant\n<ifm|think_fast>\n' }}
995
+ {%- elif effort == 'low' -%}
996
+ {{- '<|ifm|im_start|>assistant\n<ifm|think_faster>\n' }}
997
+ {%- else -%}
998
+ {{- '<|ifm|im_start|>assistant\n<ifm|think_fast>\n' }}
999
+ {%- endif -%}
1000
+ {%- endif -%}
chat_template_asst_tool_gen.jinja ADDED
@@ -0,0 +1,1000 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {%- if tool_presentation is defined -%}
2
+ {{- raise_exception("Unsupported argument: tool_presentation. Use tool_presentation_format with one of: json, xml, markdown.") -}}
3
+ {%- endif -%}
4
+ {%- if tool_calling_format is defined -%}
5
+ {{- raise_exception("Unsupported argument: tool_calling_format. Use tool_call_format with one of: json, xml, xml_typed.") -}}
6
+ {%- endif -%}
7
+ {%- if tool_format is defined -%}
8
+ {{- raise_exception("Unsupported argument: tool_format. Use tool_call_format with one of: json, xml, xml_typed.") -}}
9
+ {%- endif -%}
10
+ {%- set tool_presentation_fmt = tool_presentation_format | default('markdown') -%}
11
+ {%- set tool_call_fmt = tool_call_format | default('xml') -%}
12
+ {%- if tool_presentation_fmt != 'json' and tool_presentation_fmt != 'xml' and tool_presentation_fmt != 'markdown' -%}
13
+ {{- raise_exception("Unsupported tool_presentation_format: '" ~ tool_presentation_fmt ~ "'. Supported formats: json, xml, markdown.") -}}
14
+ {%- endif -%}
15
+ {%- if tool_call_fmt != 'json' and tool_call_fmt != 'xml' and tool_call_fmt != 'xml_typed' -%}
16
+ {{- raise_exception("Unsupported tool_call_format: '" ~ tool_call_fmt ~ "'. Supported formats: json, xml, xml_typed.") -}}
17
+ {%- endif -%}
18
+
19
+ {#- Renderability state, computed during validate_tools (single walk, no extra -#}
20
+ {#- traversal at render time): ok = working flag for the tool being validated; -#}
21
+ {#- bad = pipe-delimited indices of tools that must render as verbatim JSON. -#}
22
+ {%- set RB = namespace(ok=true, bad='|') -%}
23
+
24
+ {%- macro value_contains_mapping(v) -%}
25
+ {%- if v is mapping -%}
26
+ true
27
+ {%- elif v is sequence and v is not string -%}
28
+ {%- set f = namespace(x='false') -%}
29
+ {%- for c in v -%}{%- if value_contains_mapping(c) == 'true' -%}{%- set f.x = 'true' -%}{%- endif -%}{%- endfor -%}
30
+ {{- f.x -}}
31
+ {%- else -%}
32
+ false
33
+ {%- endif -%}
34
+ {%- endmacro -%}
35
+
36
+ {#- $ref inlining state: defs = local $defs of the tool being rendered; seen = -#}
37
+ {#- pipe-delimited names already expanded for this tool (each def inlines at most -#}
38
+ {#- once; later references render by def name; cycles terminate immediately). -#}
39
+ {#- $ref-sibling annotations (description/default/...) merge OVER the def at -#}
40
+ {#- the inline site, so use-site annotations win and are never dropped. -#}
41
+ {%- set REFS = namespace(defs={}, seen='|') -%}
42
+
43
+ {%- macro render_compact_type_name(type_name, spec) -%}
44
+ {%- if type_name == "array" -%}
45
+ array[{%- if 'items' in spec -%}{{ render_compact_type(spec['items']) }}{%- else -%}any{%- endif -%}]
46
+ {%- elif type_name -%}
47
+ {{- type_name -}}
48
+ {%- else -%}
49
+ any
50
+ {%- endif -%}
51
+ {%- endmacro -%}
52
+
53
+ {%- macro render_compact_type(spec) -%}
54
+ {%- if spec is not mapping -%}
55
+ any
56
+ {%- elif spec.type is defined and spec.type is sequence and spec.type is not string and spec.type | length > 0 -%}
57
+ {%- for type_name in spec.type -%}{{ render_compact_type_name(type_name, spec) }}{%- if not loop.last -%}|{%- endif -%}{%- endfor -%}
58
+ {%- elif spec.type is defined and spec.type is sequence and spec.type is not string -%}
59
+ any
60
+ {%- elif spec.type -%}
61
+ {{- render_compact_type_name(spec.type, spec) -}}
62
+ {%- elif spec['$ref'] is string -%}
63
+ {{- spec['$ref'].split('/') | last -}}
64
+ {%- elif spec.oneOf -%}
65
+ oneOf[{%- for variant in spec.oneOf -%}{{ render_compact_type(variant) }}{%- if not loop.last -%}|{%- endif -%}{%- endfor -%}]
66
+ {%- elif spec.anyOf -%}
67
+ anyOf[{%- for variant in spec.anyOf -%}{{ render_compact_type(variant) }}{%- if not loop.last -%}|{%- endif -%}{%- endfor -%}]
68
+ {%- elif spec.properties -%}
69
+ object
70
+ {%- elif 'items' in spec -%}
71
+ array[{{ render_compact_type(spec['items']) }}]
72
+ {%- else -%}
73
+ any
74
+ {%- endif -%}
75
+ {%- endmacro -%}
76
+
77
+ {%- macro render_markdown_type_name(type_name, spec) -%}
78
+ {%- if type_name == "array" -%}
79
+ array of {% if 'items' in spec %}{{ render_markdown_type(spec['items']) }}{% else %}any{% endif %}
80
+ {%- elif type_name -%}
81
+ {{- type_name -}}
82
+ {%- else -%}
83
+ any
84
+ {%- endif -%}
85
+ {%- endmacro -%}
86
+
87
+ {%- macro render_markdown_type(spec) -%}
88
+ {%- if spec is sameas true -%}
89
+ True
90
+ {%- elif spec is sameas false -%}
91
+ False
92
+ {%- elif spec is not mapping -%}
93
+ any
94
+ {%- elif spec.type is defined and spec.type is sequence and spec.type is not string and spec.type | length > 0 -%}
95
+ {%- for type_name in spec.type -%}{{ render_markdown_type_name(type_name, spec) }}{% if not loop.last %} or {% endif %}{%- endfor -%}
96
+ {%- elif spec.type is defined and spec.type is sequence and spec.type is not string -%}
97
+ any
98
+ {%- elif spec.type -%}
99
+ {{- render_markdown_type_name(spec.type, spec) -}}
100
+ {%- elif spec['$ref'] is string -%}
101
+ {{- spec['$ref'].split('/') | last -}}
102
+ {%- elif spec.oneOf -%}
103
+ oneOf[{%- for variant in spec.oneOf -%}{{ render_markdown_type(variant) }}{% if not loop.last %} or {% endif %}{%- endfor -%}]
104
+ {%- elif spec.anyOf -%}
105
+ anyOf[{%- for variant in spec.anyOf -%}{{ render_markdown_type(variant) }}{% if not loop.last %} or {% endif %}{%- endfor -%}]
106
+ {%- elif spec.properties -%}
107
+ object
108
+ {%- elif 'items' in spec -%}
109
+ array of {{ render_markdown_type(spec['items']) }}
110
+ {%- else -%}
111
+ any
112
+ {%- endif -%}
113
+ {%- endmacro -%}
114
+
115
+ {%- macro render_xml_text(value) -%}
116
+ {{- value.split() | join(" ") -}}
117
+ {%- endmacro -%}
118
+
119
+ {%- macro render_python_string(value) -%}
120
+ '{{- value.split() | join(" ") | replace("\\", "\\\\") | replace("'", "\\'") -}}'
121
+ {%- endmacro -%}
122
+
123
+ {%- macro render_python_repr(value) -%}
124
+ {%- if value is string -%}
125
+ {{ render_python_string(value) }}
126
+ {%- elif value is sameas true -%}
127
+ True
128
+ {%- elif value is sameas false -%}
129
+ False
130
+ {%- elif value is none -%}
131
+ None
132
+ {%- elif value is mapping -%}
133
+ {{- "{" -}}
134
+ {%- for key, child in value | items -%}
135
+ {{ render_python_repr(key) }}: {{ render_python_repr(child) }}{%- if not loop.last -%}, {% endif -%}
136
+ {%- endfor -%}
137
+ {{- "}" -}}
138
+ {%- elif value is sequence -%}
139
+ {{- "[" -}}
140
+ {%- for child in value -%}
141
+ {{ render_python_repr(child) }}{%- if not loop.last -%}, {% endif -%}
142
+ {%- endfor -%}
143
+ {{- "]" -}}
144
+ {%- else -%}
145
+ {{- value -}}
146
+ {%- endif -%}
147
+ {%- endmacro -%}
148
+
149
+ {%- macro render_xml_value(value) -%}
150
+ {%- if value is string -%}{{ render_xml_text(value) }}{%- else -%}{{ render_python_repr(value) }}{%- endif -%}
151
+ {%- endmacro -%}
152
+
153
+ {%- macro render_xml_enum_value(value) -%}
154
+ {%- if value is string -%}"{{- value | replace("\\", "\\\\") | replace("\"", "\\\"") -}}"{%- else -%}"{{- render_python_repr(value) | replace("\\", "\\\\") | replace("\"", "\\\"") -}}"{%- endif -%}
155
+ {%- endmacro -%}
156
+
157
+ {%- macro render_xml_enum(values) -%}
158
+ {%- for value in values -%}{{ render_xml_enum_value(value) }}{%- if not loop.last -%}|{%- endif -%}{%- endfor -%}
159
+ {%- endmacro -%}
160
+
161
+ {%- macro render_xml_default_attr(value) -%}
162
+ {{- " default=" }}{%- if value is string -%}"{{- value | replace("\\", "\\\\") | replace("\"", "\\\"") -}}"{%- else -%}{{ render_xml_value(value) }}{%- endif -%}
163
+ {%- endmacro -%}
164
+
165
+ {%- macro render_xml_attr(name, value) -%}
166
+ {{- " " + name + "=" }}{%- if value == "" -%}""{%- else -%}{{ render_xml_value(value) }}{%- endif -%}
167
+ {%- endmacro -%}
168
+
169
+ {%- macro validate_schema(spec, path, lenient=false, classify=true, in_variant=false) -%}
170
+ {%- if spec is mapping -%}
171
+ {%- if not lenient -%}
172
+ {%- if spec.required is defined -%}
173
+ {%- if spec.required is string or spec.required is not sequence -%}
174
+ {{- raise_exception("Schema '" + path + "' has 'required' but it is not a list.") -}}
175
+ {%- endif -%}
176
+ {%- if spec.required | length > 0 and not spec.properties and not in_variant -%}
177
+ {{- raise_exception("Schema '" + path + "' has required fields but no properties object to define them.") -}}
178
+ {%- endif -%}
179
+ {%- if spec.properties -%}
180
+ {%- for required_name in spec.required -%}
181
+ {%- if required_name not in spec.properties -%}
182
+ {{- raise_exception("Schema '" + path + "' marks '" + required_name + "' as required, but that property is not defined in properties.") -}}
183
+ {%- endif -%}
184
+ {%- endfor -%}
185
+ {%- endif -%}
186
+ {%- endif -%}
187
+ {%- endif -%}
188
+ {#- renderability classification, piggybacking on this walk (no raises here): -#}
189
+ {#- constructs the pretty renderer does not fully handle flip RB.ok so the -#}
190
+ {#- tool falls back to verbatim JSON. Skipped entirely for json presentation. -#}
191
+ {%- if classify -%}
192
+ {%- for key, value in spec | items -%}
193
+ {%- if key == '$ref' -%}
194
+ {%- if value is not string -%}{%- set RB.ok = false -%}
195
+ {%- elif not (value.startswith('#/$defs/') or value.startswith('#/definitions/')) -%}{%- set RB.ok = false -%}{%- endif -%}
196
+ {%- elif key == '$defs' or key == 'definitions' -%}
197
+ {%- if value is mapping -%}
198
+ {%- for dk, dv in value | items -%}
199
+ {{- validate_schema(dv, path + ".$defs." + dk, true) -}}
200
+ {%- endfor -%}
201
+ {%- else -%}{%- set RB.ok = false -%}{%- endif -%}
202
+ {%- elif key == 'type' -%}
203
+ {%- if value is mapping -%}{%- set RB.ok = false -%}{%- endif -%}
204
+ {%- elif key == 'enum' -%}
205
+ {%- if value is string or value is mapping or value is not sequence -%}{%- set RB.ok = false -%}{%- endif -%}
206
+ {%- elif key == 'items' -%}
207
+ {#- any items shape renders: mapping structurally, others via repr detail -#}
208
+ {%- elif key == 'oneOf' or key == 'anyOf' -%}
209
+ {%- if value is mapping or value is string or value is not sequence -%}{%- set RB.ok = false -%}{%- endif -%}
210
+ {%- elif key == 'required' -%}
211
+ {%- if value and not spec.properties -%}{%- set RB.ok = false -%}{%- endif -%}
212
+ {%- elif ('|' ~ key ~ '|') in '|description|default|title|examples|properties|patternProperties|additionalProperties|returns|' -%}
213
+ {%- elif value is mapping -%}
214
+ {%- for uk, uv in value | items -%}
215
+ {%- if value_contains_mapping(uv) == 'true' -%}{%- set RB.ok = false -%}{%- endif -%}
216
+ {%- endfor -%}
217
+ {%- elif value is sequence and value is not string -%}
218
+ {%- if value_contains_mapping(value) == 'true' -%}{%- set RB.ok = false -%}{%- endif -%}
219
+ {%- endif -%}
220
+ {%- endfor -%}
221
+ {%- endif -%}
222
+ {%- if spec.properties -%}
223
+ {%- for child_name, child_spec in spec.properties | items -%}
224
+ {{- validate_schema(child_spec, path + "." + child_name, lenient, classify) -}}
225
+ {%- endfor -%}
226
+ {%- endif -%}
227
+ {%- if 'items' in spec -%}{{- validate_schema(spec['items'], path + "[]", lenient, classify) -}}{%- endif -%}
228
+ {%- if spec.oneOf -%}
229
+ {%- for variant in spec.oneOf -%}{{- validate_schema(variant, path + ".oneOf[" + (loop.index0 | string) + "]", lenient, classify, true) -}}{%- endfor -%}
230
+ {%- endif -%}
231
+ {%- if spec.anyOf -%}
232
+ {%- for variant in spec.anyOf -%}{{- validate_schema(variant, path + ".anyOf[" + (loop.index0 | string) + "]", lenient, classify, true) -}}{%- endfor -%}
233
+ {%- endif -%}
234
+ {%- if spec.additionalProperties is mapping -%}{{- validate_schema(spec.additionalProperties, path + ".additionalProperties", lenient, classify) -}}{%- endif -%}
235
+ {%- if spec.patternProperties is mapping -%}
236
+ {%- for pattern, pattern_spec in spec.patternProperties | items -%}
237
+ {{- validate_schema(pattern_spec, path + ".patternProperties[" + pattern + "]", lenient, classify) -}}
238
+ {%- endfor -%}
239
+ {%- endif -%}
240
+ {%- if spec.returns is mapping -%}{{- validate_schema(spec.returns, path + ".returns", lenient, classify) -}}{%- endif -%}
241
+ {%- endif -%}
242
+ {%- endmacro -%}
243
+
244
+ {%- macro validate_tools(tools_list, classify=true) -%}
245
+ {%- set RB.bad = '|' -%}
246
+ {%- for tool in tools_list -%}
247
+ {%- set fn = tool.function if tool.function is defined else tool -%}
248
+ {%- set RB.ok = true -%}
249
+ {%- if fn.parameters is defined and fn.parameters is string -%}
250
+ {{- raise_exception("tool.function.parameters must be a dict, not a JSON string. Parse it before passing to the template.") -}}
251
+ {%- endif -%}
252
+ {%- if fn.parameters is not defined or fn.parameters is none -%}
253
+ {%- if fn.arguments is defined -%}
254
+ {{- raise_exception("Tool '" + fn.name + "' has 'arguments' instead of 'parameters'. Rename 'arguments' to 'parameters'.") -}}
255
+ {%- else -%}
256
+ {{- raise_exception("Tool '" + fn.name + "' is missing required 'parameters' field. Each tool must have a 'parameters' dict with 'type', 'properties', and 'required' keys.") -}}
257
+ {%- endif -%}
258
+ {%- endif -%}
259
+ {{- validate_schema(fn.parameters, "tool." + fn.name + ".parameters", false, classify) -}}
260
+ {%- if classify -%}
261
+ {%- if fn.parameters is mapping -%}
262
+ {#- unknown container-valued keys at the parameters ROOT are never rendered -#}
263
+ {#- by the pretty path (root extras are dropped) -> verbatim fallback. -#}
264
+ {%- for rk, rv in fn.parameters | items -%}
265
+ {%- if rk not in ['type', 'description', 'enum', 'default', 'properties', 'required', 'optional', 'title', 'items', 'oneOf', 'anyOf', 'additionalProperties', 'patternProperties', 'returns', 'examples', '$defs', 'definitions', '$ref'] -%}
266
+ {%- if rv is mapping or (rv is sequence and rv is not string) -%}{%- set RB.ok = false -%}{%- endif -%}
267
+ {%- endif -%}
268
+ {%- endfor -%}
269
+ {%- else -%}
270
+ {%- set RB.ok = false -%}
271
+ {%- endif -%}
272
+ {%- endif -%}
273
+ {%- if fn.returns is mapping -%}{{- validate_schema(fn.returns, "tool." + fn.name + ".returns", false, classify) -}}{%- endif -%}
274
+ {%- if classify and fn.returns is not defined and fn.response is mapping -%}{{- validate_schema(fn.response, "tool." + fn.name + ".response", true) -}}{%- endif -%}
275
+ {#- unknown container-valued keys at the FUNCTION level are never rendered -> fallback. -#}
276
+ {%- if classify -%}
277
+ {%- for fk, fv in fn | items -%}
278
+ {%- if fk not in ['name', 'description', 'parameters', 'returns', 'response', 'type', 'function'] -%}
279
+ {%- if fv is mapping or (fv is sequence and fv is not string) -%}{%- set RB.ok = false -%}{%- endif -%}
280
+ {%- endif -%}
281
+ {%- endfor -%}
282
+ {%- endif -%}
283
+ {%- if not RB.ok -%}{%- set RB.bad = RB.bad ~ loop.index0 ~ '|' -%}{%- endif -%}
284
+ {%- endfor -%}
285
+ {%- endmacro -%}
286
+
287
+ {%- macro render_tools_json(tools_list) -%}
288
+ {{- "<ifm|tools>" }}
289
+ {%- for tool in tools_list %}
290
+ {{- "\n" }}
291
+ {{- tool | tojson }}
292
+ {%- endfor %}
293
+ {{- "\n</ifm|tools>" }}
294
+ {%- endmacro -%}
295
+
296
+ {%- macro render_xml_schema_attrs(spec, include_value_attrs) -%}
297
+ {%- if spec is mapping -%}
298
+ {%- set structural_keys = ["type", "description", "enum", "default", "properties", "required", "items", "oneOf", "anyOf", "additionalProperties", "patternProperties", "returns"] -%}
299
+ {%- if include_value_attrs and spec.enum -%}{{- " enum=" }}{{ render_xml_enum(spec.enum) }}{%- endif -%}
300
+ {%- if include_value_attrs and spec.default is defined -%}{{ render_xml_default_attr(spec.default) }}{%- endif -%}
301
+ {%- if spec.additionalProperties is defined and spec.additionalProperties is not mapping -%}{{ render_xml_attr("additionalProperties", spec.additionalProperties) }}{%- endif -%}
302
+ {%- if spec.patternProperties is defined and spec.patternProperties is not mapping -%}{{ render_xml_attr("patternProperties", spec.patternProperties) }}{%- endif -%}
303
+ {%- for key, value in spec | items -%}
304
+ {%- if key not in structural_keys -%}
305
+ {{ render_xml_attr(key, value) }}
306
+ {%- endif -%}
307
+ {%- endfor -%}
308
+ {%- endif -%}
309
+ {%- endmacro -%}
310
+
311
+ {%- macro xml_schema_has_children(spec, include_properties, include_description) -%}
312
+ {%- if spec is not mapping -%}
313
+ false
314
+ {%- elif (include_description and spec.description is defined) or (include_properties and spec.properties) or 'items' in spec or spec.oneOf or spec.anyOf or spec.additionalProperties is mapping or spec.patternProperties is mapping or spec.returns is defined -%}
315
+ true
316
+ {%- else -%}
317
+ false
318
+ {%- endif -%}
319
+ {%- endmacro -%}
320
+
321
+ {%- macro render_xml_schema_node(tag, spec, include_properties) -%}
322
+ {%- if spec is mapping and spec['$ref'] is string -%}
323
+ {%- set _r = spec['$ref'] -%}
324
+ {%- set _k = _r[8:] if _r.startswith('#/$defs/') else (_r[14:] if _r.startswith('#/definitions/') else none) -%}
325
+ {%- if _k is not none and ('|' + _k + '|') not in REFS.seen and REFS.defs[_k] is mapping -%}
326
+ {%- set spec = dict((REFS.defs[_k] | items | list) + (spec | items | rejectattr('0', 'equalto', '$ref') | list)) -%}
327
+ {%- set REFS.seen = REFS.seen + _k + '|' -%}
328
+ {%- if spec['$ref'] is string -%}
329
+ {%- set _r2 = spec['$ref'] -%}
330
+ {%- set _k2 = _r2[8:] if _r2.startswith('#/$defs/') else (_r2[14:] if _r2.startswith('#/definitions/') else none) -%}
331
+ {%- if _k2 is not none and REFS.defs[_k2] is mapping -%}
332
+ {%- set spec = dict((REFS.defs[_k2] | items | list) + (spec | items | rejectattr('0', 'equalto', '$ref') | list)) -%}
333
+ {%- set REFS.seen = REFS.seen + _k2 + '|' -%}
334
+ {%- endif -%}
335
+ {%- endif -%}
336
+ {%- endif -%}
337
+ {%- endif -%}
338
+ {%- if spec is mapping -%}
339
+ {{- "<" + tag + " type=" + render_compact_type(spec) }}{{ render_xml_schema_attrs(spec, true) }}
340
+ {%- if xml_schema_has_children(spec, include_properties, true) == 'true' -%}
341
+ {{- ">" }}{{ render_xml_schema_children(spec, include_properties, true) }}{{- "</" + tag + ">" }}
342
+ {%- else -%}
343
+ {{- "/>" }}
344
+ {%- endif -%}
345
+ {%- else -%}
346
+ {{- "<" + tag + ">" }}{{ render_xml_value(spec) }}{{- "</" + tag + ">" }}
347
+ {%- endif -%}
348
+ {%- endmacro -%}
349
+
350
+ {%- macro render_xml_pattern_property(pattern, spec) -%}
351
+ {%- if spec is mapping and spec['$ref'] is string -%}
352
+ {%- set _r = spec['$ref'] -%}
353
+ {%- set _k = _r[8:] if _r.startswith('#/$defs/') else (_r[14:] if _r.startswith('#/definitions/') else none) -%}
354
+ {%- if _k is not none and ('|' + _k + '|') not in REFS.seen and REFS.defs[_k] is mapping -%}
355
+ {%- set spec = dict((REFS.defs[_k] | items | list) + (spec | items | rejectattr('0', 'equalto', '$ref') | list)) -%}
356
+ {%- set REFS.seen = REFS.seen + _k + '|' -%}
357
+ {%- if spec['$ref'] is string -%}
358
+ {%- set _r2 = spec['$ref'] -%}
359
+ {%- set _k2 = _r2[8:] if _r2.startswith('#/$defs/') else (_r2[14:] if _r2.startswith('#/definitions/') else none) -%}
360
+ {%- if _k2 is not none and REFS.defs[_k2] is mapping -%}
361
+ {%- set spec = dict((REFS.defs[_k2] | items | list) + (spec | items | rejectattr('0', 'equalto', '$ref') | list)) -%}
362
+ {%- set REFS.seen = REFS.seen + _k2 + '|' -%}
363
+ {%- endif -%}
364
+ {%- endif -%}
365
+ {%- endif -%}
366
+ {%- endif -%}
367
+ {%- if spec is mapping -%}
368
+ {{- "<patternProperty" }}{{ render_xml_attr("pattern", pattern) }}{{- " type=" + render_compact_type(spec) }}{{ render_xml_schema_attrs(spec, true) }}
369
+ {%- if xml_schema_has_children(spec, true, true) == 'true' -%}
370
+ {{- ">" }}{{ render_xml_schema_children(spec, true, true) }}{{- "</patternProperty>" }}
371
+ {%- else -%}
372
+ {{- "/>" }}
373
+ {%- endif -%}
374
+ {%- else -%}
375
+ {{- "<patternProperty" }}{{ render_xml_attr("pattern", pattern) }}{{- ">" }}{{ render_xml_value(spec) }}{{- "</patternProperty>" }}
376
+ {%- endif -%}
377
+ {%- endmacro -%}
378
+
379
+ {%- macro render_xml_schema_children(spec, include_properties, include_description) -%}
380
+ {%- if include_description and spec.description is defined -%}{{- "<description>" }}{{ spec.description }}{{- "</description>" }}{%- endif -%}
381
+ {%- if include_properties and spec.properties -%}
382
+ {%- for child_name, child_spec in spec.properties | items -%}
383
+ {{- render_xml_param(child_name, child_spec, spec.required or []) }}
384
+ {%- endfor -%}
385
+ {%- endif -%}
386
+ {%- if 'items' in spec -%}{{ render_xml_schema_node("items", spec['items'], true) }}{%- endif -%}
387
+ {%- if spec.oneOf -%}
388
+ {{- "<oneOf>" }}
389
+ {%- for variant in spec.oneOf -%}{{ render_xml_schema_node("variant", variant, true) }}{%- endfor -%}
390
+ {{- "</oneOf>" }}
391
+ {%- endif -%}
392
+ {%- if spec.anyOf -%}
393
+ {{- "<anyOf>" }}
394
+ {%- for variant in spec.anyOf -%}{{ render_xml_schema_node("variant", variant, true) }}{%- endfor -%}
395
+ {{- "</anyOf>" }}
396
+ {%- endif -%}
397
+ {%- if spec.additionalProperties is mapping -%}{{ render_xml_schema_node("additionalProperties", spec.additionalProperties, true) }}{%- endif -%}
398
+ {%- if spec.patternProperties is mapping -%}
399
+ {{- "<patternProperties>" }}
400
+ {%- for pattern, pattern_spec in spec.patternProperties | items -%}{{ render_xml_pattern_property(pattern, pattern_spec) }}{%- endfor -%}
401
+ {{- "</patternProperties>" }}
402
+ {%- elif spec.patternProperties is defined -%}<patternProperties>{{ render_xml_value(spec.patternProperties) }}</patternProperties>{%- endif -%}
403
+ {%- if spec.returns is mapping -%}{{ render_xml_schema_node("returns", spec.returns, true) }}{%- elif spec.returns is defined -%}<returns>{{ render_xml_value(spec.returns) }}</returns>{%- endif -%}
404
+ {%- endmacro -%}
405
+
406
+ {%- macro render_xml_param(name, spec, required_list) -%}
407
+ {%- if spec is mapping and spec['$ref'] is string -%}
408
+ {%- set _r = spec['$ref'] -%}
409
+ {%- set _k = _r[8:] if _r.startswith('#/$defs/') else (_r[14:] if _r.startswith('#/definitions/') else none) -%}
410
+ {%- if _k is not none and ('|' + _k + '|') not in REFS.seen and REFS.defs[_k] is mapping -%}
411
+ {%- set spec = dict((REFS.defs[_k] | items | list) + (spec | items | rejectattr('0', 'equalto', '$ref') | list)) -%}
412
+ {%- set REFS.seen = REFS.seen + _k + '|' -%}
413
+ {%- if spec['$ref'] is string -%}
414
+ {%- set _r2 = spec['$ref'] -%}
415
+ {%- set _k2 = _r2[8:] if _r2.startswith('#/$defs/') else (_r2[14:] if _r2.startswith('#/definitions/') else none) -%}
416
+ {%- if _k2 is not none and REFS.defs[_k2] is mapping -%}
417
+ {%- set spec = dict((REFS.defs[_k2] | items | list) + (spec | items | rejectattr('0', 'equalto', '$ref') | list)) -%}
418
+ {%- set REFS.seen = REFS.seen + _k2 + '|' -%}
419
+ {%- endif -%}
420
+ {%- endif -%}
421
+ {%- endif -%}
422
+ {%- endif -%}
423
+ {{- "<param name=" + name + " type=" + render_compact_type(spec) }}
424
+ {%- if name in (required_list or []) -%}{{- " required=true" }}{%- endif -%}
425
+ {%- if spec.enum -%}{{- " enum=" }}{{ render_xml_enum(spec.enum) }}{%- endif -%}
426
+ {%- if spec.default is defined -%}{{ render_xml_default_attr(spec.default) }}{%- endif -%}
427
+ {{- render_xml_schema_attrs(spec, false) }}
428
+ {%- if spec.description or xml_schema_has_children(spec, true, false) == 'true' -%}
429
+ {{- ">" }}
430
+ {%- if spec.description -%}{{ spec.description }}{%- endif -%}
431
+ {{- render_xml_schema_children(spec, true, false) }}
432
+ {{- "</param>" }}
433
+ {%- else -%}
434
+ {{- "/>" }}
435
+ {%- endif -%}
436
+ {%- endmacro -%}
437
+
438
+ {%- macro render_tools_xml(tools_list) -%}
439
+ {{- "<ifm|tools>" }}
440
+ {%- for tool in tools_list -%}
441
+ {%- set fn = tool.function if tool.function is defined else tool -%}
442
+ {%- set REFS.defs = fn.parameters['$defs'] if (fn.parameters is mapping and fn.parameters['$defs'] is mapping) else (fn.parameters['definitions'] if (fn.parameters is mapping and fn.parameters['definitions'] is mapping) else {}) -%}
443
+ {%- set REFS.seen = '|' -%}
444
+ {%- set fnp = namespace(p=fn.parameters) -%}
445
+ {%- if fnp.p is mapping and fnp.p['$ref'] is string -%}
446
+ {%- set _r = fnp.p['$ref'] -%}
447
+ {%- set _k = _r[8:] if _r.startswith('#/$defs/') else (_r[14:] if _r.startswith('#/definitions/') else none) -%}
448
+ {%- if _k is not none and REFS.defs[_k] is mapping -%}
449
+ {%- set fnp.p = dict((REFS.defs[_k] | items | list) + (fnp.p | items | rejectattr('0', 'equalto', '$ref') | list)) -%}
450
+ {%- set REFS.seen = REFS.seen + _k + '|' -%}
451
+ {%- endif -%}
452
+ {%- endif -%}
453
+ {{- "\n<function name=" + fn.name + ">" }}
454
+ {%- if fn.description -%}
455
+ {{- "<description>" }}{{ fn.description }}{{- "</description>" }}
456
+ {%- endif -%}
457
+ {{- "<parameters>" }}
458
+ {%- if fnp.p and fnp.p.properties -%}
459
+ {%- for pname, pspec in fnp.p.properties | items -%}
460
+ {{- render_xml_param(pname, pspec, fnp.p.required or []) }}
461
+ {%- endfor -%}
462
+ {%- elif fnp.p is mapping and (fnp.p.oneOf or fnp.p.anyOf or 'items' in fnp.p) -%}
463
+ {{- render_xml_schema_children(fnp.p, true, false) }}
464
+ {%- endif -%}
465
+ {{- "</parameters>" }}
466
+ {%- set fn_ret = fn.returns if fn.returns is defined else fn.response -%}
467
+ {%- if fn_ret is mapping -%}{{ render_xml_schema_node("returns", fn_ret, true) }}{%- elif fn_ret is defined -%}<returns>{{ render_xml_value(fn_ret) }}</returns>{%- endif -%}
468
+ {{- "</function>" }}
469
+ {%- endfor -%}
470
+ {{- "\n</ifm|tools>" }}
471
+ {%- endmacro -%}
472
+
473
+ {%- macro render_markdown_literal(value) -%}
474
+ {%- if value is string and value == "" -%}""
475
+ {%- elif value is string -%}`{{ value | replace("\n", "\\n") }}`
476
+ {%- else -%}`{{ render_python_repr(value) }}`
477
+ {%- endif -%}
478
+ {%- endmacro -%}
479
+
480
+ {%- macro render_allowed_values(values) -%}
481
+ {%- for value in values -%}{{ render_markdown_literal(value) }}{% if not loop.last %}, {% endif %}{%- endfor -%}
482
+ {%- endmacro -%}
483
+
484
+ {%- macro render_markdown_value(value) -%}
485
+ {%- if value is string and value == "" -%}""{%- elif value is string -%}{{ value }}{%- else -%}{{ render_python_repr(value) }}{%- endif -%}
486
+ {%- endmacro -%}
487
+
488
+ {%- macro render_markdown_detail(indent, label, value) -%}
489
+ {{- "\n" + indent + " - " + label + ": " }}{{ render_markdown_value(value) }}
490
+ {%- endmacro -%}
491
+
492
+ {%- macro render_markdown_metadata_detail(label, value) -%}
493
+ {{- "\n- " + label + ": " }}{{ render_markdown_value(value) }}
494
+ {%- endmacro -%}
495
+
496
+ {%- macro render_markdown_schema_annotations(spec, indent, include_value_details) -%}
497
+ {%- if include_value_details and spec.description is defined -%}{{ render_markdown_detail(indent, "Description", spec.description | replace("\n", "\n" + indent + " ")) }}{%- endif -%}
498
+ {%- if include_value_details and spec.enum is defined -%}{{- "\n" + indent + " - Allowed values: " }}{{ render_allowed_values(spec.enum) }}{%- endif -%}
499
+ {%- if include_value_details and spec.default is defined -%}{{- "\n" + indent + " - Default: " }}{{ render_markdown_literal(spec.default) }}{%- endif -%}
500
+ {%- if spec.additionalProperties is defined -%}
501
+ {%- if spec.additionalProperties is mapping -%}
502
+ {{- "\n" + indent + " - Additional properties *(" + render_markdown_type(spec.additionalProperties) + ")*" }}
503
+ {{- render_markdown_schema_details(spec.additionalProperties, indent + " ", true) }}
504
+ {%- else -%}
505
+ {{ render_markdown_detail(indent, "Additional properties", spec.additionalProperties) }}
506
+ {%- endif -%}
507
+ {%- endif -%}
508
+ {%- endmacro -%}
509
+
510
+ {%- macro render_markdown_metadata_annotations(spec) -%}
511
+ {%- if spec.description is defined -%}{{ render_markdown_metadata_detail("Description", spec.description | replace("\n", "\n ")) }}{%- endif -%}
512
+ {%- if spec.enum is defined -%}{{- "\n- Allowed values: " }}{{ render_allowed_values(spec.enum) }}{%- endif -%}
513
+ {%- if spec.default is defined -%}{{- "\n- Default: " }}{{ render_markdown_literal(spec.default) }}{%- endif -%}
514
+ {%- if spec.additionalProperties is defined -%}
515
+ {%- if spec.additionalProperties is mapping -%}
516
+ {{- "\n- Additional properties *(" + render_markdown_type(spec.additionalProperties) + ")*" }}
517
+ {{- render_markdown_schema_details(spec.additionalProperties, "", true) }}
518
+ {%- else -%}
519
+ {{ render_markdown_metadata_detail("Additional properties", spec.additionalProperties) }}
520
+ {%- endif -%}
521
+ {%- endif -%}
522
+ {%- endmacro -%}
523
+
524
+ {%- macro render_markdown_schema_extras(spec, indent) -%}
525
+ {%- set rendered_keys = ["type", "description", "enum", "default", "properties", "required", "items", "oneOf", "anyOf", "additionalProperties", "patternProperties", "returns"] -%}
526
+ {%- for key, value in spec | items -%}
527
+ {%- if key not in rendered_keys -%}
528
+ {{- "\n" + indent + " - " + key + ": " }}{{ render_markdown_value(value) }}
529
+ {%- endif -%}
530
+ {%- endfor -%}
531
+ {%- endmacro -%}
532
+
533
+ {%- macro render_markdown_metadata_extras(spec) -%}
534
+ {%- set rendered_keys = ["type", "description", "enum", "default", "properties", "required", "items", "oneOf", "anyOf", "additionalProperties", "patternProperties", "returns"] -%}
535
+ {%- for key, value in spec | items -%}
536
+ {%- if key not in rendered_keys -%}
537
+ {{- "\n- " + key + ": " }}{{ render_markdown_value(value) }}
538
+ {%- endif -%}
539
+ {%- endfor -%}
540
+ {%- endmacro -%}
541
+
542
+ {%- macro markdown_schema_has_extra(spec) -%}
543
+ {%- set rendered_keys = ["type", "description", "enum", "default", "properties", "required", "items", "oneOf", "anyOf", "additionalProperties", "patternProperties", "returns"] -%}
544
+ {%- set found = namespace(value='false') -%}
545
+ {%- for key, value in spec | items -%}
546
+ {%- if key not in rendered_keys -%}{%- set found.value = 'true' -%}{%- endif -%}
547
+ {%- endfor -%}
548
+ {{- found.value -}}
549
+ {%- endmacro -%}
550
+
551
+ {%- macro markdown_parameter_schema_has_details(spec) -%}
552
+ {%- if spec.description is defined or spec.enum is defined or spec.default is defined or spec.additionalProperties is defined or spec.patternProperties is defined or 'items' in spec or spec.oneOf or spec.anyOf or spec.returns is defined or markdown_schema_has_extra(spec) == 'true' -%}
553
+ true
554
+ {%- else -%}
555
+ false
556
+ {%- endif -%}
557
+ {%- endmacro -%}
558
+
559
+ {%- macro render_markdown_schema_structure(spec, indent, include_properties) -%}
560
+ {%- if include_properties and spec.properties -%}
561
+ {%- for child_name, child_spec in spec.properties | items -%}
562
+ {{- render_markdown_param(child_name, child_spec, spec.required or [], indent + " ") }}
563
+ {%- endfor -%}
564
+ {%- endif -%}
565
+ {%- if 'items' in spec and spec['items'] is mapping -%}
566
+ {{- "\n" + indent + " - Items *(" + render_markdown_type(spec['items']) + ")*" }}
567
+ {{- render_markdown_schema_details(spec['items'], indent + " ", true) }}
568
+ {%- elif 'items' in spec -%}
569
+ {{ render_markdown_detail(indent, "Items", spec['items']) }}
570
+ {%- endif -%}
571
+ {%- if spec.oneOf -%}
572
+ {{- "\n" + indent + " - oneOf:" }}
573
+ {%- for variant in spec.oneOf -%}
574
+ {{- "\n" + indent + " - Variant " }}{{ loop.index }}{{- " *(" + render_markdown_type(variant) + ")*" }}
575
+ {{- render_markdown_schema_details(variant, indent + " ", true) }}
576
+ {%- endfor -%}
577
+ {%- endif -%}
578
+ {%- if spec.anyOf -%}
579
+ {{- "\n" + indent + " - anyOf:" }}
580
+ {%- for variant in spec.anyOf -%}
581
+ {{- "\n" + indent + " - Variant " }}{{ loop.index }}{{- " *(" + render_markdown_type(variant) + ")*" }}
582
+ {{- render_markdown_schema_details(variant, indent + " ", true) }}
583
+ {%- endfor -%}
584
+ {%- endif -%}
585
+ {%- if spec.patternProperties is mapping -%}
586
+ {{- "\n" + indent + " - Pattern properties:" }}
587
+ {%- for pattern, pattern_spec in spec.patternProperties | items -%}
588
+ {%- if pattern_spec is mapping -%}
589
+ {{- "\n" + indent + " - `" + pattern + "` *(" + render_markdown_type(pattern_spec) + ")*" }}
590
+ {{- render_markdown_schema_details(pattern_spec, indent + " ", true) }}
591
+ {%- else -%}
592
+ {{- "\n" + indent + " - `" + pattern + "`: " }}{{ render_markdown_value(pattern_spec) }}
593
+ {%- endif -%}
594
+ {%- endfor -%}
595
+ {%- elif spec.patternProperties is defined -%}
596
+ {{ render_markdown_detail(indent, "Pattern properties", spec.patternProperties) }}
597
+ {%- endif -%}
598
+ {%- if spec.returns is mapping -%}
599
+ {{- "\n" + indent + " - Returns *(" + render_markdown_type(spec.returns) + ")*" }}
600
+ {{- render_markdown_schema_details(spec.returns, indent + " ", true) }}
601
+ {%- elif spec.returns is defined -%}
602
+ {{ render_markdown_detail(indent, "Returns", spec.returns) }}
603
+ {%- endif -%}
604
+ {%- endmacro -%}
605
+
606
+ {%- macro render_markdown_schema_details(spec, indent, include_value_details) -%}
607
+ {%- if spec is mapping and spec['$ref'] is string -%}
608
+ {%- set _r = spec['$ref'] -%}
609
+ {%- set _k = _r[8:] if _r.startswith('#/$defs/') else (_r[14:] if _r.startswith('#/definitions/') else none) -%}
610
+ {%- if _k is not none and ('|' + _k + '|') not in REFS.seen and REFS.defs[_k] is mapping -%}
611
+ {%- set spec = dict((REFS.defs[_k] | items | list) + (spec | items | rejectattr('0', 'equalto', '$ref') | list)) -%}
612
+ {%- set REFS.seen = REFS.seen + _k + '|' -%}
613
+ {%- if spec['$ref'] is string -%}
614
+ {%- set _r2 = spec['$ref'] -%}
615
+ {%- set _k2 = _r2[8:] if _r2.startswith('#/$defs/') else (_r2[14:] if _r2.startswith('#/definitions/') else none) -%}
616
+ {%- if _k2 is not none and REFS.defs[_k2] is mapping -%}
617
+ {%- set spec = dict((REFS.defs[_k2] | items | list) + (spec | items | rejectattr('0', 'equalto', '$ref') | list)) -%}
618
+ {%- set REFS.seen = REFS.seen + _k2 + '|' -%}
619
+ {%- endif -%}
620
+ {%- endif -%}
621
+ {%- endif -%}
622
+ {%- endif -%}
623
+ {%- if spec is mapping -%}
624
+ {{- render_markdown_schema_annotations(spec, indent, include_value_details) }}
625
+ {{- render_markdown_schema_structure(spec, indent, true) }}
626
+ {{- render_markdown_schema_extras(spec, indent) }}
627
+ {%- elif spec is not sameas true and spec is not sameas false -%}
628
+ {{- "\n" + indent + " - Value: " }}{{ render_markdown_literal(spec) }}
629
+ {%- endif -%}
630
+ {%- endmacro -%}
631
+
632
+ {%- macro render_markdown_parameter_schema(spec) -%}
633
+ {%- if spec is mapping and spec['$ref'] is string -%}
634
+ {%- set _r = spec['$ref'] -%}
635
+ {%- set _k = _r[8:] if _r.startswith('#/$defs/') else (_r[14:] if _r.startswith('#/definitions/') else none) -%}
636
+ {%- if _k is not none and ('|' + _k + '|') not in REFS.seen and REFS.defs[_k] is mapping -%}
637
+ {%- set spec = dict((REFS.defs[_k] | items | list) + (spec | items | rejectattr('0', 'equalto', '$ref') | list)) -%}
638
+ {%- set REFS.seen = REFS.seen + _k + '|' -%}
639
+ {%- if spec['$ref'] is string -%}
640
+ {%- set _r2 = spec['$ref'] -%}
641
+ {%- set _k2 = _r2[8:] if _r2.startswith('#/$defs/') else (_r2[14:] if _r2.startswith('#/definitions/') else none) -%}
642
+ {%- if _k2 is not none and REFS.defs[_k2] is mapping -%}
643
+ {%- set spec = dict((REFS.defs[_k2] | items | list) + (spec | items | rejectattr('0', 'equalto', '$ref') | list)) -%}
644
+ {%- set REFS.seen = REFS.seen + _k2 + '|' -%}
645
+ {%- endif -%}
646
+ {%- endif -%}
647
+ {%- endif -%}
648
+ {%- endif -%}
649
+ {%- if spec is mapping -%}
650
+ {{- render_markdown_metadata_annotations(spec) }}
651
+ {%- if 'items' in spec and spec['items'] is mapping -%}
652
+ {{- "\n- Items *(" + render_markdown_type(spec['items']) + ")*" }}
653
+ {{- render_markdown_schema_details(spec['items'], "", true) }}
654
+ {%- elif 'items' in spec -%}
655
+ {{ render_markdown_metadata_detail("Items", spec['items']) }}
656
+ {%- endif -%}
657
+ {%- if spec.oneOf -%}
658
+ {{- "\n- oneOf:" }}
659
+ {%- for variant in spec.oneOf -%}
660
+ {{- "\n - Variant " }}{{ loop.index }}{{- " *(" + render_markdown_type(variant) + ")*" }}
661
+ {{- render_markdown_schema_details(variant, " ", true) }}
662
+ {%- endfor -%}
663
+ {%- endif -%}
664
+ {%- if spec.anyOf -%}
665
+ {{- "\n- anyOf:" }}
666
+ {%- for variant in spec.anyOf -%}
667
+ {{- "\n - Variant " }}{{ loop.index }}{{- " *(" + render_markdown_type(variant) + ")*" }}
668
+ {{- render_markdown_schema_details(variant, " ", true) }}
669
+ {%- endfor -%}
670
+ {%- endif -%}
671
+ {%- if spec.patternProperties is mapping -%}
672
+ {{- "\n- Pattern properties:" }}
673
+ {%- for pattern, pattern_spec in spec.patternProperties | items -%}
674
+ {%- if pattern_spec is mapping -%}
675
+ {{- "\n - `" + pattern + "` *(" + render_markdown_type(pattern_spec) + ")*" }}
676
+ {{- render_markdown_schema_details(pattern_spec, " ", true) }}
677
+ {%- else -%}
678
+ {{- "\n - `" + pattern + "`: " }}{{ render_markdown_value(pattern_spec) }}
679
+ {%- endif -%}
680
+ {%- endfor -%}
681
+ {%- elif spec.patternProperties is defined -%}
682
+ {{ render_markdown_metadata_detail("Pattern properties", spec.patternProperties) }}
683
+ {%- endif -%}
684
+ {%- if spec.returns is mapping -%}
685
+ {{- "\n- Returns *(" + render_markdown_type(spec.returns) + ")*" }}
686
+ {{- render_markdown_schema_details(spec.returns, "", true) }}
687
+ {%- elif spec.returns is defined -%}
688
+ {{ render_markdown_metadata_detail("Returns", spec.returns) }}
689
+ {%- endif -%}
690
+ {{- render_markdown_metadata_extras(spec) }}
691
+ {%- endif -%}
692
+ {%- endmacro -%}
693
+
694
+ {%- macro render_markdown_param(name, spec, required_list, indent) -%}
695
+ {%- if spec is mapping and spec['$ref'] is string -%}
696
+ {%- set _r = spec['$ref'] -%}
697
+ {%- set _k = _r[8:] if _r.startswith('#/$defs/') else (_r[14:] if _r.startswith('#/definitions/') else none) -%}
698
+ {%- if _k is not none and ('|' + _k + '|') not in REFS.seen and REFS.defs[_k] is mapping -%}
699
+ {%- set spec = dict((REFS.defs[_k] | items | list) + (spec | items | rejectattr('0', 'equalto', '$ref') | list)) -%}
700
+ {%- set REFS.seen = REFS.seen + _k + '|' -%}
701
+ {%- if spec['$ref'] is string -%}
702
+ {%- set _r2 = spec['$ref'] -%}
703
+ {%- set _k2 = _r2[8:] if _r2.startswith('#/$defs/') else (_r2[14:] if _r2.startswith('#/definitions/') else none) -%}
704
+ {%- if _k2 is not none and REFS.defs[_k2] is mapping -%}
705
+ {%- set spec = dict((REFS.defs[_k2] | items | list) + (spec | items | rejectattr('0', 'equalto', '$ref') | list)) -%}
706
+ {%- set REFS.seen = REFS.seen + _k2 + '|' -%}
707
+ {%- endif -%}
708
+ {%- endif -%}
709
+ {%- endif -%}
710
+ {%- endif -%}
711
+ {{- "\n" + indent + "- `" + name + "` *(" + render_markdown_type(spec) }}
712
+ {%- if name in (required_list or []) -%}{{- ", required" }}{%- endif -%}
713
+ {{- ")*" }}
714
+ {%- if spec.description -%}{{- " - " + spec.description | replace("\n", "\n" + indent + " ") }}{%- endif -%}
715
+ {%- if spec.enum -%}
716
+ {{- "\n" + indent + " - Allowed values: " }}{{ render_allowed_values(spec.enum) }}
717
+ {%- endif -%}
718
+ {%- if spec.default is defined -%}
719
+ {{- "\n" + indent + " - Default: " }}{{ render_markdown_literal(spec.default) }}
720
+ {%- endif -%}
721
+ {{- render_markdown_schema_details(spec, indent, false) }}
722
+ {%- endmacro -%}
723
+
724
+ {%- macro render_tools_markdown(tools_list) -%}
725
+ {{- "<ifm|tools>" }}
726
+ {%- for tool in tools_list -%}
727
+ {%- set fn = tool.function if tool.function is defined else tool -%}
728
+ {%- set REFS.defs = fn.parameters['$defs'] if (fn.parameters is mapping and fn.parameters['$defs'] is mapping) else (fn.parameters['definitions'] if (fn.parameters is mapping and fn.parameters['definitions'] is mapping) else {}) -%}
729
+ {%- set REFS.seen = '|' -%}
730
+ {%- set fnp = namespace(p=fn.parameters) -%}
731
+ {%- if fnp.p is mapping and fnp.p['$ref'] is string -%}
732
+ {%- set _r = fnp.p['$ref'] -%}
733
+ {%- set _k = _r[8:] if _r.startswith('#/$defs/') else (_r[14:] if _r.startswith('#/definitions/') else none) -%}
734
+ {%- if _k is not none and REFS.defs[_k] is mapping -%}
735
+ {%- set fnp.p = dict((REFS.defs[_k] | items | list) + (fnp.p | items | rejectattr('0', 'equalto', '$ref') | list)) -%}
736
+ {%- set REFS.seen = REFS.seen + _k + '|' -%}
737
+ {%- endif -%}
738
+ {%- endif -%}
739
+ {{- "\n## " + fn.name }}
740
+ {%- if fn.description -%}
741
+ {{- "\n" + fn.description }}
742
+ {%- endif -%}
743
+ {{- "\n\n**Parameters**" }}
744
+ {%- if fnp.p and fnp.p.properties -%}
745
+ {%- for pname, pspec in fnp.p.properties | items -%}
746
+ {{- render_markdown_param(pname, pspec, fnp.p.required or [], "") }}
747
+ {%- endfor -%}
748
+ {%- elif fnp.p is mapping and (fnp.p.oneOf or fnp.p.anyOf or 'items' in fnp.p) -%}
749
+ {{- render_markdown_parameter_schema(fnp.p) }}
750
+ {%- else -%}
751
+ {{- "\n- None" }}
752
+ {%- endif -%}
753
+ {%- set fn_ret = fn.returns if fn.returns is defined else fn.response -%}
754
+ {%- if fn_ret is mapping -%}
755
+ {{- "\n\n**Returns**" }}
756
+ {{- "\n- Return *(" + render_markdown_type(fn_ret) + ")*" }}
757
+ {{- render_markdown_schema_details(fn_ret, "", true) }}
758
+ {%- elif fn_ret is defined -%}
759
+ {{- "\n\n**Returns**\n- " }}{{ render_markdown_value(fn_ret) }}
760
+ {%- endif -%}
761
+ {%- if not loop.last -%}{{- "\n" }}{%- endif -%}
762
+ {%- endfor -%}
763
+ {{- "\n</ifm|tools>" }}
764
+ {%- endmacro -%}
765
+
766
+ {%- macro render_tool_presentation(tools_list, fmt) -%}
767
+ {%- if fmt == 'json' -%}
768
+ {{- render_tools_json(tools_list) }}
769
+ {%- elif RB.bad != '|' -%}
770
+ {#- some tool uses constructs the pretty renderers cannot represent (verdicts -#}
771
+ {#- computed during validate_tools): render the WHOLE toolset exactly as the -#}
772
+ {#- json presentation would, so the block stays uniform and model-familiar. -#}
773
+ {{- render_tools_json(tools_list) }}
774
+ {%- elif fmt == 'xml' -%}
775
+ {{- render_tools_xml(tools_list) }}
776
+ {%- elif fmt == 'markdown' -%}
777
+ {{- render_tools_markdown(tools_list) }}
778
+ {%- else -%}
779
+ {{- raise_exception("Unsupported tool_presentation_format: '" + fmt + "'. Supported formats: json, xml, markdown.") }}
780
+ {%- endif -%}
781
+ {%- endmacro -%}
782
+
783
+ {%- macro render_call_instructions(fmt) -%}
784
+ {%- if fmt == 'json' -%}
785
+ {{- "Wrap all tool calls in a single <ifm|tool_calls></ifm|tool_calls> block. For each call, emit one JSON object with the function name and arguments on the same line inside <ifm|tool_call></ifm|tool_call> tags:\n\n<ifm|tool_calls>\n<ifm|tool_call>{\"name\": <function-name>, \"arguments\": <args-json-object>}</ifm|tool_call>\n</ifm|tool_calls>" }}
786
+ {%- elif fmt == 'xml' -%}
787
+ {{- "Wrap all tool calls in a single <ifm|tool_calls></ifm|tool_calls> block. For each call, write the function name at the start of <ifm|tool_call>, followed by paired <ifm|arg_key> and <ifm|arg_value> tags for each argument:\n\n<ifm|tool_calls>\n<ifm|tool_call>$FUNCTION_NAME\n<ifm|arg_key>$PARAMETER_NAME</ifm|arg_key>\n<ifm|arg_value>$PARAMETER_VALUE</ifm|arg_value>\n...\n</ifm|tool_call>\n</ifm|tool_calls>\n\nString and scalar parameters should be written as plain text. Array and object parameters should be written as JSON literals." }}
788
+ {%- elif fmt == 'xml_typed' -%}
789
+ {{- "Wrap all tool calls in a single <ifm|tool_calls></ifm|tool_calls> block. For each call, write the function name at the start of <ifm|tool_call>, followed by <ifm|arg_key>, <ifm|arg_type>, and <ifm|arg_value> tags for each argument:\n\n<ifm|tool_calls>\n<ifm|tool_call>$FUNCTION_NAME\n<ifm|arg_key>$PARAMETER_NAME</ifm|arg_key>\n<ifm|arg_type>$ARGUMENT_TYPE</ifm|arg_type>\n<ifm|arg_value>$PARAMETER_VALUE</ifm|arg_value>\n...\n</ifm|tool_call>\n</ifm|tool_calls>\n\nUse the parameter type shown in the tool definition. If that type contains anyOf or oneOf, use the actual argument value type instead. String and scalar parameters should be written as plain text. Array and object parameters should be written as JSON literals." }}
790
+ {%- else -%}
791
+ {{- raise_exception("Unsupported tool_call_format: '" + fmt + "'. Supported formats: json, xml, xml_typed.") }}
792
+ {%- endif -%}
793
+ {%- endmacro -%}
794
+
795
+ {%- macro render_system_with_tools(tools_list, system_content, presentation_fmt, call_fmt) -%}
796
+ {{- "<|ifm|im_start|>system\n# Tools\nYou may call one or more tools to assist with the user query.\n\nAvailable tools are:\n\n" }}
797
+ {{- render_tool_presentation(tools_list, presentation_fmt) }}
798
+ {{- "\n\nWhen calling tools, you MUST follow the tool-call format below:\n\n" }}
799
+ {{- render_call_instructions(call_fmt) }}
800
+ {%- if system_content -%}
801
+ {{- "\n\n" + system_content }}
802
+ {%- endif -%}
803
+ {{- "<|ifm|im_end|>" }}
804
+ {%- endmacro -%}
805
+
806
+ {%- macro render_argument_value(value) -%}
807
+ {%- if value is string -%}{{- value -}}{%- else -%}{{- value | tojson -}}{%- endif -%}
808
+ {%- endmacro -%}
809
+
810
+ {%- macro render_value_type(value) -%}
811
+ {%- if value is none -%}null
812
+ {%- elif value is boolean -%}boolean
813
+ {%- elif value is integer -%}integer
814
+ {%- elif value is number -%}number
815
+ {%- elif value is string -%}string
816
+ {%- elif value is mapping -%}object
817
+ {%- elif value is sequence -%}array
818
+ {%- else -%}any
819
+ {%- endif -%}
820
+ {%- endmacro -%}
821
+
822
+ {%- macro schema_has_combinator(spec) -%}
823
+ {%- if spec.oneOf or spec.anyOf -%}
824
+ true
825
+ {%- elif spec.type is defined and spec.type is sequence and spec.type is not string and spec.type | length > 1 -%}
826
+ true
827
+ {%- elif spec.type == "array" and 'items' in spec -%}
828
+ {{- schema_has_combinator(spec['items']) -}}
829
+ {%- elif spec.properties -%}
830
+ {%- set found = namespace(value='false') -%}
831
+ {%- for child_name, child_spec in spec.properties | items -%}
832
+ {%- if schema_has_combinator(child_spec) == 'true' -%}
833
+ {%- set found.value = 'true' -%}
834
+ {%- endif -%}
835
+ {%- endfor -%}
836
+ {{- found.value -}}
837
+ {%- else -%}
838
+ false
839
+ {%- endif -%}
840
+ {%- endmacro -%}
841
+
842
+ {%- macro render_arg_type(tools_list, tool_name, arg_name, value) -%}
843
+ {%- set found = namespace(type='any') -%}
844
+ {%- for tool in tools_list -%}
845
+ {%- set fn = tool.function if tool.function is defined else tool -%}
846
+ {%- if fn.name == tool_name and fn.parameters and fn.parameters.properties and arg_name in fn.parameters.properties -%}
847
+ {%- set spec = fn.parameters.properties[arg_name] -%}
848
+ {%- if spec is mapping and spec['$ref'] is string -%}
849
+ {%- set _r = spec['$ref'] -%}
850
+ {%- set _k = _r[8:] if _r.startswith('#/$defs/') else (_r[14:] if _r.startswith('#/definitions/') else none) -%}
851
+ {%- set _d = fn.parameters['$defs'] if fn.parameters['$defs'] is mapping else fn.parameters['definitions'] -%}
852
+ {%- set spec = dict((_d[_k] | items | list) + (spec | items | rejectattr('0', 'equalto', '$ref') | list)) if (_k is not none and _d is mapping and _d[_k] is mapping) else spec -%}
853
+ {%- endif -%}
854
+ {%- if schema_has_combinator(spec) == 'true' -%}
855
+ {%- set found.type = render_value_type(value) -%}
856
+ {%- else -%}
857
+ {%- set found.type = render_compact_type(spec) -%}
858
+ {%- endif -%}
859
+ {%- endif -%}
860
+ {%- endfor -%}
861
+ {{- found.type -}}
862
+ {%- endmacro -%}
863
+
864
+ {%- macro render_tool_calls_block(tool_calls, fmt, tools_list) -%}
865
+ {{- "<ifm|tool_calls>" }}
866
+ {%- for raw_tool_call in tool_calls -%}
867
+ {%- set tool_call = raw_tool_call.function if raw_tool_call.function else raw_tool_call -%}
868
+ {%- if tool_call.arguments is string -%}
869
+ {{- raise_exception("tool_call.arguments must be a dict, not a JSON string. Parse it before passing to the template.") -}}
870
+ {%- endif -%}
871
+ {%- if fmt == 'json' -%}
872
+ {{- "\n<ifm|tool_call>{\"name\": \"" + tool_call.name + "\", \"arguments\": " }}{{ tool_call.arguments | tojson }}{{- "}</ifm|tool_call>" }}
873
+ {%- elif fmt == 'xml' or fmt == 'xml_typed' -%}
874
+ {{- "\n<ifm|tool_call>" + tool_call.name + "\n" }}
875
+ {%- for key, value in tool_call.arguments | items -%}
876
+ {{- "<ifm|arg_key>" + key + "</ifm|arg_key>\n" }}
877
+ {%- if fmt == 'xml_typed' -%}
878
+ {{- "<ifm|arg_type>" + render_arg_type(tools_list, tool_call.name, key, value) + "</ifm|arg_type>\n" }}
879
+ {%- endif -%}
880
+ {{- "<ifm|arg_value>" }}{{ render_argument_value(value) }}{{- "</ifm|arg_value>\n" }}
881
+ {%- endfor -%}
882
+ {{- "</ifm|tool_call>" }}
883
+ {%- else -%}
884
+ {{- raise_exception("Unsupported tool_call_format: '" + fmt + "'. Supported formats: json, xml, xml_typed.") -}}
885
+ {%- endif -%}
886
+ {%- endfor -%}
887
+ {{- "\n</ifm|tool_calls>" }}
888
+ {%- endmacro -%}
889
+
890
+ {%- macro render_tool_response_messages(raw_content) -%}
891
+ {%- if raw_content is string -%}
892
+ {{- '<|ifm|im_start|>tool\n' + raw_content + '<|ifm|im_end|>' }}
893
+ {%- elif raw_content is sequence and raw_content is not string and raw_content is not mapping -%}
894
+ {%- if raw_content | length == 0 -%}
895
+ {{- raise_exception("tool message content list must not be empty.") -}}
896
+ {%- endif -%}
897
+ {{- '<|ifm|im_start|>tool\n' -}}
898
+ {%- for item in raw_content -%}
899
+ {%- if not loop.first -%}{{- '\n' -}}{%- endif -%}
900
+ {%- if item is string -%}
901
+ {{- item -}}
902
+ {%- elif item is mapping and item.text is string -%}
903
+ {{- item.text -}}
904
+ {%- else -%}
905
+ {{- (item | tojson) -}}
906
+ {%- endif -%}
907
+ {%- endfor -%}
908
+ {{- '<|ifm|im_end|>' -}}
909
+ {%- else -%}
910
+ {{- '<|ifm|im_start|>tool\n' }}{{ raw_content | tojson }}{{- '<|ifm|im_end|>' }}
911
+ {%- endif -%}
912
+ {%- endmacro -%}
913
+
914
+ {%- set available_tools = tools if tools else [] -%}
915
+ {%- if (not available_tools) and messages[0].role == 'system' and messages[0].get('tools') -%}
916
+ {%- set available_tools = messages[0]['tools'] -%}
917
+ {%- endif -%}
918
+ {%- if available_tools -%}
919
+ {{- validate_tools(available_tools, tool_presentation_fmt != 'json') }}
920
+ {%- set system_content = '' -%}
921
+ {%- if messages[0].role == 'system' and messages[0].content -%}
922
+ {%- set system_content = messages[0].content -%}
923
+ {%- endif -%}
924
+ {{- render_system_with_tools(available_tools, system_content, tool_presentation_fmt, tool_call_fmt) }}
925
+ {%- else -%}
926
+ {%- if messages[0].role == 'system' -%}
927
+ {{- '<|ifm|im_start|>system\n' + messages[0].content + '<|ifm|im_end|>' }}
928
+ {%- endif -%}
929
+ {%- endif -%}
930
+
931
+ {%- for message in messages -%}
932
+ {%- if message.content is string -%}
933
+ {%- set content = message.content -%}
934
+ {%- else -%}
935
+ {%- set content = '' -%}
936
+ {%- endif -%}
937
+ {%- if (message.role == "user") or (message.role == "system" and not loop.first) -%}
938
+ {{- '<|ifm|im_start|>' + message.role + '\n' + content + '<|ifm|im_end|>' }}
939
+ {%- elif message.role == "assistant" -%}
940
+ {%- set thinking_content = '' -%}
941
+ {%- set think_tag = '' -%}
942
+ {%- if message.think is defined and message.think is string -%}
943
+ {%- set thinking_content = message.think -%}
944
+ {%- set think_tag = 'ifm|think' -%}
945
+ {%- elif message.think_fast is defined and message.think_fast is string -%}
946
+ {%- set thinking_content = message.think_fast -%}
947
+ {%- set think_tag = 'ifm|think_fast' -%}
948
+ {%- elif message.think_faster is defined and message.think_faster is string -%}
949
+ {%- set thinking_content = message.think_faster -%}
950
+ {%- set think_tag = 'ifm|think_faster' -%}
951
+ {%- else -%}
952
+ {%- if '</ifm|think>' in content -%}
953
+ {%- set thinking_content = content.split('</ifm|think>')[0].rstrip('\n').split('<ifm|think>')[-1].lstrip('\n') -%}
954
+ {%- set content = content.split('</ifm|think>')[-1].lstrip('\n') -%}
955
+ {%- set think_tag = 'ifm|think' -%}
956
+ {%- elif '</ifm|think_fast>' in content -%}
957
+ {%- set thinking_content = content.split('</ifm|think_fast>')[0].rstrip('\n').split('<ifm|think_fast>')[-1].lstrip('\n') -%}
958
+ {%- set content = content.split('</ifm|think_fast>')[-1].lstrip('\n') -%}
959
+ {%- set think_tag = 'ifm|think_fast' -%}
960
+ {%- elif '</ifm|think_faster>' in content -%}
961
+ {%- set thinking_content = content.split('</ifm|think_faster>')[0].rstrip('\n').split('<ifm|think_faster>')[-1].lstrip('\n') -%}
962
+ {%- set content = content.split('</ifm|think_faster>')[-1].lstrip('\n') -%}
963
+ {%- set think_tag = 'ifm|think_faster' -%}
964
+ {%- endif -%}
965
+ {%- endif -%}
966
+ {{- '<|ifm|im_start|>' + message.role }}
967
+ {% generation %}
968
+ {%- if think_tag -%}
969
+ {%- if thinking_content -%}
970
+ {{- '<' + think_tag + '>\n' + thinking_content + '\n</' + think_tag + '>\n' + content.lstrip('\n') }}
971
+ {%- else -%}
972
+ {{- '<' + think_tag + '>\n</' + think_tag + '>\n' + content.lstrip('\n') }}
973
+ {%- endif -%}
974
+ {%- else -%}
975
+ {{- content }}
976
+ {%- endif -%}
977
+ {%- if message.tool_calls -%}
978
+ {%- if content -%}
979
+ {{- '\n' }}
980
+ {%- endif -%}
981
+ {{- render_tool_calls_block(message.tool_calls, tool_call_fmt, available_tools) }}
982
+ {%- endif -%}
983
+ {{- '<|ifm|im_end|>' -}}
984
+ {%- endgeneration -%}
985
+ {%- elif message.role == "tool" -%}
986
+ {{- render_tool_response_messages(message.content) }}
987
+ {%- endif -%}
988
+ {%- endfor -%}
989
+ {%- if add_generation_prompt -%}
990
+ {%- set effort = reasoning_effort | default('high') -%}
991
+ {%- if effort == 'high' -%}
992
+ {{- '<|ifm|im_start|>assistant\n<ifm|think>\n' }}
993
+ {%- elif effort == 'medium' -%}
994
+ {{- '<|ifm|im_start|>assistant\n<ifm|think_fast>\n' }}
995
+ {%- elif effort == 'low' -%}
996
+ {{- '<|ifm|im_start|>assistant\n<ifm|think_faster>\n' }}
997
+ {%- else -%}
998
+ {{- '<|ifm|im_start|>assistant\n<ifm|think_fast>\n' }}
999
+ {%- endif -%}
1000
+ {%- endif -%}
chat_template_generation.jinja ADDED
@@ -0,0 +1,1009 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {{- bos_token }}
2
+ {%- if tool_presentation is defined -%}
3
+ {{- raise_exception("Unsupported argument: tool_presentation. Use tool_presentation_format with one of: json, xml, markdown.") -}}
4
+ {%- endif -%}
5
+ {%- if tool_calling_format is defined -%}
6
+ {{- raise_exception("Unsupported argument: tool_calling_format. Use tool_call_format with one of: json, xml, xml_typed.") -}}
7
+ {%- endif -%}
8
+ {%- if tool_format is defined -%}
9
+ {{- raise_exception("Unsupported argument: tool_format. Use tool_call_format with one of: json, xml, xml_typed.") -}}
10
+ {%- endif -%}
11
+ {%- set tool_presentation_fmt = tool_presentation_format | default('markdown') -%}
12
+ {%- set tool_call_fmt = tool_call_format | default('xml') -%}
13
+ {%- if tool_presentation_fmt != 'json' and tool_presentation_fmt != 'xml' and tool_presentation_fmt != 'markdown' -%}
14
+ {{- raise_exception("Unsupported tool_presentation_format: '" ~ tool_presentation_fmt ~ "'. Supported formats: json, xml, markdown.") -}}
15
+ {%- endif -%}
16
+ {%- if tool_call_fmt != 'json' and tool_call_fmt != 'xml' and tool_call_fmt != 'xml_typed' -%}
17
+ {{- raise_exception("Unsupported tool_call_format: '" ~ tool_call_fmt ~ "'. Supported formats: json, xml, xml_typed.") -}}
18
+ {%- endif -%}
19
+
20
+ {#- Renderability state, computed during validate_tools (single walk, no extra -#}
21
+ {#- traversal at render time): ok = working flag for the tool being validated; -#}
22
+ {#- bad = pipe-delimited indices of tools that must render as verbatim JSON. -#}
23
+ {%- set RB = namespace(ok=true, bad='|') -%}
24
+
25
+ {%- macro value_contains_mapping(v) -%}
26
+ {%- if v is mapping -%}
27
+ true
28
+ {%- elif v is sequence and v is not string -%}
29
+ {%- set f = namespace(x='false') -%}
30
+ {%- for c in v -%}{%- if value_contains_mapping(c) == 'true' -%}{%- set f.x = 'true' -%}{%- endif -%}{%- endfor -%}
31
+ {{- f.x -}}
32
+ {%- else -%}
33
+ false
34
+ {%- endif -%}
35
+ {%- endmacro -%}
36
+
37
+ {#- $ref inlining state: defs = local $defs of the tool being rendered; seen = -#}
38
+ {#- pipe-delimited names already expanded for this tool (each def inlines at most -#}
39
+ {#- once; later references render by def name; cycles terminate immediately). -#}
40
+ {#- $ref-sibling annotations (description/default/...) merge OVER the def at -#}
41
+ {#- the inline site, so use-site annotations win and are never dropped. -#}
42
+ {%- set REFS = namespace(defs={}, seen='|') -%}
43
+
44
+ {%- macro render_compact_type_name(type_name, spec) -%}
45
+ {%- if type_name == "array" -%}
46
+ array[{%- if 'items' in spec -%}{{ render_compact_type(spec['items']) }}{%- else -%}any{%- endif -%}]
47
+ {%- elif type_name -%}
48
+ {{- type_name -}}
49
+ {%- else -%}
50
+ any
51
+ {%- endif -%}
52
+ {%- endmacro -%}
53
+
54
+ {%- macro render_compact_type(spec) -%}
55
+ {%- if spec is not mapping -%}
56
+ any
57
+ {%- elif spec.type is defined and spec.type is sequence and spec.type is not string and spec.type | length > 0 -%}
58
+ {%- for type_name in spec.type -%}{{ render_compact_type_name(type_name, spec) }}{%- if not loop.last -%}|{%- endif -%}{%- endfor -%}
59
+ {%- elif spec.type is defined and spec.type is sequence and spec.type is not string -%}
60
+ any
61
+ {%- elif spec.type -%}
62
+ {{- render_compact_type_name(spec.type, spec) -}}
63
+ {%- elif spec['$ref'] is string -%}
64
+ {{- spec['$ref'].split('/') | last -}}
65
+ {%- elif spec.oneOf -%}
66
+ oneOf[{%- for variant in spec.oneOf -%}{{ render_compact_type(variant) }}{%- if not loop.last -%}|{%- endif -%}{%- endfor -%}]
67
+ {%- elif spec.anyOf -%}
68
+ anyOf[{%- for variant in spec.anyOf -%}{{ render_compact_type(variant) }}{%- if not loop.last -%}|{%- endif -%}{%- endfor -%}]
69
+ {%- elif spec.properties -%}
70
+ object
71
+ {%- elif 'items' in spec -%}
72
+ array[{{ render_compact_type(spec['items']) }}]
73
+ {%- else -%}
74
+ any
75
+ {%- endif -%}
76
+ {%- endmacro -%}
77
+
78
+ {%- macro render_markdown_type_name(type_name, spec) -%}
79
+ {%- if type_name == "array" -%}
80
+ array of {% if 'items' in spec %}{{ render_markdown_type(spec['items']) }}{% else %}any{% endif %}
81
+ {%- elif type_name -%}
82
+ {{- type_name -}}
83
+ {%- else -%}
84
+ any
85
+ {%- endif -%}
86
+ {%- endmacro -%}
87
+
88
+ {%- macro render_markdown_type(spec) -%}
89
+ {%- if spec is sameas true -%}
90
+ True
91
+ {%- elif spec is sameas false -%}
92
+ False
93
+ {%- elif spec is not mapping -%}
94
+ any
95
+ {%- elif spec.type is defined and spec.type is sequence and spec.type is not string and spec.type | length > 0 -%}
96
+ {%- for type_name in spec.type -%}{{ render_markdown_type_name(type_name, spec) }}{% if not loop.last %} or {% endif %}{%- endfor -%}
97
+ {%- elif spec.type is defined and spec.type is sequence and spec.type is not string -%}
98
+ any
99
+ {%- elif spec.type -%}
100
+ {{- render_markdown_type_name(spec.type, spec) -}}
101
+ {%- elif spec['$ref'] is string -%}
102
+ {{- spec['$ref'].split('/') | last -}}
103
+ {%- elif spec.oneOf -%}
104
+ oneOf[{%- for variant in spec.oneOf -%}{{ render_markdown_type(variant) }}{% if not loop.last %} or {% endif %}{%- endfor -%}]
105
+ {%- elif spec.anyOf -%}
106
+ anyOf[{%- for variant in spec.anyOf -%}{{ render_markdown_type(variant) }}{% if not loop.last %} or {% endif %}{%- endfor -%}]
107
+ {%- elif spec.properties -%}
108
+ object
109
+ {%- elif 'items' in spec -%}
110
+ array of {{ render_markdown_type(spec['items']) }}
111
+ {%- else -%}
112
+ any
113
+ {%- endif -%}
114
+ {%- endmacro -%}
115
+
116
+ {%- macro render_xml_text(value) -%}
117
+ {{- value.split() | join(" ") -}}
118
+ {%- endmacro -%}
119
+
120
+ {%- macro render_python_string(value) -%}
121
+ '{{- value.split() | join(" ") | replace("\\", "\\\\") | replace("'", "\\'") -}}'
122
+ {%- endmacro -%}
123
+
124
+ {%- macro render_python_repr(value) -%}
125
+ {%- if value is string -%}
126
+ {{ render_python_string(value) }}
127
+ {%- elif value is sameas true -%}
128
+ True
129
+ {%- elif value is sameas false -%}
130
+ False
131
+ {%- elif value is none -%}
132
+ None
133
+ {%- elif value is mapping -%}
134
+ {{- "{" -}}
135
+ {%- for key, child in value | items -%}
136
+ {{ render_python_repr(key) }}: {{ render_python_repr(child) }}{%- if not loop.last -%}, {% endif -%}
137
+ {%- endfor -%}
138
+ {{- "}" -}}
139
+ {%- elif value is sequence -%}
140
+ {{- "[" -}}
141
+ {%- for child in value -%}
142
+ {{ render_python_repr(child) }}{%- if not loop.last -%}, {% endif -%}
143
+ {%- endfor -%}
144
+ {{- "]" -}}
145
+ {%- else -%}
146
+ {{- value -}}
147
+ {%- endif -%}
148
+ {%- endmacro -%}
149
+
150
+ {%- macro render_xml_value(value) -%}
151
+ {%- if value is string -%}{{ render_xml_text(value) }}{%- else -%}{{ render_python_repr(value) }}{%- endif -%}
152
+ {%- endmacro -%}
153
+
154
+ {%- macro render_xml_enum_value(value) -%}
155
+ {%- if value is string -%}"{{- value | replace("\\", "\\\\") | replace("\"", "\\\"") -}}"{%- else -%}"{{- render_python_repr(value) | replace("\\", "\\\\") | replace("\"", "\\\"") -}}"{%- endif -%}
156
+ {%- endmacro -%}
157
+
158
+ {%- macro render_xml_enum(values) -%}
159
+ {%- for value in values -%}{{ render_xml_enum_value(value) }}{%- if not loop.last -%}|{%- endif -%}{%- endfor -%}
160
+ {%- endmacro -%}
161
+
162
+ {%- macro render_xml_default_attr(value) -%}
163
+ {{- " default=" }}{%- if value is string -%}"{{- value | replace("\\", "\\\\") | replace("\"", "\\\"") -}}"{%- else -%}{{ render_xml_value(value) }}{%- endif -%}
164
+ {%- endmacro -%}
165
+
166
+ {%- macro render_xml_attr(name, value) -%}
167
+ {{- " " + name + "=" }}{%- if value == "" -%}""{%- else -%}{{ render_xml_value(value) }}{%- endif -%}
168
+ {%- endmacro -%}
169
+
170
+ {%- macro validate_schema(spec, path, lenient=false, classify=true, in_variant=false) -%}
171
+ {%- if spec is mapping -%}
172
+ {%- if not lenient -%}
173
+ {%- if spec.required is defined -%}
174
+ {%- if spec.required is string or spec.required is not sequence -%}
175
+ {{- raise_exception("Schema '" + path + "' has 'required' but it is not a list.") -}}
176
+ {%- endif -%}
177
+ {%- if spec.required | length > 0 and not spec.properties and not in_variant -%}
178
+ {{- raise_exception("Schema '" + path + "' has required fields but no properties object to define them.") -}}
179
+ {%- endif -%}
180
+ {%- if spec.properties -%}
181
+ {%- for required_name in spec.required -%}
182
+ {%- if required_name not in spec.properties -%}
183
+ {{- raise_exception("Schema '" + path + "' marks '" + required_name + "' as required, but that property is not defined in properties.") -}}
184
+ {%- endif -%}
185
+ {%- endfor -%}
186
+ {%- endif -%}
187
+ {%- endif -%}
188
+ {%- endif -%}
189
+ {#- renderability classification, piggybacking on this walk (no raises here): -#}
190
+ {#- constructs the pretty renderer does not fully handle flip RB.ok so the -#}
191
+ {#- tool falls back to verbatim JSON. Skipped entirely for json presentation. -#}
192
+ {%- if classify -%}
193
+ {%- for key, value in spec | items -%}
194
+ {%- if key == '$ref' -%}
195
+ {%- if value is not string -%}{%- set RB.ok = false -%}
196
+ {%- elif not (value.startswith('#/$defs/') or value.startswith('#/definitions/')) -%}{%- set RB.ok = false -%}{%- endif -%}
197
+ {%- elif key == '$defs' or key == 'definitions' -%}
198
+ {%- if value is mapping -%}
199
+ {%- for dk, dv in value | items -%}
200
+ {{- validate_schema(dv, path + ".$defs." + dk, true) -}}
201
+ {%- endfor -%}
202
+ {%- else -%}{%- set RB.ok = false -%}{%- endif -%}
203
+ {%- elif key == 'type' -%}
204
+ {%- if value is mapping -%}{%- set RB.ok = false -%}{%- endif -%}
205
+ {%- elif key == 'enum' -%}
206
+ {%- if value is string or value is mapping or value is not sequence -%}{%- set RB.ok = false -%}{%- endif -%}
207
+ {%- elif key == 'items' -%}
208
+ {#- any items shape renders: mapping structurally, others via repr detail -#}
209
+ {%- elif key == 'oneOf' or key == 'anyOf' -%}
210
+ {%- if value is mapping or value is string or value is not sequence -%}{%- set RB.ok = false -%}{%- endif -%}
211
+ {%- elif key == 'required' -%}
212
+ {%- if value and not spec.properties -%}{%- set RB.ok = false -%}{%- endif -%}
213
+ {%- elif ('|' ~ key ~ '|') in '|description|default|title|examples|properties|patternProperties|additionalProperties|returns|' -%}
214
+ {%- elif value is mapping -%}
215
+ {%- for uk, uv in value | items -%}
216
+ {%- if value_contains_mapping(uv) == 'true' -%}{%- set RB.ok = false -%}{%- endif -%}
217
+ {%- endfor -%}
218
+ {%- elif value is sequence and value is not string -%}
219
+ {%- if value_contains_mapping(value) == 'true' -%}{%- set RB.ok = false -%}{%- endif -%}
220
+ {%- endif -%}
221
+ {%- endfor -%}
222
+ {%- endif -%}
223
+ {%- if spec.properties -%}
224
+ {%- for child_name, child_spec in spec.properties | items -%}
225
+ {{- validate_schema(child_spec, path + "." + child_name, lenient, classify) -}}
226
+ {%- endfor -%}
227
+ {%- endif -%}
228
+ {%- if 'items' in spec -%}{{- validate_schema(spec['items'], path + "[]", lenient, classify) -}}{%- endif -%}
229
+ {%- if spec.oneOf -%}
230
+ {%- for variant in spec.oneOf -%}{{- validate_schema(variant, path + ".oneOf[" + (loop.index0 | string) + "]", lenient, classify, true) -}}{%- endfor -%}
231
+ {%- endif -%}
232
+ {%- if spec.anyOf -%}
233
+ {%- for variant in spec.anyOf -%}{{- validate_schema(variant, path + ".anyOf[" + (loop.index0 | string) + "]", lenient, classify, true) -}}{%- endfor -%}
234
+ {%- endif -%}
235
+ {%- if spec.additionalProperties is mapping -%}{{- validate_schema(spec.additionalProperties, path + ".additionalProperties", lenient, classify) -}}{%- endif -%}
236
+ {%- if spec.patternProperties is mapping -%}
237
+ {%- for pattern, pattern_spec in spec.patternProperties | items -%}
238
+ {{- validate_schema(pattern_spec, path + ".patternProperties[" + pattern + "]", lenient, classify) -}}
239
+ {%- endfor -%}
240
+ {%- endif -%}
241
+ {%- if spec.returns is mapping -%}{{- validate_schema(spec.returns, path + ".returns", lenient, classify) -}}{%- endif -%}
242
+ {%- endif -%}
243
+ {%- endmacro -%}
244
+
245
+ {%- macro validate_tools(tools_list, classify=true) -%}
246
+ {%- set RB.bad = '|' -%}
247
+ {%- for tool in tools_list -%}
248
+ {%- set fn = tool.function if tool.function is defined else tool -%}
249
+ {%- set RB.ok = true -%}
250
+ {%- if fn.parameters is defined and fn.parameters is string -%}
251
+ {{- raise_exception("tool.function.parameters must be a dict, not a JSON string. Parse it before passing to the template.") -}}
252
+ {%- endif -%}
253
+ {%- if fn.parameters is not defined or fn.parameters is none -%}
254
+ {%- if fn.arguments is defined -%}
255
+ {{- raise_exception("Tool '" + fn.name + "' has 'arguments' instead of 'parameters'. Rename 'arguments' to 'parameters'.") -}}
256
+ {%- else -%}
257
+ {{- raise_exception("Tool '" + fn.name + "' is missing required 'parameters' field. Each tool must have a 'parameters' dict with 'type', 'properties', and 'required' keys.") -}}
258
+ {%- endif -%}
259
+ {%- endif -%}
260
+ {{- validate_schema(fn.parameters, "tool." + fn.name + ".parameters", false, classify) -}}
261
+ {%- if classify -%}
262
+ {%- if fn.parameters is mapping -%}
263
+ {#- unknown container-valued keys at the parameters ROOT are never rendered -#}
264
+ {#- by the pretty path (root extras are dropped) -> verbatim fallback. -#}
265
+ {%- for rk, rv in fn.parameters | items -%}
266
+ {%- if rk not in ['type', 'description', 'enum', 'default', 'properties', 'required', 'optional', 'title', 'items', 'oneOf', 'anyOf', 'additionalProperties', 'patternProperties', 'returns', 'examples', '$defs', 'definitions', '$ref'] -%}
267
+ {%- if rv is mapping or (rv is sequence and rv is not string) -%}{%- set RB.ok = false -%}{%- endif -%}
268
+ {%- endif -%}
269
+ {%- endfor -%}
270
+ {%- else -%}
271
+ {%- set RB.ok = false -%}
272
+ {%- endif -%}
273
+ {%- endif -%}
274
+ {%- if fn.returns is mapping -%}{{- validate_schema(fn.returns, "tool." + fn.name + ".returns", false, classify) -}}{%- endif -%}
275
+ {%- if classify and fn.returns is not defined and fn.response is mapping -%}{{- validate_schema(fn.response, "tool." + fn.name + ".response", true) -}}{%- endif -%}
276
+ {#- unknown container-valued keys at the FUNCTION level are never rendered -> fallback. -#}
277
+ {%- if classify -%}
278
+ {%- for fk, fv in fn | items -%}
279
+ {%- if fk not in ['name', 'description', 'parameters', 'returns', 'response', 'type', 'function'] -%}
280
+ {%- if fv is mapping or (fv is sequence and fv is not string) -%}{%- set RB.ok = false -%}{%- endif -%}
281
+ {%- endif -%}
282
+ {%- endfor -%}
283
+ {%- endif -%}
284
+ {%- if not RB.ok -%}{%- set RB.bad = RB.bad ~ loop.index0 ~ '|' -%}{%- endif -%}
285
+ {%- endfor -%}
286
+ {%- endmacro -%}
287
+
288
+ {%- macro render_tools_json(tools_list) -%}
289
+ {{- "<ifm|tools>" }}
290
+ {%- for tool in tools_list %}
291
+ {{- "\n" }}
292
+ {{- tool | tojson }}
293
+ {%- endfor %}
294
+ {{- "\n</ifm|tools>" }}
295
+ {%- endmacro -%}
296
+
297
+ {%- macro render_xml_schema_attrs(spec, include_value_attrs) -%}
298
+ {%- if spec is mapping -%}
299
+ {%- set structural_keys = ["type", "description", "enum", "default", "properties", "required", "items", "oneOf", "anyOf", "additionalProperties", "patternProperties", "returns"] -%}
300
+ {%- if include_value_attrs and spec.enum -%}{{- " enum=" }}{{ render_xml_enum(spec.enum) }}{%- endif -%}
301
+ {%- if include_value_attrs and spec.default is defined -%}{{ render_xml_default_attr(spec.default) }}{%- endif -%}
302
+ {%- if spec.additionalProperties is defined and spec.additionalProperties is not mapping -%}{{ render_xml_attr("additionalProperties", spec.additionalProperties) }}{%- endif -%}
303
+ {%- if spec.patternProperties is defined and spec.patternProperties is not mapping -%}{{ render_xml_attr("patternProperties", spec.patternProperties) }}{%- endif -%}
304
+ {%- for key, value in spec | items -%}
305
+ {%- if key not in structural_keys -%}
306
+ {{ render_xml_attr(key, value) }}
307
+ {%- endif -%}
308
+ {%- endfor -%}
309
+ {%- endif -%}
310
+ {%- endmacro -%}
311
+
312
+ {%- macro xml_schema_has_children(spec, include_properties, include_description) -%}
313
+ {%- if spec is not mapping -%}
314
+ false
315
+ {%- elif (include_description and spec.description is defined) or (include_properties and spec.properties) or 'items' in spec or spec.oneOf or spec.anyOf or spec.additionalProperties is mapping or spec.patternProperties is mapping or spec.returns is defined -%}
316
+ true
317
+ {%- else -%}
318
+ false
319
+ {%- endif -%}
320
+ {%- endmacro -%}
321
+
322
+ {%- macro render_xml_schema_node(tag, spec, include_properties) -%}
323
+ {%- if spec is mapping and spec['$ref'] is string -%}
324
+ {%- set _r = spec['$ref'] -%}
325
+ {%- set _k = _r[8:] if _r.startswith('#/$defs/') else (_r[14:] if _r.startswith('#/definitions/') else none) -%}
326
+ {%- if _k is not none and ('|' + _k + '|') not in REFS.seen and REFS.defs[_k] is mapping -%}
327
+ {%- set spec = dict((REFS.defs[_k] | items | list) + (spec | items | rejectattr('0', 'equalto', '$ref') | list)) -%}
328
+ {%- set REFS.seen = REFS.seen + _k + '|' -%}
329
+ {%- if spec['$ref'] is string -%}
330
+ {%- set _r2 = spec['$ref'] -%}
331
+ {%- set _k2 = _r2[8:] if _r2.startswith('#/$defs/') else (_r2[14:] if _r2.startswith('#/definitions/') else none) -%}
332
+ {%- if _k2 is not none and REFS.defs[_k2] is mapping -%}
333
+ {%- set spec = dict((REFS.defs[_k2] | items | list) + (spec | items | rejectattr('0', 'equalto', '$ref') | list)) -%}
334
+ {%- set REFS.seen = REFS.seen + _k2 + '|' -%}
335
+ {%- endif -%}
336
+ {%- endif -%}
337
+ {%- endif -%}
338
+ {%- endif -%}
339
+ {%- if spec is mapping -%}
340
+ {{- "<" + tag + " type=" + render_compact_type(spec) }}{{ render_xml_schema_attrs(spec, true) }}
341
+ {%- if xml_schema_has_children(spec, include_properties, true) == 'true' -%}
342
+ {{- ">" }}{{ render_xml_schema_children(spec, include_properties, true) }}{{- "</" + tag + ">" }}
343
+ {%- else -%}
344
+ {{- "/>" }}
345
+ {%- endif -%}
346
+ {%- else -%}
347
+ {{- "<" + tag + ">" }}{{ render_xml_value(spec) }}{{- "</" + tag + ">" }}
348
+ {%- endif -%}
349
+ {%- endmacro -%}
350
+
351
+ {%- macro render_xml_pattern_property(pattern, spec) -%}
352
+ {%- if spec is mapping and spec['$ref'] is string -%}
353
+ {%- set _r = spec['$ref'] -%}
354
+ {%- set _k = _r[8:] if _r.startswith('#/$defs/') else (_r[14:] if _r.startswith('#/definitions/') else none) -%}
355
+ {%- if _k is not none and ('|' + _k + '|') not in REFS.seen and REFS.defs[_k] is mapping -%}
356
+ {%- set spec = dict((REFS.defs[_k] | items | list) + (spec | items | rejectattr('0', 'equalto', '$ref') | list)) -%}
357
+ {%- set REFS.seen = REFS.seen + _k + '|' -%}
358
+ {%- if spec['$ref'] is string -%}
359
+ {%- set _r2 = spec['$ref'] -%}
360
+ {%- set _k2 = _r2[8:] if _r2.startswith('#/$defs/') else (_r2[14:] if _r2.startswith('#/definitions/') else none) -%}
361
+ {%- if _k2 is not none and REFS.defs[_k2] is mapping -%}
362
+ {%- set spec = dict((REFS.defs[_k2] | items | list) + (spec | items | rejectattr('0', 'equalto', '$ref') | list)) -%}
363
+ {%- set REFS.seen = REFS.seen + _k2 + '|' -%}
364
+ {%- endif -%}
365
+ {%- endif -%}
366
+ {%- endif -%}
367
+ {%- endif -%}
368
+ {%- if spec is mapping -%}
369
+ {{- "<patternProperty" }}{{ render_xml_attr("pattern", pattern) }}{{- " type=" + render_compact_type(spec) }}{{ render_xml_schema_attrs(spec, true) }}
370
+ {%- if xml_schema_has_children(spec, true, true) == 'true' -%}
371
+ {{- ">" }}{{ render_xml_schema_children(spec, true, true) }}{{- "</patternProperty>" }}
372
+ {%- else -%}
373
+ {{- "/>" }}
374
+ {%- endif -%}
375
+ {%- else -%}
376
+ {{- "<patternProperty" }}{{ render_xml_attr("pattern", pattern) }}{{- ">" }}{{ render_xml_value(spec) }}{{- "</patternProperty>" }}
377
+ {%- endif -%}
378
+ {%- endmacro -%}
379
+
380
+ {%- macro render_xml_schema_children(spec, include_properties, include_description) -%}
381
+ {%- if include_description and spec.description is defined -%}{{- "<description>" }}{{ spec.description }}{{- "</description>" }}{%- endif -%}
382
+ {%- if include_properties and spec.properties -%}
383
+ {%- for child_name, child_spec in spec.properties | items -%}
384
+ {{- render_xml_param(child_name, child_spec, spec.required or []) }}
385
+ {%- endfor -%}
386
+ {%- endif -%}
387
+ {%- if 'items' in spec -%}{{ render_xml_schema_node("items", spec['items'], true) }}{%- endif -%}
388
+ {%- if spec.oneOf -%}
389
+ {{- "<oneOf>" }}
390
+ {%- for variant in spec.oneOf -%}{{ render_xml_schema_node("variant", variant, true) }}{%- endfor -%}
391
+ {{- "</oneOf>" }}
392
+ {%- endif -%}
393
+ {%- if spec.anyOf -%}
394
+ {{- "<anyOf>" }}
395
+ {%- for variant in spec.anyOf -%}{{ render_xml_schema_node("variant", variant, true) }}{%- endfor -%}
396
+ {{- "</anyOf>" }}
397
+ {%- endif -%}
398
+ {%- if spec.additionalProperties is mapping -%}{{ render_xml_schema_node("additionalProperties", spec.additionalProperties, true) }}{%- endif -%}
399
+ {%- if spec.patternProperties is mapping -%}
400
+ {{- "<patternProperties>" }}
401
+ {%- for pattern, pattern_spec in spec.patternProperties | items -%}{{ render_xml_pattern_property(pattern, pattern_spec) }}{%- endfor -%}
402
+ {{- "</patternProperties>" }}
403
+ {%- elif spec.patternProperties is defined -%}<patternProperties>{{ render_xml_value(spec.patternProperties) }}</patternProperties>{%- endif -%}
404
+ {%- if spec.returns is mapping -%}{{ render_xml_schema_node("returns", spec.returns, true) }}{%- elif spec.returns is defined -%}<returns>{{ render_xml_value(spec.returns) }}</returns>{%- endif -%}
405
+ {%- endmacro -%}
406
+
407
+ {%- macro render_xml_param(name, spec, required_list) -%}
408
+ {%- if spec is mapping and spec['$ref'] is string -%}
409
+ {%- set _r = spec['$ref'] -%}
410
+ {%- set _k = _r[8:] if _r.startswith('#/$defs/') else (_r[14:] if _r.startswith('#/definitions/') else none) -%}
411
+ {%- if _k is not none and ('|' + _k + '|') not in REFS.seen and REFS.defs[_k] is mapping -%}
412
+ {%- set spec = dict((REFS.defs[_k] | items | list) + (spec | items | rejectattr('0', 'equalto', '$ref') | list)) -%}
413
+ {%- set REFS.seen = REFS.seen + _k + '|' -%}
414
+ {%- if spec['$ref'] is string -%}
415
+ {%- set _r2 = spec['$ref'] -%}
416
+ {%- set _k2 = _r2[8:] if _r2.startswith('#/$defs/') else (_r2[14:] if _r2.startswith('#/definitions/') else none) -%}
417
+ {%- if _k2 is not none and REFS.defs[_k2] is mapping -%}
418
+ {%- set spec = dict((REFS.defs[_k2] | items | list) + (spec | items | rejectattr('0', 'equalto', '$ref') | list)) -%}
419
+ {%- set REFS.seen = REFS.seen + _k2 + '|' -%}
420
+ {%- endif -%}
421
+ {%- endif -%}
422
+ {%- endif -%}
423
+ {%- endif -%}
424
+ {{- "<param name=" + name + " type=" + render_compact_type(spec) }}
425
+ {%- if name in (required_list or []) -%}{{- " required=true" }}{%- endif -%}
426
+ {%- if spec.enum -%}{{- " enum=" }}{{ render_xml_enum(spec.enum) }}{%- endif -%}
427
+ {%- if spec.default is defined -%}{{ render_xml_default_attr(spec.default) }}{%- endif -%}
428
+ {{- render_xml_schema_attrs(spec, false) }}
429
+ {%- if spec.description or xml_schema_has_children(spec, true, false) == 'true' -%}
430
+ {{- ">" }}
431
+ {%- if spec.description -%}{{ spec.description }}{%- endif -%}
432
+ {{- render_xml_schema_children(spec, true, false) }}
433
+ {{- "</param>" }}
434
+ {%- else -%}
435
+ {{- "/>" }}
436
+ {%- endif -%}
437
+ {%- endmacro -%}
438
+
439
+ {%- macro render_tools_xml(tools_list) -%}
440
+ {{- "<ifm|tools>" }}
441
+ {%- for tool in tools_list -%}
442
+ {%- set fn = tool.function if tool.function is defined else tool -%}
443
+ {%- set REFS.defs = fn.parameters['$defs'] if (fn.parameters is mapping and fn.parameters['$defs'] is mapping) else (fn.parameters['definitions'] if (fn.parameters is mapping and fn.parameters['definitions'] is mapping) else {}) -%}
444
+ {%- set REFS.seen = '|' -%}
445
+ {%- set fnp = namespace(p=fn.parameters) -%}
446
+ {%- if fnp.p is mapping and fnp.p['$ref'] is string -%}
447
+ {%- set _r = fnp.p['$ref'] -%}
448
+ {%- set _k = _r[8:] if _r.startswith('#/$defs/') else (_r[14:] if _r.startswith('#/definitions/') else none) -%}
449
+ {%- if _k is not none and REFS.defs[_k] is mapping -%}
450
+ {%- set fnp.p = dict((REFS.defs[_k] | items | list) + (fnp.p | items | rejectattr('0', 'equalto', '$ref') | list)) -%}
451
+ {%- set REFS.seen = REFS.seen + _k + '|' -%}
452
+ {%- endif -%}
453
+ {%- endif -%}
454
+ {{- "\n<function name=" + fn.name + ">" }}
455
+ {%- if fn.description -%}
456
+ {{- "<description>" }}{{ fn.description }}{{- "</description>" }}
457
+ {%- endif -%}
458
+ {{- "<parameters>" }}
459
+ {%- if fnp.p and fnp.p.properties -%}
460
+ {%- for pname, pspec in fnp.p.properties | items -%}
461
+ {{- render_xml_param(pname, pspec, fnp.p.required or []) }}
462
+ {%- endfor -%}
463
+ {%- elif fnp.p is mapping and (fnp.p.oneOf or fnp.p.anyOf or 'items' in fnp.p) -%}
464
+ {{- render_xml_schema_children(fnp.p, true, false) }}
465
+ {%- endif -%}
466
+ {{- "</parameters>" }}
467
+ {%- set fn_ret = fn.returns if fn.returns is defined else fn.response -%}
468
+ {%- if fn_ret is mapping -%}{{ render_xml_schema_node("returns", fn_ret, true) }}{%- elif fn_ret is defined -%}<returns>{{ render_xml_value(fn_ret) }}</returns>{%- endif -%}
469
+ {{- "</function>" }}
470
+ {%- endfor -%}
471
+ {{- "\n</ifm|tools>" }}
472
+ {%- endmacro -%}
473
+
474
+ {%- macro render_markdown_literal(value) -%}
475
+ {%- if value is string and value == "" -%}""
476
+ {%- elif value is string -%}`{{ value | replace("\n", "\\n") }}`
477
+ {%- else -%}`{{ render_python_repr(value) }}`
478
+ {%- endif -%}
479
+ {%- endmacro -%}
480
+
481
+ {%- macro render_allowed_values(values) -%}
482
+ {%- for value in values -%}{{ render_markdown_literal(value) }}{% if not loop.last %}, {% endif %}{%- endfor -%}
483
+ {%- endmacro -%}
484
+
485
+ {%- macro render_markdown_value(value) -%}
486
+ {%- if value is string and value == "" -%}""{%- elif value is string -%}{{ value }}{%- else -%}{{ render_python_repr(value) }}{%- endif -%}
487
+ {%- endmacro -%}
488
+
489
+ {%- macro render_markdown_detail(indent, label, value) -%}
490
+ {{- "\n" + indent + " - " + label + ": " }}{{ render_markdown_value(value) }}
491
+ {%- endmacro -%}
492
+
493
+ {%- macro render_markdown_metadata_detail(label, value) -%}
494
+ {{- "\n- " + label + ": " }}{{ render_markdown_value(value) }}
495
+ {%- endmacro -%}
496
+
497
+ {%- macro render_markdown_schema_annotations(spec, indent, include_value_details) -%}
498
+ {%- if include_value_details and spec.description is defined -%}{{ render_markdown_detail(indent, "Description", spec.description | replace("\n", "\n" + indent + " ")) }}{%- endif -%}
499
+ {%- if include_value_details and spec.enum is defined -%}{{- "\n" + indent + " - Allowed values: " }}{{ render_allowed_values(spec.enum) }}{%- endif -%}
500
+ {%- if include_value_details and spec.default is defined -%}{{- "\n" + indent + " - Default: " }}{{ render_markdown_literal(spec.default) }}{%- endif -%}
501
+ {%- if spec.additionalProperties is defined -%}
502
+ {%- if spec.additionalProperties is mapping -%}
503
+ {{- "\n" + indent + " - Additional properties *(" + render_markdown_type(spec.additionalProperties) + ")*" }}
504
+ {{- render_markdown_schema_details(spec.additionalProperties, indent + " ", true) }}
505
+ {%- else -%}
506
+ {{ render_markdown_detail(indent, "Additional properties", spec.additionalProperties) }}
507
+ {%- endif -%}
508
+ {%- endif -%}
509
+ {%- endmacro -%}
510
+
511
+ {%- macro render_markdown_metadata_annotations(spec) -%}
512
+ {%- if spec.description is defined -%}{{ render_markdown_metadata_detail("Description", spec.description | replace("\n", "\n ")) }}{%- endif -%}
513
+ {%- if spec.enum is defined -%}{{- "\n- Allowed values: " }}{{ render_allowed_values(spec.enum) }}{%- endif -%}
514
+ {%- if spec.default is defined -%}{{- "\n- Default: " }}{{ render_markdown_literal(spec.default) }}{%- endif -%}
515
+ {%- if spec.additionalProperties is defined -%}
516
+ {%- if spec.additionalProperties is mapping -%}
517
+ {{- "\n- Additional properties *(" + render_markdown_type(spec.additionalProperties) + ")*" }}
518
+ {{- render_markdown_schema_details(spec.additionalProperties, "", true) }}
519
+ {%- else -%}
520
+ {{ render_markdown_metadata_detail("Additional properties", spec.additionalProperties) }}
521
+ {%- endif -%}
522
+ {%- endif -%}
523
+ {%- endmacro -%}
524
+
525
+ {%- macro render_markdown_schema_extras(spec, indent) -%}
526
+ {%- set rendered_keys = ["type", "description", "enum", "default", "properties", "required", "items", "oneOf", "anyOf", "additionalProperties", "patternProperties", "returns"] -%}
527
+ {%- for key, value in spec | items -%}
528
+ {%- if key not in rendered_keys -%}
529
+ {{- "\n" + indent + " - " + key + ": " }}{{ render_markdown_value(value) }}
530
+ {%- endif -%}
531
+ {%- endfor -%}
532
+ {%- endmacro -%}
533
+
534
+ {%- macro render_markdown_metadata_extras(spec) -%}
535
+ {%- set rendered_keys = ["type", "description", "enum", "default", "properties", "required", "items", "oneOf", "anyOf", "additionalProperties", "patternProperties", "returns"] -%}
536
+ {%- for key, value in spec | items -%}
537
+ {%- if key not in rendered_keys -%}
538
+ {{- "\n- " + key + ": " }}{{ render_markdown_value(value) }}
539
+ {%- endif -%}
540
+ {%- endfor -%}
541
+ {%- endmacro -%}
542
+
543
+ {%- macro markdown_schema_has_extra(spec) -%}
544
+ {%- set rendered_keys = ["type", "description", "enum", "default", "properties", "required", "items", "oneOf", "anyOf", "additionalProperties", "patternProperties", "returns"] -%}
545
+ {%- set found = namespace(value='false') -%}
546
+ {%- for key, value in spec | items -%}
547
+ {%- if key not in rendered_keys -%}{%- set found.value = 'true' -%}{%- endif -%}
548
+ {%- endfor -%}
549
+ {{- found.value -}}
550
+ {%- endmacro -%}
551
+
552
+ {%- macro markdown_parameter_schema_has_details(spec) -%}
553
+ {%- if spec.description is defined or spec.enum is defined or spec.default is defined or spec.additionalProperties is defined or spec.patternProperties is defined or 'items' in spec or spec.oneOf or spec.anyOf or spec.returns is defined or markdown_schema_has_extra(spec) == 'true' -%}
554
+ true
555
+ {%- else -%}
556
+ false
557
+ {%- endif -%}
558
+ {%- endmacro -%}
559
+
560
+ {%- macro render_markdown_schema_structure(spec, indent, include_properties) -%}
561
+ {%- if include_properties and spec.properties -%}
562
+ {%- for child_name, child_spec in spec.properties | items -%}
563
+ {{- render_markdown_param(child_name, child_spec, spec.required or [], indent + " ") }}
564
+ {%- endfor -%}
565
+ {%- endif -%}
566
+ {%- if 'items' in spec and spec['items'] is mapping -%}
567
+ {{- "\n" + indent + " - Items *(" + render_markdown_type(spec['items']) + ")*" }}
568
+ {{- render_markdown_schema_details(spec['items'], indent + " ", true) }}
569
+ {%- elif 'items' in spec -%}
570
+ {{ render_markdown_detail(indent, "Items", spec['items']) }}
571
+ {%- endif -%}
572
+ {%- if spec.oneOf -%}
573
+ {{- "\n" + indent + " - oneOf:" }}
574
+ {%- for variant in spec.oneOf -%}
575
+ {{- "\n" + indent + " - Variant " }}{{ loop.index }}{{- " *(" + render_markdown_type(variant) + ")*" }}
576
+ {{- render_markdown_schema_details(variant, indent + " ", true) }}
577
+ {%- endfor -%}
578
+ {%- endif -%}
579
+ {%- if spec.anyOf -%}
580
+ {{- "\n" + indent + " - anyOf:" }}
581
+ {%- for variant in spec.anyOf -%}
582
+ {{- "\n" + indent + " - Variant " }}{{ loop.index }}{{- " *(" + render_markdown_type(variant) + ")*" }}
583
+ {{- render_markdown_schema_details(variant, indent + " ", true) }}
584
+ {%- endfor -%}
585
+ {%- endif -%}
586
+ {%- if spec.patternProperties is mapping -%}
587
+ {{- "\n" + indent + " - Pattern properties:" }}
588
+ {%- for pattern, pattern_spec in spec.patternProperties | items -%}
589
+ {%- if pattern_spec is mapping -%}
590
+ {{- "\n" + indent + " - `" + pattern + "` *(" + render_markdown_type(pattern_spec) + ")*" }}
591
+ {{- render_markdown_schema_details(pattern_spec, indent + " ", true) }}
592
+ {%- else -%}
593
+ {{- "\n" + indent + " - `" + pattern + "`: " }}{{ render_markdown_value(pattern_spec) }}
594
+ {%- endif -%}
595
+ {%- endfor -%}
596
+ {%- elif spec.patternProperties is defined -%}
597
+ {{ render_markdown_detail(indent, "Pattern properties", spec.patternProperties) }}
598
+ {%- endif -%}
599
+ {%- if spec.returns is mapping -%}
600
+ {{- "\n" + indent + " - Returns *(" + render_markdown_type(spec.returns) + ")*" }}
601
+ {{- render_markdown_schema_details(spec.returns, indent + " ", true) }}
602
+ {%- elif spec.returns is defined -%}
603
+ {{ render_markdown_detail(indent, "Returns", spec.returns) }}
604
+ {%- endif -%}
605
+ {%- endmacro -%}
606
+
607
+ {%- macro render_markdown_schema_details(spec, indent, include_value_details) -%}
608
+ {%- if spec is mapping and spec['$ref'] is string -%}
609
+ {%- set _r = spec['$ref'] -%}
610
+ {%- set _k = _r[8:] if _r.startswith('#/$defs/') else (_r[14:] if _r.startswith('#/definitions/') else none) -%}
611
+ {%- if _k is not none and ('|' + _k + '|') not in REFS.seen and REFS.defs[_k] is mapping -%}
612
+ {%- set spec = dict((REFS.defs[_k] | items | list) + (spec | items | rejectattr('0', 'equalto', '$ref') | list)) -%}
613
+ {%- set REFS.seen = REFS.seen + _k + '|' -%}
614
+ {%- if spec['$ref'] is string -%}
615
+ {%- set _r2 = spec['$ref'] -%}
616
+ {%- set _k2 = _r2[8:] if _r2.startswith('#/$defs/') else (_r2[14:] if _r2.startswith('#/definitions/') else none) -%}
617
+ {%- if _k2 is not none and REFS.defs[_k2] is mapping -%}
618
+ {%- set spec = dict((REFS.defs[_k2] | items | list) + (spec | items | rejectattr('0', 'equalto', '$ref') | list)) -%}
619
+ {%- set REFS.seen = REFS.seen + _k2 + '|' -%}
620
+ {%- endif -%}
621
+ {%- endif -%}
622
+ {%- endif -%}
623
+ {%- endif -%}
624
+ {%- if spec is mapping -%}
625
+ {{- render_markdown_schema_annotations(spec, indent, include_value_details) }}
626
+ {{- render_markdown_schema_structure(spec, indent, true) }}
627
+ {{- render_markdown_schema_extras(spec, indent) }}
628
+ {%- elif spec is not sameas true and spec is not sameas false -%}
629
+ {{- "\n" + indent + " - Value: " }}{{ render_markdown_literal(spec) }}
630
+ {%- endif -%}
631
+ {%- endmacro -%}
632
+
633
+ {%- macro render_markdown_parameter_schema(spec) -%}
634
+ {%- if spec is mapping and spec['$ref'] is string -%}
635
+ {%- set _r = spec['$ref'] -%}
636
+ {%- set _k = _r[8:] if _r.startswith('#/$defs/') else (_r[14:] if _r.startswith('#/definitions/') else none) -%}
637
+ {%- if _k is not none and ('|' + _k + '|') not in REFS.seen and REFS.defs[_k] is mapping -%}
638
+ {%- set spec = dict((REFS.defs[_k] | items | list) + (spec | items | rejectattr('0', 'equalto', '$ref') | list)) -%}
639
+ {%- set REFS.seen = REFS.seen + _k + '|' -%}
640
+ {%- if spec['$ref'] is string -%}
641
+ {%- set _r2 = spec['$ref'] -%}
642
+ {%- set _k2 = _r2[8:] if _r2.startswith('#/$defs/') else (_r2[14:] if _r2.startswith('#/definitions/') else none) -%}
643
+ {%- if _k2 is not none and REFS.defs[_k2] is mapping -%}
644
+ {%- set spec = dict((REFS.defs[_k2] | items | list) + (spec | items | rejectattr('0', 'equalto', '$ref') | list)) -%}
645
+ {%- set REFS.seen = REFS.seen + _k2 + '|' -%}
646
+ {%- endif -%}
647
+ {%- endif -%}
648
+ {%- endif -%}
649
+ {%- endif -%}
650
+ {%- if spec is mapping -%}
651
+ {{- render_markdown_metadata_annotations(spec) }}
652
+ {%- if 'items' in spec and spec['items'] is mapping -%}
653
+ {{- "\n- Items *(" + render_markdown_type(spec['items']) + ")*" }}
654
+ {{- render_markdown_schema_details(spec['items'], "", true) }}
655
+ {%- elif 'items' in spec -%}
656
+ {{ render_markdown_metadata_detail("Items", spec['items']) }}
657
+ {%- endif -%}
658
+ {%- if spec.oneOf -%}
659
+ {{- "\n- oneOf:" }}
660
+ {%- for variant in spec.oneOf -%}
661
+ {{- "\n - Variant " }}{{ loop.index }}{{- " *(" + render_markdown_type(variant) + ")*" }}
662
+ {{- render_markdown_schema_details(variant, " ", true) }}
663
+ {%- endfor -%}
664
+ {%- endif -%}
665
+ {%- if spec.anyOf -%}
666
+ {{- "\n- anyOf:" }}
667
+ {%- for variant in spec.anyOf -%}
668
+ {{- "\n - Variant " }}{{ loop.index }}{{- " *(" + render_markdown_type(variant) + ")*" }}
669
+ {{- render_markdown_schema_details(variant, " ", true) }}
670
+ {%- endfor -%}
671
+ {%- endif -%}
672
+ {%- if spec.patternProperties is mapping -%}
673
+ {{- "\n- Pattern properties:" }}
674
+ {%- for pattern, pattern_spec in spec.patternProperties | items -%}
675
+ {%- if pattern_spec is mapping -%}
676
+ {{- "\n - `" + pattern + "` *(" + render_markdown_type(pattern_spec) + ")*" }}
677
+ {{- render_markdown_schema_details(pattern_spec, " ", true) }}
678
+ {%- else -%}
679
+ {{- "\n - `" + pattern + "`: " }}{{ render_markdown_value(pattern_spec) }}
680
+ {%- endif -%}
681
+ {%- endfor -%}
682
+ {%- elif spec.patternProperties is defined -%}
683
+ {{ render_markdown_metadata_detail("Pattern properties", spec.patternProperties) }}
684
+ {%- endif -%}
685
+ {%- if spec.returns is mapping -%}
686
+ {{- "\n- Returns *(" + render_markdown_type(spec.returns) + ")*" }}
687
+ {{- render_markdown_schema_details(spec.returns, "", true) }}
688
+ {%- elif spec.returns is defined -%}
689
+ {{ render_markdown_metadata_detail("Returns", spec.returns) }}
690
+ {%- endif -%}
691
+ {{- render_markdown_metadata_extras(spec) }}
692
+ {%- endif -%}
693
+ {%- endmacro -%}
694
+
695
+ {%- macro render_markdown_param(name, spec, required_list, indent) -%}
696
+ {%- if spec is mapping and spec['$ref'] is string -%}
697
+ {%- set _r = spec['$ref'] -%}
698
+ {%- set _k = _r[8:] if _r.startswith('#/$defs/') else (_r[14:] if _r.startswith('#/definitions/') else none) -%}
699
+ {%- if _k is not none and ('|' + _k + '|') not in REFS.seen and REFS.defs[_k] is mapping -%}
700
+ {%- set spec = dict((REFS.defs[_k] | items | list) + (spec | items | rejectattr('0', 'equalto', '$ref') | list)) -%}
701
+ {%- set REFS.seen = REFS.seen + _k + '|' -%}
702
+ {%- if spec['$ref'] is string -%}
703
+ {%- set _r2 = spec['$ref'] -%}
704
+ {%- set _k2 = _r2[8:] if _r2.startswith('#/$defs/') else (_r2[14:] if _r2.startswith('#/definitions/') else none) -%}
705
+ {%- if _k2 is not none and REFS.defs[_k2] is mapping -%}
706
+ {%- set spec = dict((REFS.defs[_k2] | items | list) + (spec | items | rejectattr('0', 'equalto', '$ref') | list)) -%}
707
+ {%- set REFS.seen = REFS.seen + _k2 + '|' -%}
708
+ {%- endif -%}
709
+ {%- endif -%}
710
+ {%- endif -%}
711
+ {%- endif -%}
712
+ {{- "\n" + indent + "- `" + name + "` *(" + render_markdown_type(spec) }}
713
+ {%- if name in (required_list or []) -%}{{- ", required" }}{%- endif -%}
714
+ {{- ")*" }}
715
+ {%- if spec.description -%}{{- " - " + spec.description | replace("\n", "\n" + indent + " ") }}{%- endif -%}
716
+ {%- if spec.enum -%}
717
+ {{- "\n" + indent + " - Allowed values: " }}{{ render_allowed_values(spec.enum) }}
718
+ {%- endif -%}
719
+ {%- if spec.default is defined -%}
720
+ {{- "\n" + indent + " - Default: " }}{{ render_markdown_literal(spec.default) }}
721
+ {%- endif -%}
722
+ {{- render_markdown_schema_details(spec, indent, false) }}
723
+ {%- endmacro -%}
724
+
725
+ {%- macro render_tools_markdown(tools_list) -%}
726
+ {{- "<ifm|tools>" }}
727
+ {%- for tool in tools_list -%}
728
+ {%- set fn = tool.function if tool.function is defined else tool -%}
729
+ {%- set REFS.defs = fn.parameters['$defs'] if (fn.parameters is mapping and fn.parameters['$defs'] is mapping) else (fn.parameters['definitions'] if (fn.parameters is mapping and fn.parameters['definitions'] is mapping) else {}) -%}
730
+ {%- set REFS.seen = '|' -%}
731
+ {%- set fnp = namespace(p=fn.parameters) -%}
732
+ {%- if fnp.p is mapping and fnp.p['$ref'] is string -%}
733
+ {%- set _r = fnp.p['$ref'] -%}
734
+ {%- set _k = _r[8:] if _r.startswith('#/$defs/') else (_r[14:] if _r.startswith('#/definitions/') else none) -%}
735
+ {%- if _k is not none and REFS.defs[_k] is mapping -%}
736
+ {%- set fnp.p = dict((REFS.defs[_k] | items | list) + (fnp.p | items | rejectattr('0', 'equalto', '$ref') | list)) -%}
737
+ {%- set REFS.seen = REFS.seen + _k + '|' -%}
738
+ {%- endif -%}
739
+ {%- endif -%}
740
+ {{- "\n## " + fn.name }}
741
+ {%- if fn.description -%}
742
+ {{- "\n" + fn.description }}
743
+ {%- endif -%}
744
+ {{- "\n\n**Parameters**" }}
745
+ {%- if fnp.p and fnp.p.properties -%}
746
+ {%- for pname, pspec in fnp.p.properties | items -%}
747
+ {{- render_markdown_param(pname, pspec, fnp.p.required or [], "") }}
748
+ {%- endfor -%}
749
+ {%- elif fnp.p is mapping and (fnp.p.oneOf or fnp.p.anyOf or 'items' in fnp.p) -%}
750
+ {{- render_markdown_parameter_schema(fnp.p) }}
751
+ {%- else -%}
752
+ {{- "\n- None" }}
753
+ {%- endif -%}
754
+ {%- set fn_ret = fn.returns if fn.returns is defined else fn.response -%}
755
+ {%- if fn_ret is mapping -%}
756
+ {{- "\n\n**Returns**" }}
757
+ {{- "\n- Return *(" + render_markdown_type(fn_ret) + ")*" }}
758
+ {{- render_markdown_schema_details(fn_ret, "", true) }}
759
+ {%- elif fn_ret is defined -%}
760
+ {{- "\n\n**Returns**\n- " }}{{ render_markdown_value(fn_ret) }}
761
+ {%- endif -%}
762
+ {%- if not loop.last -%}{{- "\n" }}{%- endif -%}
763
+ {%- endfor -%}
764
+ {{- "\n</ifm|tools>" }}
765
+ {%- endmacro -%}
766
+
767
+ {%- macro render_tool_presentation(tools_list, fmt) -%}
768
+ {%- if fmt == 'json' -%}
769
+ {{- render_tools_json(tools_list) }}
770
+ {%- elif RB.bad != '|' -%}
771
+ {#- some tool uses constructs the pretty renderers cannot represent (verdicts -#}
772
+ {#- computed during validate_tools): render the WHOLE toolset exactly as the -#}
773
+ {#- json presentation would, so the block stays uniform and model-familiar. -#}
774
+ {{- render_tools_json(tools_list) }}
775
+ {%- elif fmt == 'xml' -%}
776
+ {{- render_tools_xml(tools_list) }}
777
+ {%- elif fmt == 'markdown' -%}
778
+ {{- render_tools_markdown(tools_list) }}
779
+ {%- else -%}
780
+ {{- raise_exception("Unsupported tool_presentation_format: '" + fmt + "'. Supported formats: json, xml, markdown.") }}
781
+ {%- endif -%}
782
+ {%- endmacro -%}
783
+
784
+ {%- macro render_call_instructions(fmt) -%}
785
+ {%- if fmt == 'json' -%}
786
+ {{- "Wrap all tool calls in a single <ifm|tool_calls></ifm|tool_calls> block. For each call, emit one JSON object with the function name and arguments on the same line inside <ifm|tool_call></ifm|tool_call> tags:\n\n<ifm|tool_calls>\n<ifm|tool_call>{\"name\": <function-name>, \"arguments\": <args-json-object>}</ifm|tool_call>\n</ifm|tool_calls>" }}
787
+ {%- elif fmt == 'xml' -%}
788
+ {{- "Wrap all tool calls in a single <ifm|tool_calls></ifm|tool_calls> block. For each call, write the function name at the start of <ifm|tool_call>, followed by paired <ifm|arg_key> and <ifm|arg_value> tags for each argument:\n\n<ifm|tool_calls>\n<ifm|tool_call>$FUNCTION_NAME\n<ifm|arg_key>$PARAMETER_NAME</ifm|arg_key>\n<ifm|arg_value>$PARAMETER_VALUE</ifm|arg_value>\n...\n</ifm|tool_call>\n</ifm|tool_calls>\n\nString and scalar parameters should be written as plain text. Array and object parameters should be written as JSON literals." }}
789
+ {%- elif fmt == 'xml_typed' -%}
790
+ {{- "Wrap all tool calls in a single <ifm|tool_calls></ifm|tool_calls> block. For each call, write the function name at the start of <ifm|tool_call>, followed by <ifm|arg_key>, <ifm|arg_type>, and <ifm|arg_value> tags for each argument:\n\n<ifm|tool_calls>\n<ifm|tool_call>$FUNCTION_NAME\n<ifm|arg_key>$PARAMETER_NAME</ifm|arg_key>\n<ifm|arg_type>$ARGUMENT_TYPE</ifm|arg_type>\n<ifm|arg_value>$PARAMETER_VALUE</ifm|arg_value>\n...\n</ifm|tool_call>\n</ifm|tool_calls>\n\nUse the parameter type shown in the tool definition. If that type contains anyOf or oneOf, use the actual argument value type instead. String and scalar parameters should be written as plain text. Array and object parameters should be written as JSON literals." }}
791
+ {%- else -%}
792
+ {{- raise_exception("Unsupported tool_call_format: '" + fmt + "'. Supported formats: json, xml, xml_typed.") }}
793
+ {%- endif -%}
794
+ {%- endmacro -%}
795
+
796
+ {%- macro render_system_with_tools(tools_list, system_content, presentation_fmt, call_fmt) -%}
797
+ {{- "<|ifm|im_start|>system\n# Tools\nYou may call one or more tools to assist with the user query.\n\nAvailable tools are:\n\n" }}
798
+ {{- render_tool_presentation(tools_list, presentation_fmt) }}
799
+ {{- "\n\nWhen calling tools, you MUST follow the tool-call format below:\n\n" }}
800
+ {{- render_call_instructions(call_fmt) }}
801
+ {%- if system_content -%}
802
+ {{- "\n\n" + system_content }}
803
+ {%- endif -%}
804
+ {{- "<|ifm|im_end|>" }}
805
+ {%- endmacro -%}
806
+
807
+ {%- macro render_argument_value(value) -%}
808
+ {%- if value is string -%}{{- value -}}{%- else -%}{{- value | tojson -}}{%- endif -%}
809
+ {%- endmacro -%}
810
+
811
+ {%- macro render_value_type(value) -%}
812
+ {%- if value is none -%}null
813
+ {%- elif value is boolean -%}boolean
814
+ {%- elif value is integer -%}integer
815
+ {%- elif value is number -%}number
816
+ {%- elif value is string -%}string
817
+ {%- elif value is mapping -%}object
818
+ {%- elif value is sequence -%}array
819
+ {%- else -%}any
820
+ {%- endif -%}
821
+ {%- endmacro -%}
822
+
823
+ {%- macro schema_has_combinator(spec) -%}
824
+ {%- if spec.oneOf or spec.anyOf -%}
825
+ true
826
+ {%- elif spec.type is defined and spec.type is sequence and spec.type is not string and spec.type | length > 1 -%}
827
+ true
828
+ {%- elif spec.type == "array" and 'items' in spec -%}
829
+ {{- schema_has_combinator(spec['items']) -}}
830
+ {%- elif spec.properties -%}
831
+ {%- set found = namespace(value='false') -%}
832
+ {%- for child_name, child_spec in spec.properties | items -%}
833
+ {%- if schema_has_combinator(child_spec) == 'true' -%}
834
+ {%- set found.value = 'true' -%}
835
+ {%- endif -%}
836
+ {%- endfor -%}
837
+ {{- found.value -}}
838
+ {%- else -%}
839
+ false
840
+ {%- endif -%}
841
+ {%- endmacro -%}
842
+
843
+ {%- macro render_arg_type(tools_list, tool_name, arg_name, value) -%}
844
+ {%- set found = namespace(type='any') -%}
845
+ {%- for tool in tools_list -%}
846
+ {%- set fn = tool.function if tool.function is defined else tool -%}
847
+ {%- if fn.name == tool_name and fn.parameters and fn.parameters.properties and arg_name in fn.parameters.properties -%}
848
+ {%- set spec = fn.parameters.properties[arg_name] -%}
849
+ {%- if spec is mapping and spec['$ref'] is string -%}
850
+ {%- set _r = spec['$ref'] -%}
851
+ {%- set _k = _r[8:] if _r.startswith('#/$defs/') else (_r[14:] if _r.startswith('#/definitions/') else none) -%}
852
+ {%- set _d = fn.parameters['$defs'] if fn.parameters['$defs'] is mapping else fn.parameters['definitions'] -%}
853
+ {%- set spec = dict((_d[_k] | items | list) + (spec | items | rejectattr('0', 'equalto', '$ref') | list)) if (_k is not none and _d is mapping and _d[_k] is mapping) else spec -%}
854
+ {%- endif -%}
855
+ {%- if schema_has_combinator(spec) == 'true' -%}
856
+ {%- set found.type = render_value_type(value) -%}
857
+ {%- else -%}
858
+ {%- set found.type = render_compact_type(spec) -%}
859
+ {%- endif -%}
860
+ {%- endif -%}
861
+ {%- endfor -%}
862
+ {{- found.type -}}
863
+ {%- endmacro -%}
864
+
865
+ {%- macro render_tool_calls_block(tool_calls, fmt, tools_list) -%}
866
+ {{- "<ifm|tool_calls>" }}
867
+ {%- for raw_tool_call in tool_calls -%}
868
+ {%- set tool_call = raw_tool_call.function if raw_tool_call.function else raw_tool_call -%}
869
+ {%- if tool_call.arguments is string -%}
870
+ {{- raise_exception("tool_call.arguments must be a dict, not a JSON string. Parse it before passing to the template.") -}}
871
+ {%- endif -%}
872
+ {%- if fmt == 'json' -%}
873
+ {{- "\n<ifm|tool_call>{\"name\": \"" + tool_call.name + "\", \"arguments\": " }}{{ tool_call.arguments | tojson }}{{- "}</ifm|tool_call>" }}
874
+ {%- elif fmt == 'xml' or fmt == 'xml_typed' -%}
875
+ {{- "\n<ifm|tool_call>" + tool_call.name + "\n" }}
876
+ {%- for key, value in tool_call.arguments | items -%}
877
+ {{- "<ifm|arg_key>" + key + "</ifm|arg_key>\n" }}
878
+ {%- if fmt == 'xml_typed' -%}
879
+ {{- "<ifm|arg_type>" + render_arg_type(tools_list, tool_call.name, key, value) + "</ifm|arg_type>\n" }}
880
+ {%- endif -%}
881
+ {{- "<ifm|arg_value>" }}{{ render_argument_value(value) }}{{- "</ifm|arg_value>\n" }}
882
+ {%- endfor -%}
883
+ {{- "</ifm|tool_call>" }}
884
+ {%- else -%}
885
+ {{- raise_exception("Unsupported tool_call_format: '" + fmt + "'. Supported formats: json, xml, xml_typed.") -}}
886
+ {%- endif -%}
887
+ {%- endfor -%}
888
+ {{- "\n</ifm|tool_calls>" }}
889
+ {%- endmacro -%}
890
+
891
+ {%- macro render_tool_response_messages(raw_content) -%}
892
+ {%- if raw_content is string -%}
893
+ {{- '<|ifm|im_start|>tool\n' + raw_content + '<|ifm|im_end|>' }}
894
+ {%- elif raw_content is sequence and raw_content is not string and raw_content is not mapping -%}
895
+ {%- if raw_content | length == 0 -%}
896
+ {{- raise_exception("tool message content list must not be empty.") -}}
897
+ {%- endif -%}
898
+ {{- '<|ifm|im_start|>tool\n' -}}
899
+ {%- for item in raw_content -%}
900
+ {%- if not loop.first -%}{{- '\n' -}}{%- endif -%}
901
+ {%- if item is string -%}
902
+ {{- item -}}
903
+ {%- elif item is mapping and item.text is string -%}
904
+ {{- item.text -}}
905
+ {%- else -%}
906
+ {{- (item | tojson) -}}
907
+ {%- endif -%}
908
+ {%- endfor -%}
909
+ {{- '<|ifm|im_end|>' -}}
910
+ {%- else -%}
911
+ {{- '<|ifm|im_start|>tool\n' }}{{ raw_content | tojson }}{{- '<|ifm|im_end|>' }}
912
+ {%- endif -%}
913
+ {%- endmacro -%}
914
+
915
+ {%- set available_tools = tools if tools else [] -%}
916
+ {%- if (not available_tools) and messages[0].role == 'system' and messages[0].get('tools') -%}
917
+ {%- set available_tools = messages[0]['tools'] -%}
918
+ {%- endif -%}
919
+ {%- if available_tools -%}
920
+ {{- validate_tools(available_tools, tool_presentation_fmt != 'json') }}
921
+ {%- set system_content = '' -%}
922
+ {%- if messages[0].role == 'system' and messages[0].content -%}
923
+ {%- set system_content = messages[0].content -%}
924
+ {%- endif -%}
925
+ {{- render_system_with_tools(available_tools, system_content, tool_presentation_fmt, tool_call_fmt) }}
926
+ {%- else -%}
927
+ {%- if messages[0].role == 'system' -%}
928
+ {{- '<|ifm|im_start|>system\n' + messages[0].content + '<|ifm|im_end|>' }}
929
+ {%- endif -%}
930
+ {%- endif -%}
931
+
932
+ {%- for message in messages -%}
933
+ {%- if message.content is string -%}
934
+ {%- set content = message.content -%}
935
+ {%- else -%}
936
+ {%- set content = '' -%}
937
+ {%- endif -%}
938
+ {%- if (message.role == "user") or (message.role == "system" and not loop.first) -%}
939
+ {{- '<|ifm|im_start|>' + message.role + '\n' + content + '<|ifm|im_end|>' }}
940
+ {%- elif message.role == "assistant" -%}
941
+ {%- set thinking_content = '' -%}
942
+ {%- set think_tag = 'ifm|think' -%}
943
+ {%- if message.think is defined and message.think is string -%}
944
+ {%- set thinking_content = message.think -%}
945
+ {%- set think_tag = 'ifm|think' -%}
946
+ {%- elif message.think_fast is defined and message.think_fast is string -%}
947
+ {%- set thinking_content = message.think_fast -%}
948
+ {%- set think_tag = 'ifm|think_fast' -%}
949
+ {%- elif message.think_faster is defined and message.think_faster is string -%}
950
+ {%- set thinking_content = message.think_faster -%}
951
+ {%- set think_tag = 'ifm|think_faster' -%}
952
+ {%- elif message.reasoning_content is defined and message.reasoning_content is string -%}
953
+ {%- set thinking_content = message.reasoning_content -%}
954
+ {%- set think_tag = 'ifm|think' -%}
955
+ {%- elif message.reasoning is defined and message.reasoning is string -%}
956
+ {%- set thinking_content = message.reasoning -%}
957
+ {%- set think_tag = 'ifm|think' -%}
958
+ {%- elif message.think is not defined and message.reasoning is not defined and message.reasoning_content is not defined and message.think_fast is not defined and message.think_faster is not defined -%}
959
+ {{- raise_exception("Assistant message is missing a thinking field. Provide one of: think, reasoning, reasoning_content, think_fast, think_faster.") -}}
960
+ {%- else -%}
961
+ {%- if '</ifm|think>' in content -%}
962
+ {%- set thinking_content = content.split('</ifm|think>')[0].rstrip('\n').split('<ifm|think>')[-1].lstrip('\n') -%}
963
+ {%- set content = content.split('</ifm|think>')[-1].lstrip('\n') -%}
964
+ {%- set think_tag = 'ifm|think' -%}
965
+ {%- elif '</ifm|think_fast>' in content -%}
966
+ {%- set thinking_content = content.split('</ifm|think_fast>')[0].rstrip('\n').split('<ifm|think_fast>')[-1].lstrip('\n') -%}
967
+ {%- set content = content.split('</ifm|think_fast>')[-1].lstrip('\n') -%}
968
+ {%- set think_tag = 'ifm|think_fast' -%}
969
+ {%- elif '</ifm|think_faster>' in content -%}
970
+ {%- set thinking_content = content.split('</ifm|think_faster>')[0].rstrip('\n').split('<ifm|think_faster>')[-1].lstrip('\n') -%}
971
+ {%- set content = content.split('</ifm|think_faster>')[-1].lstrip('\n') -%}
972
+ {%- set think_tag = 'ifm|think_faster' -%}
973
+ {%- endif -%}
974
+ {%- endif -%}
975
+ {{- '<|ifm|im_start|>' + message.role }}
976
+ {% generation %}
977
+ {%- if think_tag -%}
978
+ {%- if thinking_content -%}
979
+ {{- '<' + think_tag + '>\n' + thinking_content + '\n</' + think_tag + '>\n' + content.lstrip('\n') }}
980
+ {%- else -%}
981
+ {{- '<' + think_tag + '>\n</' + think_tag + '>\n' + content.lstrip('\n') }}
982
+ {%- endif -%}
983
+ {%- else -%}
984
+ {{- content }}
985
+ {%- endif -%}
986
+ {%- if message.tool_calls -%}
987
+ {%- if content -%}
988
+ {{- '\n' }}
989
+ {%- endif -%}
990
+ {{- render_tool_calls_block(message.tool_calls, tool_call_fmt, available_tools) }}
991
+ {%- endif -%}
992
+ {{- '<|ifm|im_end|>' -}}
993
+ {%- endgeneration -%}
994
+ {%- elif message.role == "tool" -%}
995
+ {{- render_tool_response_messages(message.content) }}
996
+ {%- endif -%}
997
+ {%- endfor -%}
998
+ {%- if add_generation_prompt -%}
999
+ {%- set effort = reasoning_effort | default('high') -%}
1000
+ {%- if effort == 'high' -%}
1001
+ {{- '<|ifm|im_start|>assistant\n<ifm|think>\n' }}
1002
+ {%- elif effort == 'medium' -%}
1003
+ {{- '<|ifm|im_start|>assistant\n<ifm|think_fast>\n' }}
1004
+ {%- elif effort == 'low' -%}
1005
+ {{- '<|ifm|im_start|>assistant\n<ifm|think_faster>\n' }}
1006
+ {%- else -%}
1007
+ {{- raise_exception("Unsupported reasoning_effort: '" + effort + "'. Supported values: high, medium, low.") -}}
1008
+ {%- endif -%}
1009
+ {%- endif -%}
config.json ADDED
@@ -0,0 +1,88 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "K2HorizonForCausalLM"
4
+ ],
5
+ "attention_bias": false,
6
+ "attention_dropout": 0.0,
7
+ "auto_map": {
8
+ "AutoConfig": "configuration_k2_horizon.K2HorizonConfig",
9
+ "AutoModel": "modeling_k2_horizon.K2HorizonModel",
10
+ "AutoModelForCausalLM": "modeling_k2_horizon.K2HorizonForCausalLM"
11
+ },
12
+ "bos_token_id": 0,
13
+ "decoder_sparse_step": 1,
14
+ "dtype": "bfloat16",
15
+ "eos_token_id": 1,
16
+ "head_dim": 64,
17
+ "hidden_act": "silu",
18
+ "hidden_size": 1536,
19
+ "initializer_range": 0.02,
20
+ "intermediate_size": 5120,
21
+ "layernorm_num_groups": 1,
22
+ "max_position_embeddings": 131072,
23
+ "mlp_only_layers": [
24
+ 0,
25
+ 1,
26
+ 2,
27
+ 3,
28
+ 4,
29
+ 5,
30
+ 6,
31
+ 7,
32
+ 8,
33
+ 9,
34
+ 10,
35
+ 11,
36
+ 12,
37
+ 13,
38
+ 14,
39
+ 15,
40
+ 16,
41
+ 17,
42
+ 18,
43
+ 19,
44
+ 20,
45
+ 21,
46
+ 22,
47
+ 23,
48
+ 24,
49
+ 25,
50
+ 26,
51
+ 27
52
+ ],
53
+ "model_type": "k2_horizon",
54
+ "moe_gate_bias": false,
55
+ "moe_intermediate_size": 0,
56
+ "norm_topk_prob": true,
57
+ "num_attention_heads": 32,
58
+ "num_experts": 0,
59
+ "num_experts_per_tok": 0,
60
+ "num_hidden_layers": 28,
61
+ "num_key_value_heads": 8,
62
+ "num_shared_experts": 0,
63
+ "original_max_position_embeddings": 8192,
64
+ "output_router_logits": false,
65
+ "pad_token_id": 64255,
66
+ "query_key_norm": false,
67
+ "rms_norm_eps": 1e-06,
68
+ "rope_head_dim": 64,
69
+ "rope_parameters": {
70
+ "attention_factor": 1.2772588722239782,
71
+ "beta_fast": 128.0,
72
+ "beta_slow": 4.0,
73
+ "factor": 16.0,
74
+ "original_max_position_embeddings": 8192,
75
+ "rope_type": "yarn",
76
+ "truncate": true
77
+ },
78
+ "rope_theta": 1000000.0,
79
+ "router_aux_loss_coef": 0.001,
80
+ "router_scaling_factor": null,
81
+ "router_score_func": "sigmoid",
82
+ "sliding_window": null,
83
+ "tie_word_embeddings": false,
84
+ "transformers_version": "4.57.1",
85
+ "use_cache": true,
86
+ "use_sliding_window": false,
87
+ "vocab_size": 64256
88
+ }
configuration_k2_horizon.py ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The Qwen team, Alibaba Group and the HuggingFace Inc. team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """K2Horizon model configuration"""
15
+
16
+ from huggingface_hub.dataclasses import strict
17
+
18
+ from transformers.configuration_utils import PreTrainedConfig
19
+ from transformers.modeling_rope_utils import RopeParameters
20
+
21
+
22
+ @strict
23
+ class K2HorizonConfig(PreTrainedConfig):
24
+ r"""
25
+ decoder_sparse_step (`int`, *optional*, defaults to 1):
26
+ The frequency of the MoE layer.
27
+ mlp_only_layers (`list[int]`, *optional*, defaults to `[]`):
28
+ Indicate which layers use K2HorizonMLP rather than K2HorizonSparseMoeBlock
29
+ The list contains layer index, from 0 to num_layers-1 if we have num_layers layers
30
+ If `mlp_only_layers` is empty, `decoder_sparse_step` is used to determine the sparsity.
31
+
32
+ ```python
33
+ >>> from transformers import K2HorizonModel, K2HorizonConfig
34
+
35
+ >>> # Initializing a K2Horizon style configuration
36
+ >>> configuration = K2HorizonConfig()
37
+ >>> model = K2HorizonModel(configuration)
38
+
39
+ >>> # Accessing the model configuration
40
+ >>> configuration = model.config
41
+ ```
42
+ """
43
+
44
+ model_type = "k2_horizon"
45
+ keys_to_ignore_at_inference = ["past_key_values"]
46
+
47
+ vocab_size: int = 151936
48
+ hidden_size: int = 2048
49
+ intermediate_size: int = 6144
50
+ num_hidden_layers: int = 24
51
+ num_attention_heads: int = 32
52
+ num_key_value_heads: int = 4
53
+ hidden_act: str = "silu"
54
+ max_position_embeddings: int = 32768
55
+ initializer_range: float = 0.02
56
+ rms_norm_eps: float = 1e-6
57
+ use_cache: bool = True
58
+ tie_word_embeddings: bool = False
59
+ rope_parameters: RopeParameters | dict | None = None
60
+ attention_bias: bool = False
61
+ use_sliding_window: bool = False
62
+ sliding_window: int | None = 4096
63
+ attention_dropout: float | int = 0.0
64
+ decoder_sparse_step: int = 1
65
+ moe_intermediate_size: int = 768
66
+ num_experts_per_tok: int = 8
67
+ num_experts: int = 128
68
+ norm_topk_prob: bool = False
69
+ output_router_logits: bool = False
70
+ router_aux_loss_coef: float = 0.001
71
+ mlp_only_layers: list[int] | None = None
72
+ pad_token_id: int | None = None
73
+ bos_token_id: int | None = None
74
+ eos_token_id: int | list[int] | None = None
75
+
76
+ head_dim: int = 128
77
+ query_key_norm: bool = True
78
+ moe_gate_bias: bool = False
79
+ layernorm_num_groups: int = 1
80
+ num_shared_experts: int = 0
81
+ router_score_func: str = "softmax"
82
+ router_scaling_factor: float | None = 1.0
83
+ rope_head_dim: int | None = None
84
+ attention_gate_func: str | None = None
85
+ mova_num_experts: int = 0
86
+ mova_num_experts_per_tok: int = 0
87
+
88
+ def __post_init__(self, **kwargs):
89
+ self.sliding_window = self.sliding_window if self.use_sliding_window else None
90
+ self.mlp_only_layers = [] if self.mlp_only_layers is None else self.mlp_only_layers
91
+ if self.router_scaling_factor is None:
92
+ self.router_scaling_factor = 1.0
93
+ super().__post_init__(**kwargs)
94
+
95
+
96
+ __all__ = ["K2HorizonConfig"]
decision_config.json ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "k2-type-0.9b",
3
+ "base_model": "IFM/K2-Horizon-0.9B",
4
+ "temperature": 1.4778441535263076,
5
+ "head_dim": 256,
6
+ "marker_tokens": {
7
+ "state": "reserved_special_token_100",
8
+ "q": "reserved_special_token_101",
9
+ "opt": "reserved_special_token_102",
10
+ "end_opt": "reserved_special_token_103",
11
+ "decide": "reserved_special_token_104"
12
+ },
13
+ "max_len": 8192,
14
+ "max_options": 255,
15
+ "question_types": [
16
+ "noul",
17
+ "choice",
18
+ "score"
19
+ ],
20
+ "api": "POST /v1/systemone (TypeSafe-compatible)"
21
+ }
generation_config.json ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ {
2
+ "bos_token_id": 0,
3
+ "eos_token_id": 1
4
+ }
jev/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ """Inference code for Jev-style decision models (state + typed questions -> probabilities)."""
jev/encode.py ADDED
@@ -0,0 +1,147 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Turn a jev record into one packed sequence: the state once, then every question after it.
2
+
3
+ <state> state tokens | <q> instr <opt> option </opt> ... <decide> | <q> ... <decide> | ...
4
+
5
+ Isolation: a question token may attend to the state and to earlier tokens of its own question, never to another
6
+ question. Position ids restart at the end of the state for every question, so each question sees exactly the
7
+ positions it would see if it were asked alone.
8
+
9
+ Marker tokens are unused reserved ids of the K2 tokenizer, inserted by id (never through text tokenization).
10
+ """
11
+ import json
12
+
13
+ import torch
14
+
15
+ MARKERS = {"state": "reserved_special_token_100", "q": "reserved_special_token_101", "opt": "reserved_special_token_102",
16
+ "end_opt": "reserved_special_token_103", "decide": "reserved_special_token_104"}
17
+
18
+
19
+ def render(v, indent=0):
20
+ pad = " " * indent
21
+ if isinstance(v, dict):
22
+ return "\n".join(f"{pad}{k}:\n{render(x, indent + 1)}" if isinstance(x, (dict, list)) else f"{pad}{k}: {x}"
23
+ for k, x in v.items())
24
+ if isinstance(v, list):
25
+ return "\n".join(f"{pad}- {render(x, indent + 1).strip() if isinstance(x, (dict, list)) else x}" for x in v)
26
+ return f"{pad}{v}"
27
+
28
+
29
+ def options_and_target(q):
30
+ """Option texts and the target distribution for one question."""
31
+ t = q["type"]
32
+ if t == "choice":
33
+ keys = list(q["criteria"])
34
+ opts = [f"{k}: {d}" if d else str(k) for k, d in q["criteria"].items()]
35
+ if q.get("soft") is not None:
36
+ target = [float(q["soft"][k]) for k in keys]
37
+ else:
38
+ target = [1.0 if k == q["label"] else 0.0 for k in keys]
39
+ elif t == "score":
40
+ opts = [str(x) for x in q["criteria"]]
41
+ target = [float(x) for x in q["soft"]] if q.get("soft") is not None else \
42
+ [1.0 if i == q["label"] else 0.0 for i in range(len(opts))]
43
+ else:
44
+ crit = q.get("criteria") or {} # optional definitions of the two outcomes: {"false": ..., "true": ...}
45
+ opts = [f"{k}: {render(crit[k]).strip()}" if crit.get(k) else k for k in ("false", "true")]
46
+ p = float(q["soft"]) if q.get("soft") is not None else float(bool(q["label"]))
47
+ target = [1.0 - p, p]
48
+ s = sum(target)
49
+ return opts, [x / s for x in target]
50
+
51
+
52
+ def teacher_target(q):
53
+ """The question's `teacher` field as a distribution in canonical option order (None if absent)."""
54
+ t = q.get("teacher")
55
+ if t is None:
56
+ return None
57
+ if q["type"] == "choice":
58
+ return [float(t[k]) for k in q["criteria"]]
59
+ if q["type"] == "score":
60
+ return [float(x) for x in t]
61
+ return [1.0 - float(t), float(t)]
62
+
63
+
64
+ class Encoder:
65
+ def __init__(self, tok, max_len=4096, max_state=3072, teacher_mix=None):
66
+ """teacher_mix = alpha: target = alpha * gold + (1 - alpha) * teacher when a question has `teacher`."""
67
+ self.tok, self.max_len, self.max_state, self.teacher_mix = tok, max_len, max_state, teacher_mix
68
+ vocab = tok.get_vocab()
69
+ self.ids = {k: vocab[v] for k, v in MARKERS.items()}
70
+ self.bos = tok.bos_token_id
71
+
72
+ def text(self, s):
73
+ return self.tok(s, add_special_tokens=False).input_ids
74
+
75
+ def encode(self, rec, rng=None):
76
+ """Returns a dict of python lists, or None when not even one question fits.
77
+ With `rng`, choice and noul options are shown in a random order (targets permuted to match)."""
78
+ state = self.text(render(rec["state"]))[: self.max_state]
79
+ ids = [self.bos, self.ids["state"]] + state
80
+ seg = [0] * len(ids)
81
+ pos = list(range(len(ids)))
82
+ S = len(ids)
83
+ decide, opt_ends, targets, qtypes, qkeys, perms = [], [], [], [], [], []
84
+ for j, (k, q) in enumerate(rec["questions"].items()):
85
+ opts, target = options_and_target(q)
86
+ tt = teacher_target(q) if self.teacher_mix is not None else None
87
+ if tt is not None:
88
+ a = self.teacher_mix
89
+ target = [a * g + (1 - a) * t for g, t in zip(target, tt)]
90
+ order = list(range(len(opts)))
91
+ if rng is not None and q["type"] != "score":
92
+ rng.shuffle(order)
93
+ opts, target = [opts[i] for i in order], [target[i] for i in order]
94
+ instr = q["instructions"] if isinstance(q["instructions"], str) else render(q["instructions"]) # Kev uses dicts too
95
+ qi = [self.ids["q"]] + self.text(instr)
96
+ ends = []
97
+ for o in opts:
98
+ qi += [self.ids["opt"]] + self.text(o)[:128] + [self.ids["end_opt"]]
99
+ ends.append(len(qi) - 1)
100
+ qi.append(self.ids["decide"])
101
+ if len(ids) + len(qi) > self.max_len:
102
+ continue # skip questions that do not fit; the others still train
103
+ base = len(ids)
104
+ ids += qi
105
+ seg += [j + 1] * len(qi)
106
+ pos += list(range(S, S + len(qi)))
107
+ decide.append(base + len(qi) - 1)
108
+ opt_ends.append([base + e for e in ends])
109
+ targets.append(target)
110
+ qtypes.append(q["type"])
111
+ qkeys.append(k)
112
+ perms.append(order) # shown position -> canonical option index
113
+ if not decide:
114
+ return None
115
+ return {"ids": ids, "seg": seg, "pos": pos, "decide": decide, "opt_ends": opt_ends,
116
+ "targets": targets, "qtypes": qtypes, "qkeys": qkeys, "perms": perms}
117
+
118
+
119
+ def collate(items, pad_id):
120
+ """Right-pad a batch and build the [B, 1, L, L] boolean isolation mask (True = may attend)."""
121
+ B, L = len(items), max(len(x["ids"]) for x in items)
122
+ ids = torch.full((B, L), pad_id, dtype=torch.long)
123
+ pos = torch.zeros((B, L), dtype=torch.long)
124
+ seg = torch.full((B, L), -1, dtype=torch.long)
125
+ for b, x in enumerate(items):
126
+ n = len(x["ids"])
127
+ ids[b, :n] = torch.tensor(x["ids"])
128
+ pos[b, :n] = torch.tensor(x["pos"])
129
+ seg[b, :n] = torch.tensor(x["seg"])
130
+ causal = torch.ones(L, L, dtype=torch.bool).tril()
131
+ sq, sk = seg[:, :, None], seg[:, None, :]
132
+ mask = causal[None] & (sk >= 0) & (sq >= 0) & ((sk == 0) | (sk == sq))
133
+ mask |= torch.eye(L, dtype=torch.bool)[None] # padding rows attend to themselves only (avoids NaN softmax)
134
+ # flat question index: (batch row, decide position, option end positions, target)
135
+ qs = [(b, d, e, t, ty) for b, x in enumerate(items)
136
+ for d, e, t, ty in zip(x["decide"], x["opt_ends"], x["targets"], x["qtypes"])]
137
+ return {"input_ids": ids, "position_ids": pos, "mask": mask[:, None], "questions": qs}
138
+
139
+
140
+ def load_jsonl(path, limit=0):
141
+ out = []
142
+ with open(path) as fh:
143
+ for i, line in enumerate(fh):
144
+ if limit and i >= limit:
145
+ break
146
+ out.append(json.loads(line))
147
+ return out
jev/model.py ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Decision model: a causal-LM backbone plus a pointer head.
2
+
3
+ For each question the head scores every option's `</opt>` hidden state against the question's `<decide>` hidden
4
+ state (scaled dot product in a small projected space); a softmax over those scores is the answer distribution.
5
+ The LM head is never run (frozen, but saved so the checkpoint loads as a normal causal LM). A scalar temperature (fitted after training) divides the scores at inference.
6
+ """
7
+ import math
8
+
9
+ import torch
10
+ import torch.nn as nn
11
+ import torch.nn.functional as F
12
+ from transformers import AutoModelForCausalLM
13
+
14
+
15
+ class PointerHead(nn.Module):
16
+ def __init__(self, hidden, dim=256):
17
+ super().__init__()
18
+ self.norm = nn.LayerNorm(hidden)
19
+ self.q = nn.Linear(hidden, dim)
20
+ self.k = nn.Linear(hidden, dim)
21
+ self.dim = dim
22
+
23
+ def forward(self, h_decide, h_opts):
24
+ """h_decide: [H]; h_opts: [K, H] -> scores [K]."""
25
+ q = self.q(self.norm(h_decide))
26
+ k = self.k(self.norm(h_opts))
27
+ return k @ q / math.sqrt(self.dim)
28
+
29
+
30
+ class DecisionModel(nn.Module):
31
+ def __init__(self, path, head_dim=256, dtype=torch.bfloat16, attn="sdpa", lora_r=0, marker_ids=None):
32
+ super().__init__()
33
+ lm = AutoModelForCausalLM.from_pretrained(path, dtype=dtype, trust_remote_code=True, attn_implementation=attn)
34
+ lm.lm_head.requires_grad_(False) # never run; kept only so the saved checkpoint is a complete model
35
+ if lora_r:
36
+ from peft import LoraConfig, get_peft_model
37
+ cfg = LoraConfig(r=lora_r, lora_alpha=2 * lora_r, lora_dropout=0.0, bias="none",
38
+ target_modules=["q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "up_proj", "down_proj"],
39
+ trainable_token_indices={"embed_tokens": list(marker_ids or [])})
40
+ lm = get_peft_model(lm, cfg)
41
+ self.lm = lm
42
+ self.lora = bool(lora_r)
43
+ self.config = lm.config
44
+ self.head = PointerHead(lm.config.hidden_size, head_dim).to(torch.float32)
45
+ self.register_buffer("temperature", torch.ones(()))
46
+
47
+ @property
48
+ def backbone(self):
49
+ base = self.lm.get_base_model() if self.lora else self.lm
50
+ return base.model # decoder stack only
51
+
52
+ def forward(self, batch, return_hidden=False):
53
+ """Returns one score vector per question, in the order of batch['questions'].
54
+ With return_hidden, also returns the stacked `<decide>` hidden states [Q, H] (used by the RL value head)."""
55
+ dev = next(self.parameters()).device
56
+ out = self.backbone(input_ids=batch["input_ids"].to(dev), position_ids=batch["position_ids"].to(dev),
57
+ attention_mask=batch["mask"].to(dev), use_cache=False)
58
+ h = out.last_hidden_state.float()
59
+ scores = []
60
+ for b, d, ends, _, _ in batch["questions"]:
61
+ scores.append(self.head(h[b, d], h[b, ends]) / self.temperature)
62
+ if return_hidden:
63
+ return scores, torch.stack([h[b, d] for b, d, _, _, _ in batch["questions"]])
64
+ return scores
65
+
66
+
67
+ def loss_fn(scores, questions):
68
+ """Cross-entropy against the (possibly soft) target of each question, averaged over questions."""
69
+ losses = []
70
+ for s, (_, _, _, target, _) in zip(scores, questions):
71
+ t = torch.tensor(target, device=s.device, dtype=s.dtype)
72
+ losses.append(-(t * F.log_softmax(s, -1)).sum())
73
+ return torch.stack(losses).mean()
jev/serve.py ADDED
@@ -0,0 +1,143 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """HTTP server for a trained jev decision model: POST /v1/systemone (TypeSafe/Kev-compatible), plus demo pages.
2
+
3
+ python -m jev.serve --run <train run dir> [--port 8000]
4
+
5
+ Request: {"state": str|object, "questions": {id: {"type": "noul"|"choice"|"score", "instructions": ..., "criteria": ...}}}
6
+ Response: {"answers": {id: ...}, "latency_ms": float, "model": str, "input_tokens": int}
7
+ noul -> {"noul": P(true)}
8
+ choice -> {"choice": best, "confidence": (pmax - 1/K) / (1 - 1/K), "probabilities": {option: p}}
9
+ score -> {"score": expected level, "legend": {i: level}, "probabilities": {i: p}, "confidence": ...}
10
+ All questions of a request share one forward pass (state encoded once; questions isolated by the attention mask).
11
+ """
12
+ import argparse
13
+ import json
14
+ import os
15
+ import time
16
+
17
+ import torch
18
+ from fastapi import FastAPI, HTTPException
19
+ from fastapi.responses import FileResponse
20
+ from transformers import AutoTokenizer
21
+
22
+ from jev.encode import Encoder, collate, render
23
+ from jev.model import DecisionModel
24
+
25
+ DEMO = os.path.join(os.path.dirname(__file__), "demo")
26
+
27
+
28
+ def to_record(req):
29
+ """API request -> jev record (labels are placeholders; only the option layout is used)."""
30
+ qs = {}
31
+ for qid, q in req["questions"].items():
32
+ t = q.get("type")
33
+ instr = q.get("instructions") or ""
34
+ instr = instr if isinstance(instr, str) else render(instr)
35
+ if t == "choice":
36
+ crit = q.get("criteria") or {}
37
+ if not 1 <= len(crit) <= 255:
38
+ raise HTTPException(400, f"{qid}: choice needs 1..255 options")
39
+ crit = {k: (v if v is None or isinstance(v, str) else render(v)) for k, v in crit.items()}
40
+ qs[qid] = {"type": "choice", "instructions": instr, "criteria": crit, "label": next(iter(crit))}
41
+ elif t == "score":
42
+ levels = [c if isinstance(c, str) else render(c) for c in (q.get("criteria") or [])]
43
+ if not 2 <= len(levels) <= 255:
44
+ raise HTTPException(400, f"{qid}: score needs 2..255 levels")
45
+ qs[qid] = {"type": "score", "instructions": instr, "criteria": levels, "label": 0}
46
+ elif t == "noul":
47
+ crit = q.get("criteria") or {}
48
+ crit = {k: (v if v is None or isinstance(v, str) else render(v)) for k, v in crit.items() if k in ("false", "true")}
49
+ qs[qid] = {"type": "noul", "instructions": instr, "label": False, **({"criteria": crit} if crit else {})}
50
+ else:
51
+ raise HTTPException(400, f"{qid}: unknown type {t!r}")
52
+ return {"state": req["state"], "questions": qs}
53
+
54
+
55
+ def answer(q, p):
56
+ r4 = lambda x: round(float(x), 4) # noqa: E731
57
+ if q["type"] == "noul":
58
+ return {"type": "noul", "noul": r4(p[1])}
59
+ if q["type"] == "choice":
60
+ keys = list(q["criteria"])
61
+ K = len(p)
62
+ conf = 1.0 if K == 1 else (max(p) - 1 / K) / (1 - 1 / K)
63
+ return {"type": "choice", "choice": keys[max(range(K), key=lambda i: p[i])], "confidence": r4(conf),
64
+ "probabilities": {k: r4(v) for k, v in zip(keys, p)}}
65
+ L = len(p)
66
+ mode = max(range(L), key=lambda i: p[i])
67
+ return {"type": "score", "score": r4(sum(i * x for i, x in enumerate(p))),
68
+ "legend": {str(i): c for i, c in enumerate(q["criteria"])},
69
+ "probabilities": {str(i): r4(x) for i, x in enumerate(p)},
70
+ "confidence": r4(1.0 - sum(x * abs(i - mode) for i, x in enumerate(p)) / (L - 1))}
71
+
72
+
73
+ def load(path):
74
+ """-> (model on GPU, tokenizer, name). Accepts a train run dir (args.json + model/pointer_head.pt) or a release dir
75
+ (weights at the root + pointer_head.safetensors + decision_config.json)."""
76
+ if os.path.exists(f"{path}/decision_config.json"):
77
+ from safetensors.torch import load_file
78
+ cfg = json.load(open(f"{path}/decision_config.json"))
79
+ weights, head, T, name = path, load_file(f"{path}/pointer_head.safetensors"), cfg["temperature"], cfg["name"]
80
+ else:
81
+ ckpt = torch.load(f"{path}/model/pointer_head.pt", map_location="cpu")
82
+ weights, head, T = f"{path}/model", ckpt["head"], ckpt["temperature"]
83
+ name = json.load(open(f"{path}/args.json")).get("name", os.path.basename(path.rstrip("/")))
84
+ tok = AutoTokenizer.from_pretrained(weights, trust_remote_code=True)
85
+ model = DecisionModel(weights)
86
+ model.head.load_state_dict(head)
87
+ model.temperature.fill_(T)
88
+ return model.cuda().eval(), tok, name
89
+
90
+
91
+ def build(run, max_len=8192):
92
+ model, tok, name = load(run)
93
+ enc = Encoder(tok, max_len, max_len - 1024)
94
+ pad = tok.pad_token_id if tok.pad_token_id is not None else tok.eos_token_id
95
+ head = {"temperature": float(model.temperature)}
96
+
97
+ app = FastAPI(title="jev decision model")
98
+
99
+ @app.post("/v1/systemone")
100
+ def systemone(req: dict):
101
+ t0 = time.perf_counter()
102
+ rec = to_record(req)
103
+ e = enc.encode(rec)
104
+ if e is None or len(e["decide"]) != len(rec["questions"]):
105
+ raise HTTPException(413, f"request does not fit in {max_len} tokens")
106
+ with torch.no_grad(), torch.autocast("cuda", dtype=torch.bfloat16):
107
+ scores = model(collate([e], pad))
108
+ answers = {}
109
+ for k, s in zip(e["qkeys"], scores):
110
+ p = torch.softmax(s.float(), -1).tolist()
111
+ answers[k] = answer(rec["questions"][k], p)
112
+ torch.cuda.synchronize()
113
+ return {"answers": answers, "model": name, "input_tokens": len(e["ids"]),
114
+ "latency_ms": round((time.perf_counter() - t0) * 1000, 1)}
115
+
116
+ @app.get("/health")
117
+ def health():
118
+ return {"ok": True, "model": name, "temperature": float(head["temperature"])}
119
+
120
+ if os.path.isdir(DEMO): # demo pages are optional (not shipped in the weights release)
121
+ @app.get("/")
122
+ def playground():
123
+ return FileResponse(os.path.join(DEMO, "playground.html"))
124
+
125
+ @app.get("/snake")
126
+ def snake():
127
+ return FileResponse(os.path.join(DEMO, "snake.html"))
128
+
129
+ return app
130
+
131
+
132
+ def main():
133
+ ap = argparse.ArgumentParser()
134
+ ap.add_argument("--run", required=True)
135
+ ap.add_argument("--host", default="0.0.0.0")
136
+ ap.add_argument("--port", type=int, default=8000)
137
+ args = ap.parse_args()
138
+ import uvicorn
139
+ uvicorn.run(build(args.run), host=args.host, port=args.port, log_level="warning")
140
+
141
+
142
+ if __name__ == "__main__":
143
+ main()
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:786cd5be07bb5267e6bbac3599db6779b4be9ffe46b35656e2578af8747f28b0
3
+ size 2156601000
modeling_k2_horizon.py ADDED
@@ -0,0 +1,1116 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
2
+ # This file was automatically generated from src/transformers/models/qwen3_moe/modular_qwen3_moe.py.
3
+ # Do NOT edit this file manually as any edits will be overwritten by the generation of
4
+ # the file from the modular. If any change should be done, please apply the change to the
5
+ # modular_qwen3_moe.py file directly. One of our CI enforces this.
6
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
7
+ # coding=utf-8
8
+ # Copyright 2025 The Qwen team, Alibaba Group and the HuggingFace Inc. team. All rights reserved.
9
+ #
10
+ # Licensed under the Apache License, Version 2.0 (the "License");
11
+ # you may not use this file except in compliance with the License.
12
+ # You may obtain a copy of the License at
13
+ #
14
+ # http://www.apache.org/licenses/LICENSE-2.0
15
+ #
16
+ # Unless required by applicable law or agreed to in writing, software
17
+ # distributed under the License is distributed on an "AS IS" BASIS,
18
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19
+ # See the License for the specific language governing permissions and
20
+ # limitations under the License.
21
+
22
+ from typing import Callable, Optional, Union
23
+
24
+ import math
25
+ import torch
26
+ import torch.nn.functional as F
27
+ from torch import nn
28
+
29
+ from transformers.activations import ACT2FN
30
+ from transformers.cache_utils import Cache, DynamicCache
31
+ from transformers.generation import GenerationMixin
32
+ from transformers.masking_utils import create_causal_mask, create_sliding_window_causal_mask
33
+ from transformers.modeling_flash_attention_utils import FlashAttentionKwargs
34
+ from transformers.modeling_layers import (
35
+ GenericForQuestionAnswering,
36
+ GenericForSequenceClassification,
37
+ GenericForTokenClassification,
38
+ GradientCheckpointingLayer,
39
+ )
40
+ from transformers.modeling_outputs import MoeCausalLMOutputWithPast, MoeModelOutputWithPast
41
+ from transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
42
+ from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
43
+ from transformers.processing_utils import Unpack
44
+ from transformers.utils import TransformersKwargs, auto_docstring, can_return_tuple
45
+ from transformers.utils.generic import maybe_autocast
46
+ from transformers.utils.deprecation import deprecate_kwarg
47
+ from transformers.utils.output_capturing import OutputRecorder
48
+
49
+ from .configuration_k2_horizon import K2HorizonConfig
50
+
51
+
52
+ def rotate_half(x):
53
+ """Rotates half the hidden dims of the input."""
54
+ x1 = x[..., : x.shape[-1] // 2]
55
+ x2 = x[..., x.shape[-1] // 2:]
56
+ return torch.cat((-x2, x1), dim=-1)
57
+
58
+
59
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
60
+ """Applies Rotary Position Embedding to the query and key tensors.
61
+
62
+ Args:
63
+ q (`torch.Tensor`): The query tensor.
64
+ k (`torch.Tensor`): The key tensor.
65
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
66
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
67
+ position_ids (`torch.Tensor`, *optional*):
68
+ Deprecated and unused.
69
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
70
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
71
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
72
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
73
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
74
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
75
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
76
+ Returns:
77
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
78
+ """
79
+ cos = cos.unsqueeze(unsqueeze_dim)
80
+ sin = sin.unsqueeze(unsqueeze_dim)
81
+ q_embed = (q * cos) + (rotate_half(q) * sin)
82
+ k_embed = (k * cos) + (rotate_half(k) * sin)
83
+ return q_embed, k_embed
84
+
85
+
86
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
87
+ """
88
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
89
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
90
+ """
91
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
92
+ if n_rep == 1:
93
+ return hidden_states
94
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
95
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
96
+
97
+
98
+ def split_to_interleaved(x):
99
+ # Split halves: x0 x1 x2 x3 ... y0 y1 y2 y3 ...
100
+ # Interleaved: x0 y0 x1 y1 x2 y2 x3 y3 ...
101
+ return x.reshape(*x.shape[:-1], 2, -1).transpose(-1, -2).reshape(*x.shape[:-1], -1)
102
+
103
+
104
+ def interleaved_to_split(x):
105
+ # Interleaved: x0 y0 x1 y1 x2 y2 x3 y3 ...
106
+ # Split halves: x0 x1 x2 x3 ... y0 y1 y2 y3 ...
107
+ return x.reshape(*x.shape[:-1], -1, 2).transpose(-1, -2).reshape(*x.shape[:-1], -1)
108
+
109
+
110
+ def eager_attention_forward(
111
+ module: nn.Module,
112
+ query: torch.Tensor,
113
+ key: torch.Tensor,
114
+ value: torch.Tensor,
115
+ attention_mask: Optional[torch.Tensor],
116
+ scaling: float,
117
+ dropout: float = 0.0,
118
+ **kwargs: Unpack[TransformersKwargs],
119
+ ):
120
+ key_states = repeat_kv(key, module.num_key_value_groups)
121
+ value_states = repeat_kv(value, module.num_key_value_groups)
122
+
123
+ attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
124
+ if attention_mask is not None:
125
+ causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
126
+ attn_weights = attn_weights + causal_mask
127
+
128
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
129
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
130
+ attn_output = torch.matmul(attn_weights, value_states)
131
+ attn_output = attn_output.transpose(1, 2).contiguous()
132
+
133
+ return attn_output, attn_weights
134
+
135
+
136
+ def calc_router_weights(
137
+ router_logits: torch.Tensor,
138
+ router_bias: Optional[torch.Tensor],
139
+ score_func: str,
140
+ top_k: int,
141
+ scaling_factor: Optional[float],
142
+ ) -> tuple[torch.Tensor, torch.Tensor]:
143
+ """Return native-XLLM-compatible routing weights and selected experts.
144
+
145
+ XLLM applies router bias only to the values used for top-k selection. The
146
+ selected routes are still weighted by the original router probabilities,
147
+ then optionally normalized and scaled.
148
+ """
149
+ if score_func == "softmax":
150
+ routing_scores = F.softmax(router_logits, dim=-1, dtype=torch.float32)
151
+ elif score_func == "sigmoid":
152
+ routing_scores = torch.sigmoid(router_logits.to(torch.float32))
153
+ else:
154
+ raise ValueError(f"Unsupported router score function: {score_func}")
155
+
156
+ selection_scores = routing_scores
157
+ if router_bias is not None:
158
+ selection_scores = selection_scores + router_bias.to(selection_scores)
159
+
160
+ selected_indices = torch.topk(selection_scores, top_k, dim=-1).indices
161
+ routing_weights = torch.gather(routing_scores, dim=-1, index=selected_indices)
162
+ if top_k > 1:
163
+ routing_weights = routing_weights / routing_weights.sum(dim=-1, keepdim=True)
164
+ if scaling_factor is not None:
165
+ routing_weights = routing_weights * scaling_factor
166
+ return routing_weights, selected_indices
167
+
168
+
169
+ def combine_routed_experts(
170
+ hidden_states: torch.Tensor,
171
+ routing_weights: torch.Tensor,
172
+ selected_indices: torch.Tensor,
173
+ experts: nn.ModuleList,
174
+ activation: Optional[Callable[[torch.Tensor], torch.Tensor]] = None,
175
+ ) -> torch.Tensor:
176
+ num_tokens, hidden_dim = hidden_states.shape
177
+ final_hidden_states = torch.zeros(
178
+ (num_tokens, experts[0].out_features),
179
+ dtype=hidden_states.dtype,
180
+ device=hidden_states.device,
181
+ )
182
+ expert_mask = torch.nn.functional.one_hot(
183
+ selected_indices, num_classes=len(experts)
184
+ ).permute(2, 1, 0)
185
+
186
+ for expert_idx in torch.nonzero(expert_mask.sum(dim=(-1, -2)), as_tuple=False).flatten():
187
+ topk_positions, token_positions = torch.where(expert_mask[int(expert_idx)])
188
+ expert_states = experts[int(expert_idx)](hidden_states[token_positions])
189
+ if activation is not None:
190
+ expert_states = activation(expert_states)
191
+ expert_states = expert_states * routing_weights[token_positions, topk_positions, None].to(expert_states.dtype)
192
+ final_hidden_states.index_add_(0, token_positions, expert_states.to(hidden_states.dtype))
193
+
194
+ return final_hidden_states
195
+
196
+
197
+ class K2HorizonAttention(nn.Module):
198
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
199
+
200
+ def __init__(self, config: K2HorizonConfig, layer_idx: int):
201
+ super().__init__()
202
+ self.config = config
203
+ self.layer_idx = layer_idx
204
+ self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
205
+ self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
206
+ self.scaling = self.head_dim ** -0.5
207
+ self.attention_dropout = config.attention_dropout
208
+ self.is_causal = True
209
+
210
+ self.rope_head_dim = self.head_dim if config.rope_head_dim is None else config.rope_head_dim
211
+
212
+ self.q_proj = nn.Linear(
213
+ config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.attention_bias
214
+ )
215
+ self.k_proj = nn.Linear(
216
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
217
+ )
218
+ self.v_proj = nn.Linear(
219
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
220
+ )
221
+ self.o_proj = nn.Linear(
222
+ config.num_attention_heads * self.head_dim, config.hidden_size, bias=config.attention_bias
223
+ )
224
+
225
+ self.gate_func = config.attention_gate_func
226
+ if self.gate_func is not None:
227
+ self.gate_proj = nn.Linear(
228
+ config.hidden_size,
229
+ config.num_attention_heads * self.head_dim,
230
+ bias=False)
231
+
232
+ if config.query_key_norm:
233
+ self.q_norm = K2HorizonRMSNorm(
234
+ hidden_size=config.num_attention_heads * self.head_dim,
235
+ n_groups=config.num_attention_heads,
236
+ eps=config.rms_norm_eps)
237
+ self.k_norm = K2HorizonRMSNorm(
238
+ hidden_size=config.num_key_value_heads * self.head_dim,
239
+ n_groups=config.num_key_value_heads,
240
+ eps=config.rms_norm_eps)
241
+
242
+ self.sliding_window = getattr(config, "sliding_window", None)
243
+
244
+ @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
245
+ def forward(
246
+ self,
247
+ hidden_states: torch.Tensor,
248
+ position_embeddings: tuple[torch.Tensor, torch.Tensor],
249
+ attention_mask: Optional[torch.Tensor],
250
+ past_key_values: Optional[Cache] = None,
251
+ cache_position: Optional[torch.LongTensor] = None,
252
+ **kwargs: Unpack[FlashAttentionKwargs],
253
+ ) -> tuple[torch.Tensor, Optional[torch.Tensor]]:
254
+ input_shape = hidden_states.shape[:-1]
255
+ hidden_shape = (*input_shape, -1, self.head_dim)
256
+
257
+ if self.config.query_key_norm:
258
+ query_states = self.q_norm(self.q_proj(hidden_states)).view(hidden_shape).transpose(1, 2)
259
+ key_states = self.k_norm(self.k_proj(hidden_states)).view(hidden_shape).transpose(1, 2)
260
+ else:
261
+ query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
262
+ key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2)
263
+
264
+ value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
265
+
266
+ cos, sin = position_embeddings
267
+ if self.rope_head_dim == self.head_dim:
268
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
269
+ else:
270
+ query_states, query_states_ = torch.split(
271
+ split_to_interleaved(query_states),
272
+ split_size_or_sections=[self.rope_head_dim, self.head_dim - self.rope_head_dim],
273
+ dim=-1)
274
+
275
+ key_states, key_states_ = torch.split(
276
+ split_to_interleaved(key_states),
277
+ split_size_or_sections=[self.rope_head_dim, self.head_dim - self.rope_head_dim],
278
+ dim=-1)
279
+
280
+ query_states, key_states = apply_rotary_pos_emb(
281
+ interleaved_to_split(query_states),
282
+ interleaved_to_split(key_states),
283
+ cos,
284
+ sin)
285
+
286
+ query_states = interleaved_to_split(torch.cat(
287
+ [split_to_interleaved(query_states), query_states_], dim=-1))
288
+ key_states = interleaved_to_split(torch.cat(
289
+ [split_to_interleaved(key_states), key_states_], dim=-1))
290
+
291
+ if past_key_values is not None:
292
+ # sin and cos are specific to RoPE models; cache_position needed for the static cache
293
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
294
+ key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx, cache_kwargs)
295
+
296
+ attention_interface: Callable = eager_attention_forward
297
+ if self.config._attn_implementation != "eager":
298
+ attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
299
+
300
+ attn_output, attn_weights = attention_interface(
301
+ self,
302
+ query_states,
303
+ key_states,
304
+ value_states,
305
+ attention_mask,
306
+ dropout=0.0 if not self.training else self.attention_dropout,
307
+ scaling=self.scaling,
308
+ sliding_window=self.sliding_window, # diff with Llama
309
+ **kwargs,
310
+ )
311
+
312
+ if self.gate_func is not None:
313
+ gate = self.gate_proj(hidden_states).view(
314
+ input_shape + (-1, self.head_dim))
315
+ if self.gate_func == 'silu':
316
+ gate = F.silu(gate)
317
+ else:
318
+ assert self.gate_func == 'softplus'
319
+ gate = F.softplus(gate, beta=math.log(2))
320
+
321
+ attn_output = attn_output * gate
322
+
323
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
324
+ attn_output = self.o_proj(attn_output)
325
+ return attn_output, attn_weights
326
+
327
+
328
+ def apply_rotary_pos_emb_xllm(q, k, freqs_cis):
329
+ if q.shape[-1] % 2 != 0 or k.shape[-1] % 2 != 0:
330
+ raise ValueError(f"RoPE dimensions must be even, got q={q.shape[-1]} and k={k.shape[-1]}")
331
+ q_ = torch.view_as_complex(q.float().reshape(*q.shape[:-1], -1, 2))
332
+ k_ = torch.view_as_complex(k.float().reshape(*k.shape[:-1], -1, 2))
333
+ if freqs_cis.ndim == 2:
334
+ freqs_cis = freqs_cis.unsqueeze(1)
335
+ elif freqs_cis.ndim == 3:
336
+ freqs_cis = freqs_cis.unsqueeze(2)
337
+ else:
338
+ raise ValueError(f"Unsupported freqs_cis shape: {tuple(freqs_cis.shape)}")
339
+ if freqs_cis.shape[-1] != q_.shape[-1] or freqs_cis.shape[-1] != k_.shape[-1]:
340
+ raise ValueError(
341
+ "RoPE frequency dimension mismatch: "
342
+ f"q_rope_dim={q.shape[-1]}, k_rope_dim={k.shape[-1]}, "
343
+ f"q_complex_dim={q_.shape[-1]}, k_complex_dim={k_.shape[-1]}, "
344
+ f"freqs_complex_dim={freqs_cis.shape[-1]}, freqs_shape={tuple(freqs_cis.shape)}"
345
+ )
346
+ q_embed = torch.view_as_real(q_ * freqs_cis).flatten(-2).to(q.dtype)
347
+ k_embed = torch.view_as_real(k_ * freqs_cis).flatten(-2).to(k.dtype)
348
+ return q_embed, k_embed
349
+
350
+
351
+ class K2HorizonMoVAAttention(nn.Module):
352
+ """MoVA attention with routed value experts and optional post-attention gate."""
353
+
354
+ def __init__(self, config: K2HorizonConfig, layer_idx: int):
355
+ super().__init__()
356
+ self.config = config
357
+ self.layer_idx = layer_idx
358
+ self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
359
+ self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
360
+ self.scaling = self.head_dim**-0.5
361
+ self.attention_dropout = config.attention_dropout
362
+ self.is_causal = True
363
+
364
+ self.num_experts_per_tok = config.mova_num_experts_per_tok
365
+ self.router_score_func = config.router_score_func
366
+ self.router_scaling_factor = config.router_scaling_factor
367
+ self.gate_func = config.attention_gate_func
368
+
369
+ self.rope_head_dim = self.head_dim if config.rope_head_dim is None else config.rope_head_dim
370
+
371
+ self.q_proj = nn.Linear(
372
+ config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.attention_bias
373
+ )
374
+ self.k_proj = nn.Linear(
375
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
376
+ )
377
+ self.o_proj = nn.Linear(
378
+ config.num_attention_heads * self.head_dim, config.hidden_size, bias=config.attention_bias
379
+ )
380
+ self.v_router = nn.Linear(
381
+ config.hidden_size,
382
+ config.mova_num_experts,
383
+ bias=config.moe_gate_bias)
384
+ self.v_experts = nn.ModuleList([
385
+ nn.Linear(
386
+ config.hidden_size,
387
+ config.num_key_value_heads * self.head_dim,
388
+ bias=False
389
+ ) for _ in range(config.mova_num_experts)
390
+ ])
391
+
392
+ if self.gate_func is not None:
393
+ self.gate_proj = nn.Linear(
394
+ config.hidden_size,
395
+ config.num_attention_heads * self.head_dim,
396
+ bias=False)
397
+
398
+ if config.query_key_norm:
399
+ self.q_norm = K2HorizonRMSNorm(
400
+ hidden_size=config.num_attention_heads * self.head_dim,
401
+ n_groups=config.num_attention_heads,
402
+ eps=config.rms_norm_eps,
403
+ )
404
+ self.k_norm = K2HorizonRMSNorm(
405
+ hidden_size=config.num_key_value_heads * self.head_dim,
406
+ n_groups=config.num_key_value_heads,
407
+ eps=config.rms_norm_eps,
408
+ )
409
+
410
+ self.sliding_window = getattr(config, "sliding_window", None)
411
+
412
+ @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
413
+ def forward(
414
+ self,
415
+ hidden_states: torch.Tensor,
416
+ position_embeddings: torch.Tensor,
417
+ attention_mask: Optional[torch.Tensor],
418
+ past_key_values: Optional[Cache] = None,
419
+ cache_position: Optional[torch.LongTensor] = None,
420
+ **kwargs: Unpack[FlashAttentionKwargs],
421
+ ) -> tuple[torch.Tensor, Optional[torch.Tensor]]:
422
+ input_shape = hidden_states.shape[:-1]
423
+ hidden_shape = (*input_shape, -1, self.head_dim)
424
+ flat_hidden_states = hidden_states.reshape(-1, hidden_states.shape[-1])
425
+
426
+ # Match native MOVAttention router semantics exactly: compute logits with
427
+ # the weight-only linear and apply router bias only to selection scores.
428
+ router_logits = F.linear(flat_hidden_states, self.v_router.weight)
429
+ routing_weights, selected_values = calc_router_weights(
430
+ router_logits=router_logits,
431
+ router_bias=self.v_router.bias,
432
+ score_func=self.router_score_func,
433
+ top_k=self.num_experts_per_tok,
434
+ scaling_factor=self.router_scaling_factor,
435
+ )
436
+
437
+ mixed_value_states = combine_routed_experts(
438
+ hidden_states=flat_hidden_states,
439
+ routing_weights=routing_weights,
440
+ selected_indices=selected_values,
441
+ experts=self.v_experts,
442
+ activation=F.silu)
443
+
444
+ value_states = mixed_value_states.view(hidden_shape).transpose(1, 2)
445
+
446
+ if self.config.query_key_norm:
447
+ query_states = self.q_norm(self.q_proj(hidden_states)).view(hidden_shape).transpose(1, 2)
448
+ key_states = self.k_norm(self.k_proj(hidden_states)).view(hidden_shape).transpose(1, 2)
449
+ else:
450
+ query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
451
+ key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2)
452
+
453
+ cos, sin = position_embeddings
454
+ if self.rope_head_dim == self.head_dim:
455
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
456
+ else:
457
+ query_states, query_states_ = torch.split(
458
+ split_to_interleaved(query_states),
459
+ split_size_or_sections=[self.rope_head_dim, self.head_dim - self.rope_head_dim],
460
+ dim=-1)
461
+
462
+ key_states, key_states_ = torch.split(
463
+ split_to_interleaved(key_states),
464
+ split_size_or_sections=[self.rope_head_dim, self.head_dim - self.rope_head_dim],
465
+ dim=-1)
466
+
467
+ query_states, key_states = apply_rotary_pos_emb(
468
+ interleaved_to_split(query_states),
469
+ interleaved_to_split(key_states),
470
+ cos,
471
+ sin)
472
+
473
+ query_states = interleaved_to_split(torch.cat(
474
+ [split_to_interleaved(query_states), query_states_], dim=-1))
475
+ key_states = interleaved_to_split(torch.cat(
476
+ [split_to_interleaved(key_states), key_states_], dim=-1))
477
+
478
+ if past_key_values is not None:
479
+ cache_kwargs = {"cache_position": cache_position}
480
+ key_states, value_states = past_key_values.update(
481
+ key_states, value_states, self.layer_idx, cache_kwargs
482
+ )
483
+
484
+ attention_interface: Callable = eager_attention_forward
485
+ if self.config._attn_implementation != "eager":
486
+ attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
487
+
488
+ attn_output, attn_weights = attention_interface(
489
+ self,
490
+ query_states,
491
+ key_states,
492
+ value_states,
493
+ attention_mask,
494
+ dropout=0.0 if not self.training else self.attention_dropout,
495
+ scaling=self.scaling,
496
+ sliding_window=self.sliding_window,
497
+ **kwargs,
498
+ )
499
+
500
+ if self.gate_func is not None:
501
+ gate = self.gate_proj(hidden_states).view(input_shape + (-1, self.head_dim))
502
+ if self.gate_func == 'silu':
503
+ gate = F.silu(gate)
504
+ else:
505
+ assert self.gate_func == 'softplus'
506
+ gate = F.softplus(gate, beta=math.log(2))
507
+
508
+ attn_output = attn_output * gate
509
+
510
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
511
+ attn_output = self.o_proj(attn_output)
512
+ return attn_output, attn_weights
513
+
514
+
515
+ class K2HorizonMLP(nn.Module):
516
+ def __init__(self, config, intermediate_size=None):
517
+ super().__init__()
518
+ self.config = config
519
+ self.hidden_size = config.hidden_size
520
+ self.intermediate_size = intermediate_size if intermediate_size is not None else config.intermediate_size
521
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
522
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
523
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
524
+ self.act_fn = ACT2FN[config.hidden_act]
525
+
526
+ def forward(self, x):
527
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
528
+ return down_proj
529
+
530
+
531
+ class K2HorizonSparseMoeBlock(nn.Module):
532
+ def __init__(self, config):
533
+ super().__init__()
534
+ self.num_experts = config.num_experts
535
+ self.top_k = config.num_experts_per_tok
536
+ self.norm_topk_prob = config.norm_topk_prob
537
+ self.num_shared_experts = config.num_shared_experts
538
+ self.router_score_func = config.router_score_func
539
+ self.router_scaling_factor = config.router_scaling_factor
540
+
541
+ # gating
542
+ self.gate = nn.Linear(config.hidden_size, config.num_experts, bias=config.moe_gate_bias)
543
+ self.experts = nn.ModuleList(
544
+ [K2HorizonMLP(config, intermediate_size=config.moe_intermediate_size) for _ in range(self.num_experts)]
545
+ )
546
+
547
+ if config.num_shared_experts > 0:
548
+ self.shared_experts = K2HorizonMLP(
549
+ config=config,
550
+ intermediate_size=config.moe_intermediate_size * config.num_shared_experts)
551
+
552
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
553
+ """ """
554
+ residuals = hidden_states
555
+
556
+ batch_size, sequence_length, hidden_dim = hidden_states.shape
557
+ hidden_states = hidden_states.view(-1, hidden_dim)
558
+ # router_logits: (batch * sequence_length, n_experts)
559
+ # router_logits = self.gate(hidden_states)
560
+ router_logits = F.linear(hidden_states, self.gate.weight)
561
+
562
+ if self.router_score_func == "softmax":
563
+ routing_weights = F.softmax(router_logits, dim=1, dtype=torch.float)
564
+ else:
565
+ assert self.router_score_func == "sigmoid"
566
+ routing_weights = F.sigmoid(router_logits.to(torch.float32))
567
+
568
+ routing_weights_for_choice = routing_weights
569
+ if self.gate.bias is not None:
570
+ routing_weights_for_choice = routing_weights + self.gate.bias.to(routing_weights.dtype)
571
+
572
+ _, selected_experts = torch.topk(routing_weights_for_choice, self.top_k, dim=-1)
573
+ routing_weights = torch.gather(routing_weights, dim=-1, index=selected_experts)
574
+
575
+ if self.norm_topk_prob: # only diff with mixtral sparse moe block!
576
+ routing_weights /= routing_weights.sum(dim=-1, keepdim=True)
577
+ routing_weights = routing_weights * self.router_scaling_factor
578
+ # we cast back to the input dtype
579
+ routing_weights = routing_weights.to(hidden_states.dtype)
580
+
581
+ final_hidden_states = torch.zeros(
582
+ (batch_size * sequence_length, hidden_dim), dtype=hidden_states.dtype, device=hidden_states.device
583
+ )
584
+
585
+ # One hot encode the selected experts to create an expert mask
586
+ # this will be used to easily index which expert is going to be sollicitated
587
+ expert_mask = torch.nn.functional.one_hot(selected_experts, num_classes=self.num_experts).permute(2, 1, 0)
588
+
589
+ # Loop over all available experts in the model and perform the computation on each expert
590
+ expert_hit = torch.greater(expert_mask.sum(dim=(-1, -2)), 0).nonzero()
591
+ for expert_idx in expert_hit:
592
+ expert_layer = self.experts[expert_idx]
593
+ idx, top_x = torch.where(expert_mask[expert_idx].squeeze(0))
594
+
595
+ # Index the correct hidden states and compute the expert hidden state for
596
+ # the current expert. We need to make sure to multiply the output hidden
597
+ # states by `routing_weights` on the corresponding tokens (top-1 and top-2)
598
+ current_state = hidden_states[None, top_x].reshape(-1, hidden_dim)
599
+ current_hidden_states = expert_layer(current_state) * routing_weights[top_x, idx, None]
600
+
601
+ # However `index_add_` only support torch tensors for indexing so we'll use
602
+ # the `top_x` tensor here.
603
+ final_hidden_states.index_add_(0, top_x, current_hidden_states.to(hidden_states.dtype))
604
+ final_hidden_states = final_hidden_states.reshape(batch_size, sequence_length, hidden_dim)
605
+
606
+ if self.num_shared_experts > 0:
607
+ final_hidden_states = final_hidden_states + self.shared_experts(residuals)
608
+
609
+ return final_hidden_states, router_logits
610
+
611
+
612
+ # @use_kernel_forward_from_hub("RMSNorm")
613
+ class K2HorizonRMSNorm(nn.Module):
614
+ def __init__(self, hidden_size: int, n_groups: int, eps=1e-6):
615
+ """
616
+ K2HorizonRMSNorm is equivalent to T5LayerNorm
617
+ """
618
+ super().__init__()
619
+ self.n_groups = n_groups
620
+ self.hidden_size = hidden_size
621
+ assert hidden_size % n_groups == 0
622
+ self.weight = nn.Parameter(torch.ones(hidden_size))
623
+ self.variance_epsilon = eps
624
+
625
+ def forward(self, hidden_states):
626
+ input_dtype = hidden_states.dtype
627
+ hidden_states = hidden_states.to(torch.float32)
628
+
629
+ hidden_states = hidden_states.reshape(*hidden_states.shape[:-1], self.n_groups, -1)
630
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
631
+
632
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
633
+ hidden_states = hidden_states.reshape(*hidden_states.shape[:-2], -1)
634
+ hidden_states = self.weight * hidden_states
635
+
636
+ return hidden_states.to(input_dtype)
637
+
638
+ def extra_repr(self):
639
+ return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
640
+
641
+
642
+ class K2HorizonDecoderLayer(GradientCheckpointingLayer):
643
+ def __init__(self, config: K2HorizonConfig, layer_idx: int):
644
+ super().__init__()
645
+ self.hidden_size = config.hidden_size
646
+
647
+ is_sparse_layer = (layer_idx not in config.mlp_only_layers) and (
648
+ config.num_experts > 0 and (layer_idx + 1) % config.decoder_sparse_step == 0)
649
+
650
+ if is_sparse_layer and config.mova_num_experts > 0:
651
+ self.self_attn = K2HorizonMoVAAttention(config=config, layer_idx=layer_idx)
652
+ else:
653
+ self.self_attn = K2HorizonAttention(config, layer_idx)
654
+
655
+ if is_sparse_layer:
656
+ self.mlp = K2HorizonSparseMoeBlock(config)
657
+ else:
658
+ self.mlp = K2HorizonMLP(config, intermediate_size=config.intermediate_size)
659
+
660
+ assert config.hidden_size % config.layernorm_num_groups == 0
661
+ self.input_layernorm = K2HorizonRMSNorm(
662
+ hidden_size=config.hidden_size,
663
+ n_groups=config.layernorm_num_groups,
664
+ eps=config.rms_norm_eps)
665
+ self.post_attention_layernorm = K2HorizonRMSNorm(
666
+ hidden_size=config.hidden_size,
667
+ n_groups=config.layernorm_num_groups,
668
+ eps=config.rms_norm_eps)
669
+
670
+ @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
671
+ def forward(
672
+ self,
673
+ hidden_states: torch.Tensor,
674
+ position_embeddings: tuple[torch.Tensor, torch.Tensor],
675
+ attention_mask: Optional[torch.Tensor] = None,
676
+ position_ids: Optional[torch.LongTensor] = None,
677
+ past_key_values: Optional[Cache] = None,
678
+ cache_position: Optional[torch.LongTensor] = None,
679
+ **kwargs: Unpack[FlashAttentionKwargs],
680
+ ) -> torch.FloatTensor:
681
+ """
682
+ Args:
683
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
684
+ attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
685
+ `(batch, sequence_length)` where padding elements are indicated by 0.
686
+ output_attentions (`bool`, *optional*):
687
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
688
+ returned tensors for more detail.
689
+ output_router_logits (`bool`, *optional*):
690
+ Whether or not to return the logits of all the routers. They are useful for computing the router loss,
691
+ and should not be returned during inference.
692
+ use_cache (`bool`, *optional*):
693
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
694
+ (see `past_key_values`).
695
+ past_key_values (`Cache`, *optional*): cached past key and value projection states
696
+ cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
697
+ Indices depicting the position of the input sequence tokens in the sequence.
698
+ position_embeddings (`tuple[torch.FloatTensor, torch.FloatTensor]`, *optional*):
699
+ Tuple containing the cosine and sine positional embeddings of shape `(batch_size, seq_len, head_dim)`,
700
+ with `head_dim` being the embedding dimension of each attention head.
701
+ kwargs (`dict`, *optional*):
702
+ Arbitrary kwargs to be ignored, used for FSDP and other methods that injects code
703
+ into the model
704
+ """
705
+ residual = hidden_states
706
+ hidden_states = self.input_layernorm(hidden_states)
707
+
708
+ # Self Attention
709
+ hidden_states, _ = self.self_attn(
710
+ hidden_states=hidden_states,
711
+ position_embeddings=position_embeddings,
712
+ attention_mask=attention_mask,
713
+ position_ids=position_ids,
714
+ past_key_values=past_key_values,
715
+ cache_position=cache_position,
716
+ **kwargs,
717
+ )
718
+
719
+ hidden_states = residual + hidden_states
720
+
721
+ # Fully Connected
722
+ residual = hidden_states
723
+ hidden_states = self.post_attention_layernorm(hidden_states)
724
+ hidden_states = self.mlp(hidden_states)
725
+ # For the MoE layers, we need to unpack
726
+ if isinstance(hidden_states, tuple):
727
+ hidden_states, _ = hidden_states
728
+ hidden_states = residual + hidden_states
729
+
730
+ return hidden_states
731
+
732
+
733
+ class K2HorizonRotaryEmbedding(nn.Module):
734
+ inv_freq: torch.Tensor # fix linting for `register_buffer`
735
+
736
+ def __init__(self, config: K2HorizonConfig, device=None):
737
+ super().__init__()
738
+ self.max_seq_len_cached = config.max_position_embeddings
739
+ self.original_max_seq_len = config.max_position_embeddings
740
+
741
+ self.config = config
742
+
743
+ self.rope_type = self.config.rope_parameters["rope_type"]
744
+ rope_init_fn: Callable = self.compute_default_rope_parameters
745
+ if self.rope_type != "default":
746
+ rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
747
+ inv_freq, self.attention_scaling = rope_init_fn(self.config, device)
748
+
749
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
750
+ self.register_buffer("original_inv_freq", inv_freq.clone(), persistent=False)
751
+
752
+ @staticmethod
753
+ def compute_default_rope_parameters(
754
+ config: K2HorizonConfig | None = None,
755
+ device: Optional["torch.device"] = None,
756
+ seq_len: int | None = None,
757
+ ) -> tuple["torch.Tensor", float]:
758
+ """
759
+ Computes the inverse frequencies according to the original RoPE implementation
760
+ Args:
761
+ config ([`~transformers.PreTrainedConfig`]):
762
+ The model configuration.
763
+ device (`torch.device`):
764
+ The device to use for initialization of the inverse frequencies.
765
+ seq_len (`int`, *optional*):
766
+ The current sequence length. Unused for this type of RoPE.
767
+ Returns:
768
+ Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the
769
+ post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE).
770
+ """
771
+ base = config.rope_parameters["rope_theta"]
772
+ # dim = getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads
773
+ dim = (
774
+ config.rope_head_dim
775
+ if config.rope_head_dim is not None
776
+ else getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads
777
+ )
778
+
779
+ attention_factor = 1.0 # Unused in this type of RoPE
780
+
781
+ # Compute the inverse frequencies
782
+ inv_freq = 1.0 / (
783
+ base ** (torch.arange(0, dim, 2, dtype=torch.int64).to(device=device, dtype=torch.float) / dim)
784
+ )
785
+ return inv_freq, attention_factor
786
+
787
+ @torch.no_grad()
788
+ @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
789
+ def forward(self, x, position_ids):
790
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)
791
+ position_ids_expanded = position_ids[:, None, :].float()
792
+
793
+ device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
794
+ with maybe_autocast(device_type=device_type, enabled=False): # Force float32
795
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
796
+ emb = torch.cat((freqs, freqs), dim=-1)
797
+ cos = emb.cos() * self.attention_scaling
798
+ sin = emb.sin() * self.attention_scaling
799
+
800
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
801
+
802
+
803
+ @auto_docstring
804
+ class K2HorizonPreTrainedModel(PreTrainedModel):
805
+ config: K2HorizonConfig
806
+ base_model_prefix = "model"
807
+ supports_gradient_checkpointing = True
808
+ _no_split_modules = ["K2HorizonDecoderLayer"]
809
+ _skip_keys_device_placement = ["past_key_values"]
810
+ _supports_flash_attn = True
811
+ _supports_sdpa = True
812
+ _supports_flex_attn = True
813
+ _can_compile_fullgraph = False # MoE models don't work with torch.compile (`torch.where(condition)` not supported)
814
+ _supports_attention_backend = True
815
+ _can_record_outputs = {
816
+ "router_logits": OutputRecorder(K2HorizonSparseMoeBlock, index=1),
817
+ "hidden_states": K2HorizonDecoderLayer,
818
+ "attentions": K2HorizonAttention,
819
+ }
820
+
821
+
822
+ @auto_docstring
823
+ class K2HorizonModel(K2HorizonPreTrainedModel):
824
+ def __init__(self, config: K2HorizonConfig):
825
+ super().__init__(config)
826
+ # self.padding_idx = config.pad_token_id
827
+ self.padding_idx = getattr(config, "padding_idx", None)
828
+ self.vocab_size = config.vocab_size
829
+
830
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
831
+ self.layers = nn.ModuleList(
832
+ [K2HorizonDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
833
+ )
834
+
835
+ assert config.hidden_size % config.layernorm_num_groups == 0
836
+ self.norm = K2HorizonRMSNorm(
837
+ hidden_size=config.hidden_size,
838
+ n_groups=config.layernorm_num_groups,
839
+ eps=config.rms_norm_eps)
840
+
841
+ self.rotary_emb = K2HorizonRotaryEmbedding(config=config)
842
+ self.gradient_checkpointing = False
843
+
844
+ # Initialize weights and apply final processing
845
+ self.post_init()
846
+
847
+ @auto_docstring
848
+ def forward(
849
+ self,
850
+ input_ids: Optional[torch.LongTensor] = None,
851
+ attention_mask: Optional[torch.Tensor] = None,
852
+ position_ids: Optional[torch.LongTensor] = None,
853
+ past_key_values: Optional[Cache] = None,
854
+ inputs_embeds: Optional[torch.FloatTensor] = None,
855
+ use_cache: Optional[bool] = None,
856
+ cache_position: Optional[torch.LongTensor] = None,
857
+ **kwargs: Unpack[TransformersKwargs],
858
+ ) -> MoeModelOutputWithPast:
859
+ if (input_ids is None) ^ (inputs_embeds is not None):
860
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
861
+
862
+ if use_cache and past_key_values is None:
863
+ past_key_values = DynamicCache(config=self.config)
864
+
865
+ if inputs_embeds is None:
866
+ inputs_embeds = self.embed_tokens(input_ids)
867
+
868
+ if cache_position is None:
869
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
870
+ cache_position = torch.arange(
871
+ past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
872
+ )
873
+ if position_ids is None:
874
+ position_ids = cache_position.unsqueeze(0)
875
+
876
+ mask_function = create_causal_mask if self.config.sliding_window is None else create_sliding_window_causal_mask
877
+ causal_mask = mask_function(
878
+ config=self.config,
879
+ inputs_embeds=inputs_embeds,
880
+ attention_mask=attention_mask,
881
+ past_key_values=past_key_values,
882
+ position_ids=position_ids,
883
+ )
884
+
885
+ hidden_states = inputs_embeds
886
+
887
+ # create position embeddings to be shared across the decoder layers
888
+ position_embeddings = self.rotary_emb(hidden_states, position_ids)
889
+
890
+ for layer_idx, decoder_layer in enumerate(self.layers[: self.config.num_hidden_layers]):
891
+ hidden_states = decoder_layer(
892
+ hidden_states,
893
+ position_embeddings=position_embeddings,
894
+ attention_mask=causal_mask,
895
+ position_ids=position_ids,
896
+ past_key_values=past_key_values,
897
+ use_cache=use_cache,
898
+ cache_position=cache_position,
899
+ **kwargs,
900
+ )
901
+
902
+ hidden_states = self.norm(hidden_states)
903
+
904
+ return MoeModelOutputWithPast( # only diff with Mistral is the output type, we need MoE
905
+ last_hidden_state=hidden_states,
906
+ past_key_values=past_key_values,
907
+ )
908
+
909
+
910
+ def load_balancing_loss_func(
911
+ gate_logits: Union[torch.Tensor, tuple[torch.Tensor], None],
912
+ num_experts: Optional[int] = None,
913
+ top_k=2,
914
+ attention_mask: Optional[torch.Tensor] = None,
915
+ ) -> Union[torch.Tensor, int]:
916
+ r"""
917
+ Computes auxiliary load balancing loss as in Switch Transformer - implemented in Pytorch.
918
+
919
+ See Switch Transformer (https://huggingface.co/papers/2101.03961) for more details. This function implements the loss
920
+ function presented in equations (4) - (6) of the paper. It aims at penalizing cases where the routing between
921
+ experts is too unbalanced.
922
+
923
+ Args:
924
+ gate_logits:
925
+ Logits from the `gate`, should be a tuple of model.config.num_hidden_layers tensors of
926
+ shape [batch_size X sequence_length, num_experts].
927
+ num_experts:
928
+ Number of experts
929
+ top_k:
930
+ The number of experts to route per-token, can be also interpreted as the `top-k` routing
931
+ parameter.
932
+ attention_mask (`torch.Tensor`, *optional*):
933
+ The attention_mask used in forward function
934
+ shape [batch_size X sequence_length] if not None.
935
+
936
+ Returns:
937
+ The auxiliary loss.
938
+ """
939
+ if gate_logits is None or not isinstance(gate_logits, tuple):
940
+ return 0
941
+
942
+ if isinstance(gate_logits, tuple):
943
+ compute_device = gate_logits[0].device
944
+ concatenated_gate_logits = torch.cat([layer_gate.to(compute_device) for layer_gate in gate_logits], dim=0)
945
+
946
+ routing_weights = torch.nn.functional.softmax(concatenated_gate_logits, dim=-1)
947
+
948
+ _, selected_experts = torch.topk(routing_weights, top_k, dim=-1)
949
+
950
+ expert_mask = torch.nn.functional.one_hot(selected_experts, num_experts)
951
+
952
+ if attention_mask is None:
953
+ # Compute the percentage of tokens routed to each experts
954
+ tokens_per_expert = torch.mean(expert_mask.float(), dim=0)
955
+
956
+ # Compute the average probability of routing to these experts
957
+ router_prob_per_expert = torch.mean(routing_weights, dim=0)
958
+ else:
959
+ batch_size, sequence_length = attention_mask.shape
960
+ num_hidden_layers = concatenated_gate_logits.shape[0] // (batch_size * sequence_length)
961
+
962
+ # Compute the mask that masks all padding tokens as 0 with the same shape of expert_mask
963
+ expert_attention_mask = (
964
+ attention_mask[None, :, :, None, None]
965
+ .expand((num_hidden_layers, batch_size, sequence_length, top_k, num_experts))
966
+ .reshape(-1, top_k, num_experts)
967
+ .to(compute_device)
968
+ )
969
+
970
+ # Compute the percentage of tokens routed to each experts
971
+ tokens_per_expert = torch.sum(expert_mask.float() * expert_attention_mask, dim=0) / torch.sum(
972
+ expert_attention_mask, dim=0
973
+ )
974
+
975
+ # Compute the mask that masks all padding tokens as 0 with the same shape of tokens_per_expert
976
+ router_per_expert_attention_mask = (
977
+ attention_mask[None, :, :, None]
978
+ .expand((num_hidden_layers, batch_size, sequence_length, num_experts))
979
+ .reshape(-1, num_experts)
980
+ .to(compute_device)
981
+ )
982
+
983
+ # Compute the average probability of routing to these experts
984
+ router_prob_per_expert = torch.sum(routing_weights * router_per_expert_attention_mask, dim=0) / torch.sum(
985
+ router_per_expert_attention_mask, dim=0
986
+ )
987
+
988
+ overall_loss = torch.sum(tokens_per_expert * router_prob_per_expert.unsqueeze(0))
989
+ return overall_loss * num_experts
990
+
991
+
992
+ @auto_docstring
993
+ class K2HorizonForCausalLM(K2HorizonPreTrainedModel, GenerationMixin):
994
+ # _tied_weights_keys = ["lm_head.weight"]
995
+ # _tp_plan = {"lm_head": "colwise_rep"}
996
+ # _pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
997
+
998
+ def __init__(self, config):
999
+ super().__init__(config)
1000
+ self.model = K2HorizonModel(config)
1001
+ self.vocab_size = config.vocab_size
1002
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1003
+ self.router_aux_loss_coef = config.router_aux_loss_coef
1004
+ self.num_experts = config.num_experts
1005
+ self.num_experts_per_tok = config.num_experts_per_tok
1006
+
1007
+ # Initialize weights and apply final processing
1008
+ self.post_init()
1009
+
1010
+ @can_return_tuple
1011
+ @auto_docstring
1012
+ def forward(
1013
+ self,
1014
+ input_ids: Optional[torch.LongTensor] = None,
1015
+ attention_mask: Optional[torch.Tensor] = None,
1016
+ position_ids: Optional[torch.LongTensor] = None,
1017
+ past_key_values: Optional[Cache] = None,
1018
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1019
+ labels: Optional[torch.LongTensor] = None,
1020
+ use_cache: Optional[bool] = None,
1021
+ output_router_logits: Optional[bool] = None,
1022
+ cache_position: Optional[torch.LongTensor] = None,
1023
+ logits_to_keep: Union[int, torch.Tensor] = 0,
1024
+ **kwargs: Unpack[TransformersKwargs],
1025
+ ) -> MoeCausalLMOutputWithPast:
1026
+ r"""
1027
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1028
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1029
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1030
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1031
+
1032
+ Example:
1033
+
1034
+ ```python
1035
+ >>> from transformers import AutoTokenizer, K2HorizonForCausalLM
1036
+
1037
+ >>> model = K2HorizonForCausalLM.from_pretrained("Qwen/Qwen3-MoE-15B-A2B")
1038
+ >>> tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen3-MoE-15B-A2B")
1039
+
1040
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
1041
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1042
+
1043
+ >>> # Generate
1044
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1045
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1046
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
1047
+ ```"""
1048
+
1049
+ output_router_logits = (
1050
+ output_router_logits if output_router_logits is not None else self.config.output_router_logits
1051
+ )
1052
+
1053
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1054
+ outputs: MoeModelOutputWithPast = self.model(
1055
+ input_ids=input_ids,
1056
+ attention_mask=attention_mask,
1057
+ position_ids=position_ids,
1058
+ past_key_values=past_key_values,
1059
+ inputs_embeds=inputs_embeds,
1060
+ use_cache=use_cache,
1061
+ output_router_logits=output_router_logits,
1062
+ cache_position=cache_position,
1063
+ **kwargs,
1064
+ )
1065
+
1066
+ hidden_states = outputs.last_hidden_state
1067
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
1068
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
1069
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
1070
+
1071
+ loss = None
1072
+ if labels is not None:
1073
+ loss = self.loss_function(logits, labels, self.vocab_size, **kwargs)
1074
+
1075
+ aux_loss = None
1076
+ if output_router_logits:
1077
+ aux_loss = load_balancing_loss_func(
1078
+ outputs.router_logits,
1079
+ self.num_experts,
1080
+ self.num_experts_per_tok,
1081
+ attention_mask,
1082
+ )
1083
+ if labels is not None:
1084
+ loss += self.router_aux_loss_coef * aux_loss.to(loss.device) # make sure to reside in the same device
1085
+
1086
+ return MoeCausalLMOutputWithPast(
1087
+ loss=loss,
1088
+ aux_loss=aux_loss,
1089
+ logits=logits,
1090
+ past_key_values=outputs.past_key_values,
1091
+ hidden_states=outputs.hidden_states,
1092
+ attentions=outputs.attentions,
1093
+ router_logits=outputs.router_logits,
1094
+ )
1095
+
1096
+
1097
+ class K2HorizonForSequenceClassification(GenericForSequenceClassification, K2HorizonPreTrainedModel):
1098
+ pass
1099
+
1100
+
1101
+ class K2HorizonForTokenClassification(GenericForTokenClassification, K2HorizonPreTrainedModel):
1102
+ pass
1103
+
1104
+
1105
+ class K2HorizonForQuestionAnswering(GenericForQuestionAnswering, K2HorizonPreTrainedModel):
1106
+ base_model_prefix = "transformer" # For BC, where `transformer` was used instead of `model`
1107
+
1108
+
1109
+ __all__ = [
1110
+ "K2HorizonForCausalLM",
1111
+ "K2HorizonForQuestionAnswering",
1112
+ "K2HorizonModel",
1113
+ "K2HorizonPreTrainedModel",
1114
+ "K2HorizonForSequenceClassification",
1115
+ "K2HorizonForTokenClassification",
1116
+ ]
pointer_head.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9158178c1d1b156062105ed02369f616f106f592ed6a32ed000cd46af614aaf1
3
+ size 3160520
requirements.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ torch>=2.6
2
+ transformers>=5.17,<6
3
+ safetensors>=0.8
4
+ fastapi>=0.141
5
+ uvicorn>=0.53
special_tokens_map.json ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ {
2
+ "bos_token": "<|begin_of_text|>",
3
+ "eos_token": "<|endoftext|>",
4
+ "pad_token": "reserved_special_token_205"
5
+ }
tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
tokenizer_config.json ADDED
@@ -0,0 +1,2075 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "added_tokens_decoder": {
3
+ "0": {
4
+ "content": "<|begin_of_text|>",
5
+ "lstrip": false,
6
+ "normalized": false,
7
+ "rstrip": false,
8
+ "single_word": false,
9
+ "special": true
10
+ },
11
+ "1": {
12
+ "content": "<|endoftext|>",
13
+ "lstrip": false,
14
+ "normalized": false,
15
+ "rstrip": false,
16
+ "single_word": false,
17
+ "special": true
18
+ },
19
+ "64000": {
20
+ "content": "<|fim_prefix|>",
21
+ "lstrip": false,
22
+ "normalized": false,
23
+ "rstrip": false,
24
+ "single_word": false,
25
+ "special": true
26
+ },
27
+ "64001": {
28
+ "content": "<|fim_middle|>",
29
+ "lstrip": false,
30
+ "normalized": false,
31
+ "rstrip": false,
32
+ "single_word": false,
33
+ "special": true
34
+ },
35
+ "64002": {
36
+ "content": "<|fim_suffix|>",
37
+ "lstrip": false,
38
+ "normalized": false,
39
+ "rstrip": false,
40
+ "single_word": false,
41
+ "special": true
42
+ },
43
+ "64003": {
44
+ "content": "<|fim_pad|>",
45
+ "lstrip": false,
46
+ "normalized": false,
47
+ "rstrip": false,
48
+ "single_word": false,
49
+ "special": true
50
+ },
51
+ "64004": {
52
+ "content": "<|filename|>",
53
+ "lstrip": false,
54
+ "normalized": false,
55
+ "rstrip": false,
56
+ "single_word": false,
57
+ "special": true
58
+ },
59
+ "64005": {
60
+ "content": "<|gh_stars|>",
61
+ "lstrip": false,
62
+ "normalized": false,
63
+ "rstrip": false,
64
+ "single_word": false,
65
+ "special": true
66
+ },
67
+ "64006": {
68
+ "content": "<|issue_start|>",
69
+ "lstrip": false,
70
+ "normalized": false,
71
+ "rstrip": false,
72
+ "single_word": false,
73
+ "special": true
74
+ },
75
+ "64007": {
76
+ "content": "<|issue_comment|>",
77
+ "lstrip": false,
78
+ "normalized": false,
79
+ "rstrip": false,
80
+ "single_word": false,
81
+ "special": true
82
+ },
83
+ "64008": {
84
+ "content": "<|issue_closed|>",
85
+ "lstrip": false,
86
+ "normalized": false,
87
+ "rstrip": false,
88
+ "single_word": false,
89
+ "special": true
90
+ },
91
+ "64009": {
92
+ "content": "<|jupyter_start|>",
93
+ "lstrip": false,
94
+ "normalized": false,
95
+ "rstrip": false,
96
+ "single_word": false,
97
+ "special": true
98
+ },
99
+ "64010": {
100
+ "content": "<|jupyter_text|>",
101
+ "lstrip": false,
102
+ "normalized": false,
103
+ "rstrip": false,
104
+ "single_word": false,
105
+ "special": true
106
+ },
107
+ "64011": {
108
+ "content": "<|jupyter_code|>",
109
+ "lstrip": false,
110
+ "normalized": false,
111
+ "rstrip": false,
112
+ "single_word": false,
113
+ "special": true
114
+ },
115
+ "64012": {
116
+ "content": "<|jupyter_output|>",
117
+ "lstrip": false,
118
+ "normalized": false,
119
+ "rstrip": false,
120
+ "single_word": false,
121
+ "special": true
122
+ },
123
+ "64013": {
124
+ "content": "<|empty_output|>",
125
+ "lstrip": false,
126
+ "normalized": false,
127
+ "rstrip": false,
128
+ "single_word": false,
129
+ "special": true
130
+ },
131
+ "64014": {
132
+ "content": "<|commit_before|>",
133
+ "lstrip": false,
134
+ "normalized": false,
135
+ "rstrip": false,
136
+ "single_word": false,
137
+ "special": true
138
+ },
139
+ "64015": {
140
+ "content": "<|commit_msg|>",
141
+ "lstrip": false,
142
+ "normalized": false,
143
+ "rstrip": false,
144
+ "single_word": false,
145
+ "special": true
146
+ },
147
+ "64016": {
148
+ "content": "<|commit_after|>",
149
+ "lstrip": false,
150
+ "normalized": false,
151
+ "rstrip": false,
152
+ "single_word": false,
153
+ "special": true
154
+ },
155
+ "64017": {
156
+ "content": "<|reponame|>",
157
+ "lstrip": false,
158
+ "normalized": false,
159
+ "rstrip": false,
160
+ "single_word": false,
161
+ "special": true
162
+ },
163
+ "64018": {
164
+ "content": "<|ifm|im_start|>",
165
+ "lstrip": false,
166
+ "normalized": false,
167
+ "rstrip": false,
168
+ "single_word": false,
169
+ "special": true
170
+ },
171
+ "64019": {
172
+ "content": "<|ifm|im_end|>",
173
+ "lstrip": false,
174
+ "normalized": false,
175
+ "rstrip": false,
176
+ "single_word": false,
177
+ "special": true
178
+ },
179
+ "64020": {
180
+ "content": "<|sys_start|>",
181
+ "lstrip": false,
182
+ "normalized": false,
183
+ "rstrip": false,
184
+ "single_word": false,
185
+ "special": true
186
+ },
187
+ "64021": {
188
+ "content": "<|sys_end|>",
189
+ "lstrip": false,
190
+ "normalized": false,
191
+ "rstrip": false,
192
+ "single_word": false,
193
+ "special": true
194
+ },
195
+ "64022": {
196
+ "content": "<|start_header_id|>",
197
+ "lstrip": false,
198
+ "normalized": false,
199
+ "rstrip": false,
200
+ "single_word": false,
201
+ "special": true
202
+ },
203
+ "64023": {
204
+ "content": "<|end_header_id|>",
205
+ "lstrip": false,
206
+ "normalized": false,
207
+ "rstrip": false,
208
+ "single_word": false,
209
+ "special": true
210
+ },
211
+ "64024": {
212
+ "content": "<|eot_id|>",
213
+ "lstrip": false,
214
+ "normalized": false,
215
+ "rstrip": false,
216
+ "single_word": false,
217
+ "special": true
218
+ },
219
+ "64025": {
220
+ "content": "<|begin_of_thought|>",
221
+ "lstrip": false,
222
+ "normalized": false,
223
+ "rstrip": false,
224
+ "single_word": false,
225
+ "special": true
226
+ },
227
+ "64026": {
228
+ "content": "<|end_of_thought|>",
229
+ "lstrip": false,
230
+ "normalized": false,
231
+ "rstrip": false,
232
+ "single_word": false,
233
+ "special": true
234
+ },
235
+ "64027": {
236
+ "content": "<|begin_of_solution|>",
237
+ "lstrip": false,
238
+ "normalized": false,
239
+ "rstrip": false,
240
+ "single_word": false,
241
+ "special": true
242
+ },
243
+ "64028": {
244
+ "content": "<|end_of_solution|>",
245
+ "lstrip": false,
246
+ "normalized": false,
247
+ "rstrip": false,
248
+ "single_word": false,
249
+ "special": true
250
+ },
251
+ "64029": {
252
+ "content": "<ifm|think>",
253
+ "lstrip": false,
254
+ "normalized": false,
255
+ "rstrip": false,
256
+ "single_word": false,
257
+ "special": false
258
+ },
259
+ "64030": {
260
+ "content": "</ifm|think>",
261
+ "lstrip": false,
262
+ "normalized": false,
263
+ "rstrip": false,
264
+ "single_word": false,
265
+ "special": false
266
+ },
267
+ "64031": {
268
+ "content": "<image>",
269
+ "lstrip": false,
270
+ "normalized": false,
271
+ "rstrip": false,
272
+ "single_word": false,
273
+ "special": true
274
+ },
275
+ "64032": {
276
+ "content": "</image>",
277
+ "lstrip": false,
278
+ "normalized": false,
279
+ "rstrip": false,
280
+ "single_word": false,
281
+ "special": true
282
+ },
283
+ "64033": {
284
+ "content": "<video>",
285
+ "lstrip": false,
286
+ "normalized": false,
287
+ "rstrip": false,
288
+ "single_word": false,
289
+ "special": true
290
+ },
291
+ "64034": {
292
+ "content": "</video>",
293
+ "lstrip": false,
294
+ "normalized": false,
295
+ "rstrip": false,
296
+ "single_word": false,
297
+ "special": true
298
+ },
299
+ "64035": {
300
+ "content": "<audio>",
301
+ "lstrip": false,
302
+ "normalized": false,
303
+ "rstrip": false,
304
+ "single_word": false,
305
+ "special": true
306
+ },
307
+ "64036": {
308
+ "content": "</audio>",
309
+ "lstrip": false,
310
+ "normalized": false,
311
+ "rstrip": false,
312
+ "single_word": false,
313
+ "special": true
314
+ },
315
+ "64037": {
316
+ "content": "<|user_start|>",
317
+ "lstrip": false,
318
+ "normalized": false,
319
+ "rstrip": false,
320
+ "single_word": false,
321
+ "special": true
322
+ },
323
+ "64038": {
324
+ "content": "<|user_end|>",
325
+ "lstrip": false,
326
+ "normalized": false,
327
+ "rstrip": false,
328
+ "single_word": false,
329
+ "special": true
330
+ },
331
+ "64039": {
332
+ "content": "<|assistant_start|>",
333
+ "lstrip": false,
334
+ "normalized": false,
335
+ "rstrip": false,
336
+ "single_word": false,
337
+ "special": true
338
+ },
339
+ "64040": {
340
+ "content": "<|assistant_end|>",
341
+ "lstrip": false,
342
+ "normalized": false,
343
+ "rstrip": false,
344
+ "single_word": false,
345
+ "special": true
346
+ },
347
+ "64041": {
348
+ "content": "<ifm|tools>",
349
+ "lstrip": false,
350
+ "normalized": false,
351
+ "rstrip": false,
352
+ "single_word": false,
353
+ "special": false
354
+ },
355
+ "64042": {
356
+ "content": "</ifm|tools>",
357
+ "lstrip": false,
358
+ "normalized": false,
359
+ "rstrip": false,
360
+ "single_word": false,
361
+ "special": false
362
+ },
363
+ "64043": {
364
+ "content": "<ifm|tool_call>",
365
+ "lstrip": false,
366
+ "normalized": false,
367
+ "rstrip": false,
368
+ "single_word": false,
369
+ "special": false
370
+ },
371
+ "64044": {
372
+ "content": "</ifm|tool_call>",
373
+ "lstrip": false,
374
+ "normalized": false,
375
+ "rstrip": false,
376
+ "single_word": false,
377
+ "special": false
378
+ },
379
+ "64045": {
380
+ "content": "<tool_response>",
381
+ "lstrip": false,
382
+ "normalized": false,
383
+ "rstrip": false,
384
+ "single_word": false,
385
+ "special": false
386
+ },
387
+ "64046": {
388
+ "content": "</tool_response>",
389
+ "lstrip": false,
390
+ "normalized": false,
391
+ "rstrip": false,
392
+ "single_word": false,
393
+ "special": false
394
+ },
395
+ "64047": {
396
+ "content": "<|table_start|>",
397
+ "lstrip": false,
398
+ "normalized": false,
399
+ "rstrip": false,
400
+ "single_word": false,
401
+ "special": true
402
+ },
403
+ "64048": {
404
+ "content": "<|table_row|>",
405
+ "lstrip": false,
406
+ "normalized": false,
407
+ "rstrip": false,
408
+ "single_word": false,
409
+ "special": true
410
+ },
411
+ "64049": {
412
+ "content": "<|table_end|>",
413
+ "lstrip": false,
414
+ "normalized": false,
415
+ "rstrip": false,
416
+ "single_word": false,
417
+ "special": true
418
+ },
419
+ "64050": {
420
+ "content": "<ifm|think_fast>",
421
+ "lstrip": false,
422
+ "normalized": false,
423
+ "rstrip": false,
424
+ "single_word": false,
425
+ "special": false
426
+ },
427
+ "64051": {
428
+ "content": "</ifm|think_fast>",
429
+ "lstrip": false,
430
+ "normalized": false,
431
+ "rstrip": false,
432
+ "single_word": false,
433
+ "special": false
434
+ },
435
+ "64052": {
436
+ "content": "<ifm|think_faster>",
437
+ "lstrip": false,
438
+ "normalized": false,
439
+ "rstrip": false,
440
+ "single_word": false,
441
+ "special": false
442
+ },
443
+ "64053": {
444
+ "content": "</ifm|think_faster>",
445
+ "lstrip": false,
446
+ "normalized": false,
447
+ "rstrip": false,
448
+ "single_word": false,
449
+ "special": false
450
+ },
451
+ "64054": {
452
+ "content": "<ifm|tool_calls>",
453
+ "lstrip": false,
454
+ "normalized": false,
455
+ "rstrip": false,
456
+ "single_word": false,
457
+ "special": false
458
+ },
459
+ "64055": {
460
+ "content": "</ifm|tool_calls>",
461
+ "lstrip": false,
462
+ "normalized": false,
463
+ "rstrip": false,
464
+ "single_word": false,
465
+ "special": false
466
+ },
467
+ "64056": {
468
+ "content": "<ifm|arg_key>",
469
+ "lstrip": false,
470
+ "normalized": false,
471
+ "rstrip": false,
472
+ "single_word": false,
473
+ "special": false
474
+ },
475
+ "64057": {
476
+ "content": "</ifm|arg_key>",
477
+ "lstrip": false,
478
+ "normalized": false,
479
+ "rstrip": false,
480
+ "single_word": false,
481
+ "special": false
482
+ },
483
+ "64058": {
484
+ "content": "<ifm|arg_type>",
485
+ "lstrip": false,
486
+ "normalized": false,
487
+ "rstrip": false,
488
+ "single_word": false,
489
+ "special": false
490
+ },
491
+ "64059": {
492
+ "content": "</ifm|arg_type>",
493
+ "lstrip": false,
494
+ "normalized": false,
495
+ "rstrip": false,
496
+ "single_word": false,
497
+ "special": false
498
+ },
499
+ "64060": {
500
+ "content": "<ifm|arg_value>",
501
+ "lstrip": false,
502
+ "normalized": false,
503
+ "rstrip": false,
504
+ "single_word": false,
505
+ "special": false
506
+ },
507
+ "64061": {
508
+ "content": "</ifm|arg_value>",
509
+ "lstrip": false,
510
+ "normalized": false,
511
+ "rstrip": false,
512
+ "single_word": false,
513
+ "special": false
514
+ },
515
+ "64062": {
516
+ "content": "reserved_special_token_12",
517
+ "lstrip": false,
518
+ "normalized": false,
519
+ "rstrip": false,
520
+ "single_word": false,
521
+ "special": true
522
+ },
523
+ "64063": {
524
+ "content": "reserved_special_token_13",
525
+ "lstrip": false,
526
+ "normalized": false,
527
+ "rstrip": false,
528
+ "single_word": false,
529
+ "special": true
530
+ },
531
+ "64064": {
532
+ "content": "reserved_special_token_14",
533
+ "lstrip": false,
534
+ "normalized": false,
535
+ "rstrip": false,
536
+ "single_word": false,
537
+ "special": true
538
+ },
539
+ "64065": {
540
+ "content": "reserved_special_token_15",
541
+ "lstrip": false,
542
+ "normalized": false,
543
+ "rstrip": false,
544
+ "single_word": false,
545
+ "special": true
546
+ },
547
+ "64066": {
548
+ "content": "reserved_special_token_16",
549
+ "lstrip": false,
550
+ "normalized": false,
551
+ "rstrip": false,
552
+ "single_word": false,
553
+ "special": true
554
+ },
555
+ "64067": {
556
+ "content": "reserved_special_token_17",
557
+ "lstrip": false,
558
+ "normalized": false,
559
+ "rstrip": false,
560
+ "single_word": false,
561
+ "special": true
562
+ },
563
+ "64068": {
564
+ "content": "reserved_special_token_18",
565
+ "lstrip": false,
566
+ "normalized": false,
567
+ "rstrip": false,
568
+ "single_word": false,
569
+ "special": true
570
+ },
571
+ "64069": {
572
+ "content": "reserved_special_token_19",
573
+ "lstrip": false,
574
+ "normalized": false,
575
+ "rstrip": false,
576
+ "single_word": false,
577
+ "special": true
578
+ },
579
+ "64070": {
580
+ "content": "reserved_special_token_20",
581
+ "lstrip": false,
582
+ "normalized": false,
583
+ "rstrip": false,
584
+ "single_word": false,
585
+ "special": true
586
+ },
587
+ "64071": {
588
+ "content": "reserved_special_token_21",
589
+ "lstrip": false,
590
+ "normalized": false,
591
+ "rstrip": false,
592
+ "single_word": false,
593
+ "special": true
594
+ },
595
+ "64072": {
596
+ "content": "reserved_special_token_22",
597
+ "lstrip": false,
598
+ "normalized": false,
599
+ "rstrip": false,
600
+ "single_word": false,
601
+ "special": true
602
+ },
603
+ "64073": {
604
+ "content": "reserved_special_token_23",
605
+ "lstrip": false,
606
+ "normalized": false,
607
+ "rstrip": false,
608
+ "single_word": false,
609
+ "special": true
610
+ },
611
+ "64074": {
612
+ "content": "reserved_special_token_24",
613
+ "lstrip": false,
614
+ "normalized": false,
615
+ "rstrip": false,
616
+ "single_word": false,
617
+ "special": true
618
+ },
619
+ "64075": {
620
+ "content": "reserved_special_token_25",
621
+ "lstrip": false,
622
+ "normalized": false,
623
+ "rstrip": false,
624
+ "single_word": false,
625
+ "special": true
626
+ },
627
+ "64076": {
628
+ "content": "reserved_special_token_26",
629
+ "lstrip": false,
630
+ "normalized": false,
631
+ "rstrip": false,
632
+ "single_word": false,
633
+ "special": true
634
+ },
635
+ "64077": {
636
+ "content": "reserved_special_token_27",
637
+ "lstrip": false,
638
+ "normalized": false,
639
+ "rstrip": false,
640
+ "single_word": false,
641
+ "special": true
642
+ },
643
+ "64078": {
644
+ "content": "reserved_special_token_28",
645
+ "lstrip": false,
646
+ "normalized": false,
647
+ "rstrip": false,
648
+ "single_word": false,
649
+ "special": true
650
+ },
651
+ "64079": {
652
+ "content": "reserved_special_token_29",
653
+ "lstrip": false,
654
+ "normalized": false,
655
+ "rstrip": false,
656
+ "single_word": false,
657
+ "special": true
658
+ },
659
+ "64080": {
660
+ "content": "reserved_special_token_30",
661
+ "lstrip": false,
662
+ "normalized": false,
663
+ "rstrip": false,
664
+ "single_word": false,
665
+ "special": true
666
+ },
667
+ "64081": {
668
+ "content": "reserved_special_token_31",
669
+ "lstrip": false,
670
+ "normalized": false,
671
+ "rstrip": false,
672
+ "single_word": false,
673
+ "special": true
674
+ },
675
+ "64082": {
676
+ "content": "reserved_special_token_32",
677
+ "lstrip": false,
678
+ "normalized": false,
679
+ "rstrip": false,
680
+ "single_word": false,
681
+ "special": true
682
+ },
683
+ "64083": {
684
+ "content": "reserved_special_token_33",
685
+ "lstrip": false,
686
+ "normalized": false,
687
+ "rstrip": false,
688
+ "single_word": false,
689
+ "special": true
690
+ },
691
+ "64084": {
692
+ "content": "reserved_special_token_34",
693
+ "lstrip": false,
694
+ "normalized": false,
695
+ "rstrip": false,
696
+ "single_word": false,
697
+ "special": true
698
+ },
699
+ "64085": {
700
+ "content": "reserved_special_token_35",
701
+ "lstrip": false,
702
+ "normalized": false,
703
+ "rstrip": false,
704
+ "single_word": false,
705
+ "special": true
706
+ },
707
+ "64086": {
708
+ "content": "reserved_special_token_36",
709
+ "lstrip": false,
710
+ "normalized": false,
711
+ "rstrip": false,
712
+ "single_word": false,
713
+ "special": true
714
+ },
715
+ "64087": {
716
+ "content": "reserved_special_token_37",
717
+ "lstrip": false,
718
+ "normalized": false,
719
+ "rstrip": false,
720
+ "single_word": false,
721
+ "special": true
722
+ },
723
+ "64088": {
724
+ "content": "reserved_special_token_38",
725
+ "lstrip": false,
726
+ "normalized": false,
727
+ "rstrip": false,
728
+ "single_word": false,
729
+ "special": true
730
+ },
731
+ "64089": {
732
+ "content": "reserved_special_token_39",
733
+ "lstrip": false,
734
+ "normalized": false,
735
+ "rstrip": false,
736
+ "single_word": false,
737
+ "special": true
738
+ },
739
+ "64090": {
740
+ "content": "reserved_special_token_40",
741
+ "lstrip": false,
742
+ "normalized": false,
743
+ "rstrip": false,
744
+ "single_word": false,
745
+ "special": true
746
+ },
747
+ "64091": {
748
+ "content": "reserved_special_token_41",
749
+ "lstrip": false,
750
+ "normalized": false,
751
+ "rstrip": false,
752
+ "single_word": false,
753
+ "special": true
754
+ },
755
+ "64092": {
756
+ "content": "reserved_special_token_42",
757
+ "lstrip": false,
758
+ "normalized": false,
759
+ "rstrip": false,
760
+ "single_word": false,
761
+ "special": true
762
+ },
763
+ "64093": {
764
+ "content": "reserved_special_token_43",
765
+ "lstrip": false,
766
+ "normalized": false,
767
+ "rstrip": false,
768
+ "single_word": false,
769
+ "special": true
770
+ },
771
+ "64094": {
772
+ "content": "reserved_special_token_44",
773
+ "lstrip": false,
774
+ "normalized": false,
775
+ "rstrip": false,
776
+ "single_word": false,
777
+ "special": true
778
+ },
779
+ "64095": {
780
+ "content": "reserved_special_token_45",
781
+ "lstrip": false,
782
+ "normalized": false,
783
+ "rstrip": false,
784
+ "single_word": false,
785
+ "special": true
786
+ },
787
+ "64096": {
788
+ "content": "reserved_special_token_46",
789
+ "lstrip": false,
790
+ "normalized": false,
791
+ "rstrip": false,
792
+ "single_word": false,
793
+ "special": true
794
+ },
795
+ "64097": {
796
+ "content": "reserved_special_token_47",
797
+ "lstrip": false,
798
+ "normalized": false,
799
+ "rstrip": false,
800
+ "single_word": false,
801
+ "special": true
802
+ },
803
+ "64098": {
804
+ "content": "reserved_special_token_48",
805
+ "lstrip": false,
806
+ "normalized": false,
807
+ "rstrip": false,
808
+ "single_word": false,
809
+ "special": true
810
+ },
811
+ "64099": {
812
+ "content": "reserved_special_token_49",
813
+ "lstrip": false,
814
+ "normalized": false,
815
+ "rstrip": false,
816
+ "single_word": false,
817
+ "special": true
818
+ },
819
+ "64100": {
820
+ "content": "reserved_special_token_50",
821
+ "lstrip": false,
822
+ "normalized": false,
823
+ "rstrip": false,
824
+ "single_word": false,
825
+ "special": true
826
+ },
827
+ "64101": {
828
+ "content": "reserved_special_token_51",
829
+ "lstrip": false,
830
+ "normalized": false,
831
+ "rstrip": false,
832
+ "single_word": false,
833
+ "special": true
834
+ },
835
+ "64102": {
836
+ "content": "reserved_special_token_52",
837
+ "lstrip": false,
838
+ "normalized": false,
839
+ "rstrip": false,
840
+ "single_word": false,
841
+ "special": true
842
+ },
843
+ "64103": {
844
+ "content": "reserved_special_token_53",
845
+ "lstrip": false,
846
+ "normalized": false,
847
+ "rstrip": false,
848
+ "single_word": false,
849
+ "special": true
850
+ },
851
+ "64104": {
852
+ "content": "reserved_special_token_54",
853
+ "lstrip": false,
854
+ "normalized": false,
855
+ "rstrip": false,
856
+ "single_word": false,
857
+ "special": true
858
+ },
859
+ "64105": {
860
+ "content": "reserved_special_token_55",
861
+ "lstrip": false,
862
+ "normalized": false,
863
+ "rstrip": false,
864
+ "single_word": false,
865
+ "special": true
866
+ },
867
+ "64106": {
868
+ "content": "reserved_special_token_56",
869
+ "lstrip": false,
870
+ "normalized": false,
871
+ "rstrip": false,
872
+ "single_word": false,
873
+ "special": true
874
+ },
875
+ "64107": {
876
+ "content": "reserved_special_token_57",
877
+ "lstrip": false,
878
+ "normalized": false,
879
+ "rstrip": false,
880
+ "single_word": false,
881
+ "special": true
882
+ },
883
+ "64108": {
884
+ "content": "reserved_special_token_58",
885
+ "lstrip": false,
886
+ "normalized": false,
887
+ "rstrip": false,
888
+ "single_word": false,
889
+ "special": true
890
+ },
891
+ "64109": {
892
+ "content": "reserved_special_token_59",
893
+ "lstrip": false,
894
+ "normalized": false,
895
+ "rstrip": false,
896
+ "single_word": false,
897
+ "special": true
898
+ },
899
+ "64110": {
900
+ "content": "reserved_special_token_60",
901
+ "lstrip": false,
902
+ "normalized": false,
903
+ "rstrip": false,
904
+ "single_word": false,
905
+ "special": true
906
+ },
907
+ "64111": {
908
+ "content": "reserved_special_token_61",
909
+ "lstrip": false,
910
+ "normalized": false,
911
+ "rstrip": false,
912
+ "single_word": false,
913
+ "special": true
914
+ },
915
+ "64112": {
916
+ "content": "reserved_special_token_62",
917
+ "lstrip": false,
918
+ "normalized": false,
919
+ "rstrip": false,
920
+ "single_word": false,
921
+ "special": true
922
+ },
923
+ "64113": {
924
+ "content": "reserved_special_token_63",
925
+ "lstrip": false,
926
+ "normalized": false,
927
+ "rstrip": false,
928
+ "single_word": false,
929
+ "special": true
930
+ },
931
+ "64114": {
932
+ "content": "reserved_special_token_64",
933
+ "lstrip": false,
934
+ "normalized": false,
935
+ "rstrip": false,
936
+ "single_word": false,
937
+ "special": true
938
+ },
939
+ "64115": {
940
+ "content": "reserved_special_token_65",
941
+ "lstrip": false,
942
+ "normalized": false,
943
+ "rstrip": false,
944
+ "single_word": false,
945
+ "special": true
946
+ },
947
+ "64116": {
948
+ "content": "reserved_special_token_66",
949
+ "lstrip": false,
950
+ "normalized": false,
951
+ "rstrip": false,
952
+ "single_word": false,
953
+ "special": true
954
+ },
955
+ "64117": {
956
+ "content": "reserved_special_token_67",
957
+ "lstrip": false,
958
+ "normalized": false,
959
+ "rstrip": false,
960
+ "single_word": false,
961
+ "special": true
962
+ },
963
+ "64118": {
964
+ "content": "reserved_special_token_68",
965
+ "lstrip": false,
966
+ "normalized": false,
967
+ "rstrip": false,
968
+ "single_word": false,
969
+ "special": true
970
+ },
971
+ "64119": {
972
+ "content": "reserved_special_token_69",
973
+ "lstrip": false,
974
+ "normalized": false,
975
+ "rstrip": false,
976
+ "single_word": false,
977
+ "special": true
978
+ },
979
+ "64120": {
980
+ "content": "reserved_special_token_70",
981
+ "lstrip": false,
982
+ "normalized": false,
983
+ "rstrip": false,
984
+ "single_word": false,
985
+ "special": true
986
+ },
987
+ "64121": {
988
+ "content": "reserved_special_token_71",
989
+ "lstrip": false,
990
+ "normalized": false,
991
+ "rstrip": false,
992
+ "single_word": false,
993
+ "special": true
994
+ },
995
+ "64122": {
996
+ "content": "reserved_special_token_72",
997
+ "lstrip": false,
998
+ "normalized": false,
999
+ "rstrip": false,
1000
+ "single_word": false,
1001
+ "special": true
1002
+ },
1003
+ "64123": {
1004
+ "content": "reserved_special_token_73",
1005
+ "lstrip": false,
1006
+ "normalized": false,
1007
+ "rstrip": false,
1008
+ "single_word": false,
1009
+ "special": true
1010
+ },
1011
+ "64124": {
1012
+ "content": "reserved_special_token_74",
1013
+ "lstrip": false,
1014
+ "normalized": false,
1015
+ "rstrip": false,
1016
+ "single_word": false,
1017
+ "special": true
1018
+ },
1019
+ "64125": {
1020
+ "content": "reserved_special_token_75",
1021
+ "lstrip": false,
1022
+ "normalized": false,
1023
+ "rstrip": false,
1024
+ "single_word": false,
1025
+ "special": true
1026
+ },
1027
+ "64126": {
1028
+ "content": "reserved_special_token_76",
1029
+ "lstrip": false,
1030
+ "normalized": false,
1031
+ "rstrip": false,
1032
+ "single_word": false,
1033
+ "special": true
1034
+ },
1035
+ "64127": {
1036
+ "content": "reserved_special_token_77",
1037
+ "lstrip": false,
1038
+ "normalized": false,
1039
+ "rstrip": false,
1040
+ "single_word": false,
1041
+ "special": true
1042
+ },
1043
+ "64128": {
1044
+ "content": "reserved_special_token_78",
1045
+ "lstrip": false,
1046
+ "normalized": false,
1047
+ "rstrip": false,
1048
+ "single_word": false,
1049
+ "special": true
1050
+ },
1051
+ "64129": {
1052
+ "content": "reserved_special_token_79",
1053
+ "lstrip": false,
1054
+ "normalized": false,
1055
+ "rstrip": false,
1056
+ "single_word": false,
1057
+ "special": true
1058
+ },
1059
+ "64130": {
1060
+ "content": "reserved_special_token_80",
1061
+ "lstrip": false,
1062
+ "normalized": false,
1063
+ "rstrip": false,
1064
+ "single_word": false,
1065
+ "special": true
1066
+ },
1067
+ "64131": {
1068
+ "content": "reserved_special_token_81",
1069
+ "lstrip": false,
1070
+ "normalized": false,
1071
+ "rstrip": false,
1072
+ "single_word": false,
1073
+ "special": true
1074
+ },
1075
+ "64132": {
1076
+ "content": "reserved_special_token_82",
1077
+ "lstrip": false,
1078
+ "normalized": false,
1079
+ "rstrip": false,
1080
+ "single_word": false,
1081
+ "special": true
1082
+ },
1083
+ "64133": {
1084
+ "content": "reserved_special_token_83",
1085
+ "lstrip": false,
1086
+ "normalized": false,
1087
+ "rstrip": false,
1088
+ "single_word": false,
1089
+ "special": true
1090
+ },
1091
+ "64134": {
1092
+ "content": "reserved_special_token_84",
1093
+ "lstrip": false,
1094
+ "normalized": false,
1095
+ "rstrip": false,
1096
+ "single_word": false,
1097
+ "special": true
1098
+ },
1099
+ "64135": {
1100
+ "content": "reserved_special_token_85",
1101
+ "lstrip": false,
1102
+ "normalized": false,
1103
+ "rstrip": false,
1104
+ "single_word": false,
1105
+ "special": true
1106
+ },
1107
+ "64136": {
1108
+ "content": "reserved_special_token_86",
1109
+ "lstrip": false,
1110
+ "normalized": false,
1111
+ "rstrip": false,
1112
+ "single_word": false,
1113
+ "special": true
1114
+ },
1115
+ "64137": {
1116
+ "content": "reserved_special_token_87",
1117
+ "lstrip": false,
1118
+ "normalized": false,
1119
+ "rstrip": false,
1120
+ "single_word": false,
1121
+ "special": true
1122
+ },
1123
+ "64138": {
1124
+ "content": "reserved_special_token_88",
1125
+ "lstrip": false,
1126
+ "normalized": false,
1127
+ "rstrip": false,
1128
+ "single_word": false,
1129
+ "special": true
1130
+ },
1131
+ "64139": {
1132
+ "content": "reserved_special_token_89",
1133
+ "lstrip": false,
1134
+ "normalized": false,
1135
+ "rstrip": false,
1136
+ "single_word": false,
1137
+ "special": true
1138
+ },
1139
+ "64140": {
1140
+ "content": "reserved_special_token_90",
1141
+ "lstrip": false,
1142
+ "normalized": false,
1143
+ "rstrip": false,
1144
+ "single_word": false,
1145
+ "special": true
1146
+ },
1147
+ "64141": {
1148
+ "content": "reserved_special_token_91",
1149
+ "lstrip": false,
1150
+ "normalized": false,
1151
+ "rstrip": false,
1152
+ "single_word": false,
1153
+ "special": true
1154
+ },
1155
+ "64142": {
1156
+ "content": "reserved_special_token_92",
1157
+ "lstrip": false,
1158
+ "normalized": false,
1159
+ "rstrip": false,
1160
+ "single_word": false,
1161
+ "special": true
1162
+ },
1163
+ "64143": {
1164
+ "content": "reserved_special_token_93",
1165
+ "lstrip": false,
1166
+ "normalized": false,
1167
+ "rstrip": false,
1168
+ "single_word": false,
1169
+ "special": true
1170
+ },
1171
+ "64144": {
1172
+ "content": "reserved_special_token_94",
1173
+ "lstrip": false,
1174
+ "normalized": false,
1175
+ "rstrip": false,
1176
+ "single_word": false,
1177
+ "special": true
1178
+ },
1179
+ "64145": {
1180
+ "content": "reserved_special_token_95",
1181
+ "lstrip": false,
1182
+ "normalized": false,
1183
+ "rstrip": false,
1184
+ "single_word": false,
1185
+ "special": true
1186
+ },
1187
+ "64146": {
1188
+ "content": "reserved_special_token_96",
1189
+ "lstrip": false,
1190
+ "normalized": false,
1191
+ "rstrip": false,
1192
+ "single_word": false,
1193
+ "special": true
1194
+ },
1195
+ "64147": {
1196
+ "content": "reserved_special_token_97",
1197
+ "lstrip": false,
1198
+ "normalized": false,
1199
+ "rstrip": false,
1200
+ "single_word": false,
1201
+ "special": true
1202
+ },
1203
+ "64148": {
1204
+ "content": "reserved_special_token_98",
1205
+ "lstrip": false,
1206
+ "normalized": false,
1207
+ "rstrip": false,
1208
+ "single_word": false,
1209
+ "special": true
1210
+ },
1211
+ "64149": {
1212
+ "content": "reserved_special_token_99",
1213
+ "lstrip": false,
1214
+ "normalized": false,
1215
+ "rstrip": false,
1216
+ "single_word": false,
1217
+ "special": true
1218
+ },
1219
+ "64150": {
1220
+ "content": "reserved_special_token_100",
1221
+ "lstrip": false,
1222
+ "normalized": false,
1223
+ "rstrip": false,
1224
+ "single_word": false,
1225
+ "special": true
1226
+ },
1227
+ "64151": {
1228
+ "content": "reserved_special_token_101",
1229
+ "lstrip": false,
1230
+ "normalized": false,
1231
+ "rstrip": false,
1232
+ "single_word": false,
1233
+ "special": true
1234
+ },
1235
+ "64152": {
1236
+ "content": "reserved_special_token_102",
1237
+ "lstrip": false,
1238
+ "normalized": false,
1239
+ "rstrip": false,
1240
+ "single_word": false,
1241
+ "special": true
1242
+ },
1243
+ "64153": {
1244
+ "content": "reserved_special_token_103",
1245
+ "lstrip": false,
1246
+ "normalized": false,
1247
+ "rstrip": false,
1248
+ "single_word": false,
1249
+ "special": true
1250
+ },
1251
+ "64154": {
1252
+ "content": "reserved_special_token_104",
1253
+ "lstrip": false,
1254
+ "normalized": false,
1255
+ "rstrip": false,
1256
+ "single_word": false,
1257
+ "special": true
1258
+ },
1259
+ "64155": {
1260
+ "content": "reserved_special_token_105",
1261
+ "lstrip": false,
1262
+ "normalized": false,
1263
+ "rstrip": false,
1264
+ "single_word": false,
1265
+ "special": true
1266
+ },
1267
+ "64156": {
1268
+ "content": "reserved_special_token_106",
1269
+ "lstrip": false,
1270
+ "normalized": false,
1271
+ "rstrip": false,
1272
+ "single_word": false,
1273
+ "special": true
1274
+ },
1275
+ "64157": {
1276
+ "content": "reserved_special_token_107",
1277
+ "lstrip": false,
1278
+ "normalized": false,
1279
+ "rstrip": false,
1280
+ "single_word": false,
1281
+ "special": true
1282
+ },
1283
+ "64158": {
1284
+ "content": "reserved_special_token_108",
1285
+ "lstrip": false,
1286
+ "normalized": false,
1287
+ "rstrip": false,
1288
+ "single_word": false,
1289
+ "special": true
1290
+ },
1291
+ "64159": {
1292
+ "content": "reserved_special_token_109",
1293
+ "lstrip": false,
1294
+ "normalized": false,
1295
+ "rstrip": false,
1296
+ "single_word": false,
1297
+ "special": true
1298
+ },
1299
+ "64160": {
1300
+ "content": "reserved_special_token_110",
1301
+ "lstrip": false,
1302
+ "normalized": false,
1303
+ "rstrip": false,
1304
+ "single_word": false,
1305
+ "special": true
1306
+ },
1307
+ "64161": {
1308
+ "content": "reserved_special_token_111",
1309
+ "lstrip": false,
1310
+ "normalized": false,
1311
+ "rstrip": false,
1312
+ "single_word": false,
1313
+ "special": true
1314
+ },
1315
+ "64162": {
1316
+ "content": "reserved_special_token_112",
1317
+ "lstrip": false,
1318
+ "normalized": false,
1319
+ "rstrip": false,
1320
+ "single_word": false,
1321
+ "special": true
1322
+ },
1323
+ "64163": {
1324
+ "content": "reserved_special_token_113",
1325
+ "lstrip": false,
1326
+ "normalized": false,
1327
+ "rstrip": false,
1328
+ "single_word": false,
1329
+ "special": true
1330
+ },
1331
+ "64164": {
1332
+ "content": "reserved_special_token_114",
1333
+ "lstrip": false,
1334
+ "normalized": false,
1335
+ "rstrip": false,
1336
+ "single_word": false,
1337
+ "special": true
1338
+ },
1339
+ "64165": {
1340
+ "content": "reserved_special_token_115",
1341
+ "lstrip": false,
1342
+ "normalized": false,
1343
+ "rstrip": false,
1344
+ "single_word": false,
1345
+ "special": true
1346
+ },
1347
+ "64166": {
1348
+ "content": "reserved_special_token_116",
1349
+ "lstrip": false,
1350
+ "normalized": false,
1351
+ "rstrip": false,
1352
+ "single_word": false,
1353
+ "special": true
1354
+ },
1355
+ "64167": {
1356
+ "content": "reserved_special_token_117",
1357
+ "lstrip": false,
1358
+ "normalized": false,
1359
+ "rstrip": false,
1360
+ "single_word": false,
1361
+ "special": true
1362
+ },
1363
+ "64168": {
1364
+ "content": "reserved_special_token_118",
1365
+ "lstrip": false,
1366
+ "normalized": false,
1367
+ "rstrip": false,
1368
+ "single_word": false,
1369
+ "special": true
1370
+ },
1371
+ "64169": {
1372
+ "content": "reserved_special_token_119",
1373
+ "lstrip": false,
1374
+ "normalized": false,
1375
+ "rstrip": false,
1376
+ "single_word": false,
1377
+ "special": true
1378
+ },
1379
+ "64170": {
1380
+ "content": "reserved_special_token_120",
1381
+ "lstrip": false,
1382
+ "normalized": false,
1383
+ "rstrip": false,
1384
+ "single_word": false,
1385
+ "special": true
1386
+ },
1387
+ "64171": {
1388
+ "content": "reserved_special_token_121",
1389
+ "lstrip": false,
1390
+ "normalized": false,
1391
+ "rstrip": false,
1392
+ "single_word": false,
1393
+ "special": true
1394
+ },
1395
+ "64172": {
1396
+ "content": "reserved_special_token_122",
1397
+ "lstrip": false,
1398
+ "normalized": false,
1399
+ "rstrip": false,
1400
+ "single_word": false,
1401
+ "special": true
1402
+ },
1403
+ "64173": {
1404
+ "content": "reserved_special_token_123",
1405
+ "lstrip": false,
1406
+ "normalized": false,
1407
+ "rstrip": false,
1408
+ "single_word": false,
1409
+ "special": true
1410
+ },
1411
+ "64174": {
1412
+ "content": "reserved_special_token_124",
1413
+ "lstrip": false,
1414
+ "normalized": false,
1415
+ "rstrip": false,
1416
+ "single_word": false,
1417
+ "special": true
1418
+ },
1419
+ "64175": {
1420
+ "content": "reserved_special_token_125",
1421
+ "lstrip": false,
1422
+ "normalized": false,
1423
+ "rstrip": false,
1424
+ "single_word": false,
1425
+ "special": true
1426
+ },
1427
+ "64176": {
1428
+ "content": "reserved_special_token_126",
1429
+ "lstrip": false,
1430
+ "normalized": false,
1431
+ "rstrip": false,
1432
+ "single_word": false,
1433
+ "special": true
1434
+ },
1435
+ "64177": {
1436
+ "content": "reserved_special_token_127",
1437
+ "lstrip": false,
1438
+ "normalized": false,
1439
+ "rstrip": false,
1440
+ "single_word": false,
1441
+ "special": true
1442
+ },
1443
+ "64178": {
1444
+ "content": "reserved_special_token_128",
1445
+ "lstrip": false,
1446
+ "normalized": false,
1447
+ "rstrip": false,
1448
+ "single_word": false,
1449
+ "special": true
1450
+ },
1451
+ "64179": {
1452
+ "content": "reserved_special_token_129",
1453
+ "lstrip": false,
1454
+ "normalized": false,
1455
+ "rstrip": false,
1456
+ "single_word": false,
1457
+ "special": true
1458
+ },
1459
+ "64180": {
1460
+ "content": "reserved_special_token_130",
1461
+ "lstrip": false,
1462
+ "normalized": false,
1463
+ "rstrip": false,
1464
+ "single_word": false,
1465
+ "special": true
1466
+ },
1467
+ "64181": {
1468
+ "content": "reserved_special_token_131",
1469
+ "lstrip": false,
1470
+ "normalized": false,
1471
+ "rstrip": false,
1472
+ "single_word": false,
1473
+ "special": true
1474
+ },
1475
+ "64182": {
1476
+ "content": "reserved_special_token_132",
1477
+ "lstrip": false,
1478
+ "normalized": false,
1479
+ "rstrip": false,
1480
+ "single_word": false,
1481
+ "special": true
1482
+ },
1483
+ "64183": {
1484
+ "content": "reserved_special_token_133",
1485
+ "lstrip": false,
1486
+ "normalized": false,
1487
+ "rstrip": false,
1488
+ "single_word": false,
1489
+ "special": true
1490
+ },
1491
+ "64184": {
1492
+ "content": "reserved_special_token_134",
1493
+ "lstrip": false,
1494
+ "normalized": false,
1495
+ "rstrip": false,
1496
+ "single_word": false,
1497
+ "special": true
1498
+ },
1499
+ "64185": {
1500
+ "content": "reserved_special_token_135",
1501
+ "lstrip": false,
1502
+ "normalized": false,
1503
+ "rstrip": false,
1504
+ "single_word": false,
1505
+ "special": true
1506
+ },
1507
+ "64186": {
1508
+ "content": "reserved_special_token_136",
1509
+ "lstrip": false,
1510
+ "normalized": false,
1511
+ "rstrip": false,
1512
+ "single_word": false,
1513
+ "special": true
1514
+ },
1515
+ "64187": {
1516
+ "content": "reserved_special_token_137",
1517
+ "lstrip": false,
1518
+ "normalized": false,
1519
+ "rstrip": false,
1520
+ "single_word": false,
1521
+ "special": true
1522
+ },
1523
+ "64188": {
1524
+ "content": "reserved_special_token_138",
1525
+ "lstrip": false,
1526
+ "normalized": false,
1527
+ "rstrip": false,
1528
+ "single_word": false,
1529
+ "special": true
1530
+ },
1531
+ "64189": {
1532
+ "content": "reserved_special_token_139",
1533
+ "lstrip": false,
1534
+ "normalized": false,
1535
+ "rstrip": false,
1536
+ "single_word": false,
1537
+ "special": true
1538
+ },
1539
+ "64190": {
1540
+ "content": "reserved_special_token_140",
1541
+ "lstrip": false,
1542
+ "normalized": false,
1543
+ "rstrip": false,
1544
+ "single_word": false,
1545
+ "special": true
1546
+ },
1547
+ "64191": {
1548
+ "content": "reserved_special_token_141",
1549
+ "lstrip": false,
1550
+ "normalized": false,
1551
+ "rstrip": false,
1552
+ "single_word": false,
1553
+ "special": true
1554
+ },
1555
+ "64192": {
1556
+ "content": "reserved_special_token_142",
1557
+ "lstrip": false,
1558
+ "normalized": false,
1559
+ "rstrip": false,
1560
+ "single_word": false,
1561
+ "special": true
1562
+ },
1563
+ "64193": {
1564
+ "content": "reserved_special_token_143",
1565
+ "lstrip": false,
1566
+ "normalized": false,
1567
+ "rstrip": false,
1568
+ "single_word": false,
1569
+ "special": true
1570
+ },
1571
+ "64194": {
1572
+ "content": "reserved_special_token_144",
1573
+ "lstrip": false,
1574
+ "normalized": false,
1575
+ "rstrip": false,
1576
+ "single_word": false,
1577
+ "special": true
1578
+ },
1579
+ "64195": {
1580
+ "content": "reserved_special_token_145",
1581
+ "lstrip": false,
1582
+ "normalized": false,
1583
+ "rstrip": false,
1584
+ "single_word": false,
1585
+ "special": true
1586
+ },
1587
+ "64196": {
1588
+ "content": "reserved_special_token_146",
1589
+ "lstrip": false,
1590
+ "normalized": false,
1591
+ "rstrip": false,
1592
+ "single_word": false,
1593
+ "special": true
1594
+ },
1595
+ "64197": {
1596
+ "content": "reserved_special_token_147",
1597
+ "lstrip": false,
1598
+ "normalized": false,
1599
+ "rstrip": false,
1600
+ "single_word": false,
1601
+ "special": true
1602
+ },
1603
+ "64198": {
1604
+ "content": "reserved_special_token_148",
1605
+ "lstrip": false,
1606
+ "normalized": false,
1607
+ "rstrip": false,
1608
+ "single_word": false,
1609
+ "special": true
1610
+ },
1611
+ "64199": {
1612
+ "content": "reserved_special_token_149",
1613
+ "lstrip": false,
1614
+ "normalized": false,
1615
+ "rstrip": false,
1616
+ "single_word": false,
1617
+ "special": true
1618
+ },
1619
+ "64200": {
1620
+ "content": "reserved_special_token_150",
1621
+ "lstrip": false,
1622
+ "normalized": false,
1623
+ "rstrip": false,
1624
+ "single_word": false,
1625
+ "special": true
1626
+ },
1627
+ "64201": {
1628
+ "content": "reserved_special_token_151",
1629
+ "lstrip": false,
1630
+ "normalized": false,
1631
+ "rstrip": false,
1632
+ "single_word": false,
1633
+ "special": true
1634
+ },
1635
+ "64202": {
1636
+ "content": "reserved_special_token_152",
1637
+ "lstrip": false,
1638
+ "normalized": false,
1639
+ "rstrip": false,
1640
+ "single_word": false,
1641
+ "special": true
1642
+ },
1643
+ "64203": {
1644
+ "content": "reserved_special_token_153",
1645
+ "lstrip": false,
1646
+ "normalized": false,
1647
+ "rstrip": false,
1648
+ "single_word": false,
1649
+ "special": true
1650
+ },
1651
+ "64204": {
1652
+ "content": "reserved_special_token_154",
1653
+ "lstrip": false,
1654
+ "normalized": false,
1655
+ "rstrip": false,
1656
+ "single_word": false,
1657
+ "special": true
1658
+ },
1659
+ "64205": {
1660
+ "content": "reserved_special_token_155",
1661
+ "lstrip": false,
1662
+ "normalized": false,
1663
+ "rstrip": false,
1664
+ "single_word": false,
1665
+ "special": true
1666
+ },
1667
+ "64206": {
1668
+ "content": "reserved_special_token_156",
1669
+ "lstrip": false,
1670
+ "normalized": false,
1671
+ "rstrip": false,
1672
+ "single_word": false,
1673
+ "special": true
1674
+ },
1675
+ "64207": {
1676
+ "content": "reserved_special_token_157",
1677
+ "lstrip": false,
1678
+ "normalized": false,
1679
+ "rstrip": false,
1680
+ "single_word": false,
1681
+ "special": true
1682
+ },
1683
+ "64208": {
1684
+ "content": "reserved_special_token_158",
1685
+ "lstrip": false,
1686
+ "normalized": false,
1687
+ "rstrip": false,
1688
+ "single_word": false,
1689
+ "special": true
1690
+ },
1691
+ "64209": {
1692
+ "content": "reserved_special_token_159",
1693
+ "lstrip": false,
1694
+ "normalized": false,
1695
+ "rstrip": false,
1696
+ "single_word": false,
1697
+ "special": true
1698
+ },
1699
+ "64210": {
1700
+ "content": "reserved_special_token_160",
1701
+ "lstrip": false,
1702
+ "normalized": false,
1703
+ "rstrip": false,
1704
+ "single_word": false,
1705
+ "special": true
1706
+ },
1707
+ "64211": {
1708
+ "content": "reserved_special_token_161",
1709
+ "lstrip": false,
1710
+ "normalized": false,
1711
+ "rstrip": false,
1712
+ "single_word": false,
1713
+ "special": true
1714
+ },
1715
+ "64212": {
1716
+ "content": "reserved_special_token_162",
1717
+ "lstrip": false,
1718
+ "normalized": false,
1719
+ "rstrip": false,
1720
+ "single_word": false,
1721
+ "special": true
1722
+ },
1723
+ "64213": {
1724
+ "content": "reserved_special_token_163",
1725
+ "lstrip": false,
1726
+ "normalized": false,
1727
+ "rstrip": false,
1728
+ "single_word": false,
1729
+ "special": true
1730
+ },
1731
+ "64214": {
1732
+ "content": "reserved_special_token_164",
1733
+ "lstrip": false,
1734
+ "normalized": false,
1735
+ "rstrip": false,
1736
+ "single_word": false,
1737
+ "special": true
1738
+ },
1739
+ "64215": {
1740
+ "content": "reserved_special_token_165",
1741
+ "lstrip": false,
1742
+ "normalized": false,
1743
+ "rstrip": false,
1744
+ "single_word": false,
1745
+ "special": true
1746
+ },
1747
+ "64216": {
1748
+ "content": "reserved_special_token_166",
1749
+ "lstrip": false,
1750
+ "normalized": false,
1751
+ "rstrip": false,
1752
+ "single_word": false,
1753
+ "special": true
1754
+ },
1755
+ "64217": {
1756
+ "content": "reserved_special_token_167",
1757
+ "lstrip": false,
1758
+ "normalized": false,
1759
+ "rstrip": false,
1760
+ "single_word": false,
1761
+ "special": true
1762
+ },
1763
+ "64218": {
1764
+ "content": "reserved_special_token_168",
1765
+ "lstrip": false,
1766
+ "normalized": false,
1767
+ "rstrip": false,
1768
+ "single_word": false,
1769
+ "special": true
1770
+ },
1771
+ "64219": {
1772
+ "content": "reserved_special_token_169",
1773
+ "lstrip": false,
1774
+ "normalized": false,
1775
+ "rstrip": false,
1776
+ "single_word": false,
1777
+ "special": true
1778
+ },
1779
+ "64220": {
1780
+ "content": "reserved_special_token_170",
1781
+ "lstrip": false,
1782
+ "normalized": false,
1783
+ "rstrip": false,
1784
+ "single_word": false,
1785
+ "special": true
1786
+ },
1787
+ "64221": {
1788
+ "content": "reserved_special_token_171",
1789
+ "lstrip": false,
1790
+ "normalized": false,
1791
+ "rstrip": false,
1792
+ "single_word": false,
1793
+ "special": true
1794
+ },
1795
+ "64222": {
1796
+ "content": "reserved_special_token_172",
1797
+ "lstrip": false,
1798
+ "normalized": false,
1799
+ "rstrip": false,
1800
+ "single_word": false,
1801
+ "special": true
1802
+ },
1803
+ "64223": {
1804
+ "content": "reserved_special_token_173",
1805
+ "lstrip": false,
1806
+ "normalized": false,
1807
+ "rstrip": false,
1808
+ "single_word": false,
1809
+ "special": true
1810
+ },
1811
+ "64224": {
1812
+ "content": "reserved_special_token_174",
1813
+ "lstrip": false,
1814
+ "normalized": false,
1815
+ "rstrip": false,
1816
+ "single_word": false,
1817
+ "special": true
1818
+ },
1819
+ "64225": {
1820
+ "content": "reserved_special_token_175",
1821
+ "lstrip": false,
1822
+ "normalized": false,
1823
+ "rstrip": false,
1824
+ "single_word": false,
1825
+ "special": true
1826
+ },
1827
+ "64226": {
1828
+ "content": "reserved_special_token_176",
1829
+ "lstrip": false,
1830
+ "normalized": false,
1831
+ "rstrip": false,
1832
+ "single_word": false,
1833
+ "special": true
1834
+ },
1835
+ "64227": {
1836
+ "content": "reserved_special_token_177",
1837
+ "lstrip": false,
1838
+ "normalized": false,
1839
+ "rstrip": false,
1840
+ "single_word": false,
1841
+ "special": true
1842
+ },
1843
+ "64228": {
1844
+ "content": "reserved_special_token_178",
1845
+ "lstrip": false,
1846
+ "normalized": false,
1847
+ "rstrip": false,
1848
+ "single_word": false,
1849
+ "special": true
1850
+ },
1851
+ "64229": {
1852
+ "content": "reserved_special_token_179",
1853
+ "lstrip": false,
1854
+ "normalized": false,
1855
+ "rstrip": false,
1856
+ "single_word": false,
1857
+ "special": true
1858
+ },
1859
+ "64230": {
1860
+ "content": "reserved_special_token_180",
1861
+ "lstrip": false,
1862
+ "normalized": false,
1863
+ "rstrip": false,
1864
+ "single_word": false,
1865
+ "special": true
1866
+ },
1867
+ "64231": {
1868
+ "content": "reserved_special_token_181",
1869
+ "lstrip": false,
1870
+ "normalized": false,
1871
+ "rstrip": false,
1872
+ "single_word": false,
1873
+ "special": true
1874
+ },
1875
+ "64232": {
1876
+ "content": "reserved_special_token_182",
1877
+ "lstrip": false,
1878
+ "normalized": false,
1879
+ "rstrip": false,
1880
+ "single_word": false,
1881
+ "special": true
1882
+ },
1883
+ "64233": {
1884
+ "content": "reserved_special_token_183",
1885
+ "lstrip": false,
1886
+ "normalized": false,
1887
+ "rstrip": false,
1888
+ "single_word": false,
1889
+ "special": true
1890
+ },
1891
+ "64234": {
1892
+ "content": "reserved_special_token_184",
1893
+ "lstrip": false,
1894
+ "normalized": false,
1895
+ "rstrip": false,
1896
+ "single_word": false,
1897
+ "special": true
1898
+ },
1899
+ "64235": {
1900
+ "content": "reserved_special_token_185",
1901
+ "lstrip": false,
1902
+ "normalized": false,
1903
+ "rstrip": false,
1904
+ "single_word": false,
1905
+ "special": true
1906
+ },
1907
+ "64236": {
1908
+ "content": "reserved_special_token_186",
1909
+ "lstrip": false,
1910
+ "normalized": false,
1911
+ "rstrip": false,
1912
+ "single_word": false,
1913
+ "special": true
1914
+ },
1915
+ "64237": {
1916
+ "content": "reserved_special_token_187",
1917
+ "lstrip": false,
1918
+ "normalized": false,
1919
+ "rstrip": false,
1920
+ "single_word": false,
1921
+ "special": true
1922
+ },
1923
+ "64238": {
1924
+ "content": "reserved_special_token_188",
1925
+ "lstrip": false,
1926
+ "normalized": false,
1927
+ "rstrip": false,
1928
+ "single_word": false,
1929
+ "special": true
1930
+ },
1931
+ "64239": {
1932
+ "content": "reserved_special_token_189",
1933
+ "lstrip": false,
1934
+ "normalized": false,
1935
+ "rstrip": false,
1936
+ "single_word": false,
1937
+ "special": true
1938
+ },
1939
+ "64240": {
1940
+ "content": "reserved_special_token_190",
1941
+ "lstrip": false,
1942
+ "normalized": false,
1943
+ "rstrip": false,
1944
+ "single_word": false,
1945
+ "special": true
1946
+ },
1947
+ "64241": {
1948
+ "content": "reserved_special_token_191",
1949
+ "lstrip": false,
1950
+ "normalized": false,
1951
+ "rstrip": false,
1952
+ "single_word": false,
1953
+ "special": true
1954
+ },
1955
+ "64242": {
1956
+ "content": "reserved_special_token_192",
1957
+ "lstrip": false,
1958
+ "normalized": false,
1959
+ "rstrip": false,
1960
+ "single_word": false,
1961
+ "special": true
1962
+ },
1963
+ "64243": {
1964
+ "content": "reserved_special_token_193",
1965
+ "lstrip": false,
1966
+ "normalized": false,
1967
+ "rstrip": false,
1968
+ "single_word": false,
1969
+ "special": true
1970
+ },
1971
+ "64244": {
1972
+ "content": "reserved_special_token_194",
1973
+ "lstrip": false,
1974
+ "normalized": false,
1975
+ "rstrip": false,
1976
+ "single_word": false,
1977
+ "special": true
1978
+ },
1979
+ "64245": {
1980
+ "content": "reserved_special_token_195",
1981
+ "lstrip": false,
1982
+ "normalized": false,
1983
+ "rstrip": false,
1984
+ "single_word": false,
1985
+ "special": true
1986
+ },
1987
+ "64246": {
1988
+ "content": "reserved_special_token_196",
1989
+ "lstrip": false,
1990
+ "normalized": false,
1991
+ "rstrip": false,
1992
+ "single_word": false,
1993
+ "special": true
1994
+ },
1995
+ "64247": {
1996
+ "content": "reserved_special_token_197",
1997
+ "lstrip": false,
1998
+ "normalized": false,
1999
+ "rstrip": false,
2000
+ "single_word": false,
2001
+ "special": true
2002
+ },
2003
+ "64248": {
2004
+ "content": "reserved_special_token_198",
2005
+ "lstrip": false,
2006
+ "normalized": false,
2007
+ "rstrip": false,
2008
+ "single_word": false,
2009
+ "special": true
2010
+ },
2011
+ "64249": {
2012
+ "content": "reserved_special_token_199",
2013
+ "lstrip": false,
2014
+ "normalized": false,
2015
+ "rstrip": false,
2016
+ "single_word": false,
2017
+ "special": true
2018
+ },
2019
+ "64250": {
2020
+ "content": "reserved_special_token_200",
2021
+ "lstrip": false,
2022
+ "normalized": false,
2023
+ "rstrip": false,
2024
+ "single_word": false,
2025
+ "special": true
2026
+ },
2027
+ "64251": {
2028
+ "content": "reserved_special_token_201",
2029
+ "lstrip": false,
2030
+ "normalized": false,
2031
+ "rstrip": false,
2032
+ "single_word": false,
2033
+ "special": true
2034
+ },
2035
+ "64252": {
2036
+ "content": "reserved_special_token_202",
2037
+ "lstrip": false,
2038
+ "normalized": false,
2039
+ "rstrip": false,
2040
+ "single_word": false,
2041
+ "special": true
2042
+ },
2043
+ "64253": {
2044
+ "content": "reserved_special_token_203",
2045
+ "lstrip": false,
2046
+ "normalized": false,
2047
+ "rstrip": false,
2048
+ "single_word": false,
2049
+ "special": true
2050
+ },
2051
+ "64254": {
2052
+ "content": "<|python_tag|>",
2053
+ "lstrip": false,
2054
+ "normalized": false,
2055
+ "rstrip": false,
2056
+ "single_word": false,
2057
+ "special": false
2058
+ },
2059
+ "64255": {
2060
+ "content": "reserved_special_token_205",
2061
+ "lstrip": false,
2062
+ "normalized": false,
2063
+ "rstrip": false,
2064
+ "single_word": false,
2065
+ "special": true
2066
+ }
2067
+ },
2068
+ "bos_token": "<|begin_of_text|>",
2069
+ "clean_up_tokenization_spaces": false,
2070
+ "eos_token": "<|endoftext|>",
2071
+ "extra_special_tokens": {},
2072
+ "model_max_length": 1000000000000000019884624838656,
2073
+ "tokenizer_class": "PreTrainedTokenizerFast",
2074
+ "pad_token": "reserved_special_token_205"
2075
+ }