Spaces:
Running
Running
Download data.js from evalstate/tool-research-v3: direct link, hf CLI and curl.
- Browser
- Download file 329 kB
-
https://huggingface.co/spaces/evalstate/tool-research-v3/resolve/main/data.js
- Command line
-
hf download hf://spaces/evalstate/tool-research-v3/data.js
-
curl -L -o data.js https://huggingface.co/spaces/evalstate/tool-research-v3/resolve/main/data.js
329 kB
// Auto-generated by v2-work/build_data.py — do not hand-edit.
export const REPORT_DATA = {
"meta": {
"generatedAt": "2026-11-22",
"repos": {
"transformers": {
"sha": "4cac50ff5414dd0b591e6d5fc1c5ca3f32a20a16",
"shortSha": "4cac50f",
"url": "https://github.com/huggingface/transformers/tree/4cac50ff5414dd0b591e6d5fc1c5ca3f32a20a16"
},
"vllm": {
"sha": "ef687f6179b752c028767e610addbda67ed36d03",
"shortSha": "ef687f6",
"url": "https://github.com/vllm-project/vllm/tree/ef687f6179b752c028767e610addbda67ed36d03"
},
"sglang": {
"sha": "1918da6349f9be1c62315503e1a7458a3957bc5f",
"shortSha": "1918da6",
"url": "https://github.com/sgl-project/sglang/tree/1918da6349f9be1c62315503e1a7458a3957bc5f"
},
"llama_cpp": {
"sha": "35c9b1f39ebe5a7bb83986d64415a079218be78d",
"shortSha": "35c9b1f",
"url": "https://github.com/ggml-org/llama.cpp/tree/35c9b1f39ebe5a7bb83986d64415a079218be78d"
}
}
},
"presets": {
"search": {
"id": "search",
"label": "search_models",
"sub": "flat",
"userPrompt": "Find small speech-recognition models, at most 3.",
"tools": [
{
"type": "function",
"function": {
"name": "search_models",
"description": "Search the Hugging Face Hub for models.",
"parameters": {
"type": "object",
"properties": {
"query": {
"type": "string",
"description": "Free-text search, e.g. 'whisper small'."
},
"task": {
"type": "string",
"enum": [
"text-generation",
"automatic-speech-recognition",
"image-text-to-text"
],
"description": "Pipeline tag to filter by."
},
"limit": {
"type": "integer",
"minimum": 1,
"maximum": 50,
"description": "How many results to return."
}
},
"required": [
"query"
]
}
}
}
],
"sampleArgs": {
"query": "whisper small",
"task": "automatic-speech-recognition",
"limit": 3
},
"sampleToolResult": {
"count": 2,
"models": [
"openai/whisper-small",
"distil-whisper/distil-small.en"
]
},
"textReply": "You can filter Hugging Face models by automatic-speech-recognition on huggingface.co/models, or let me run search_models if you want live matches.",
"tip": "Rename <code>limit</code> to <code>max_results</code>, add <code>\"default\": 10</code>, or change its type to <code>\"string\"</code> and watch both the prompt and parsed call update."
},
"ticket": {
"id": "ticket",
"label": "create_ticket",
"sub": "nested",
"userPrompt": "Open a high-priority ticket for cust_42 (email ops@acme.dev) tagged billing.",
"tools": [
{
"type": "function",
"function": {
"name": "create_ticket",
"description": "Create a support ticket with nested customer contact details.",
"parameters": {
"type": "object",
"properties": {
"priority": {
"type": "string",
"enum": [
"low",
"normal",
"high",
"urgent"
],
"default": "normal",
"description": "Triage urgency level."
},
"tags": {
"type": "array",
"items": {
"type": "string"
},
"description": "Routing labels for the queue."
},
"customer": {
"type": "object",
"description": "Customer account and reachable contact points.",
"properties": {
"id": {
"type": "string",
"description": "Internal customer identifier."
},
"contacts": {
"type": "array",
"description": "Verified contact channels.",
"items": {
"type": "object",
"properties": {
"kind": {
"type": "string",
"enum": [
"email",
"phone",
"slack"
],
"description": "Channel type."
},
"value": {
"type": "string",
"description": "Channel address or handle."
}
},
"required": [
"kind",
"value"
]
}
}
},
"required": [
"id"
]
}
},
"required": [
"priority",
"customer"
],
"additionalProperties": false
}
}
}
],
"sampleArgs": {
"priority": "high",
"tags": [
"billing"
],
"customer": {
"id": "cust_42",
"contacts": [
{
"kind": "email",
"value": "ops@acme.dev"
}
]
}
},
"sampleToolResult": {
"ticket_id": "TCK-9041",
"status": "open"
},
"textReply": "Before opening a high-priority billing ticket for cust_42, confirm whether an incident ID should be attached.",
"tip": "Compare <code>gpt-oss-120b</code> with <code>Kimi-K2.6</code> or <code>Qwen3.8-27B</code>: Harmony's TypeScript macro collapses <code>contacts</code> to <code>any[]</code>, dropping <code>kind</code> and <code>value</code>."
}
},
"sharedExcerpts": {
"vllm_finish_reason": {
"repo": "vllm",
"path": "vllm/entrypoints/serve/utils/tool_calls_utils.py",
"start": 41,
"end": 59,
"hl": [
53,
54,
57,
58
],
"sha": "ef687f6179b752c028767e610addbda67ed36d03",
"url": "https://github.com/vllm-project/vllm/blob/ef687f6179b752c028767e610addbda67ed36d03/vllm/entrypoints/serve/utils/tool_calls_utils.py#L41-L59",
"note": "vLLM rewrites engine finish_reason \"stop\" to \"tool_calls\" when tool_calls are extracted and the request did not force a single named tool.",
"code": "def resolve_finish_reason(\n engine_finish_reason: str | None,\n request: ChatCompletionRequest | None,\n tool_calls_made: bool,\n) -> str:\n \"\"\"Map the engine finish reason to the OpenAI chat `finish_reason`.\n\n `tool_calls` is reported only when the choice actually carries tool\n calls, the engine stopped on its own (a `length` cut stays visible so\n clients can tell a truncated call from a complete one) and the caller did\n not force a single named tool, for which OpenAI reports `stop`.\n \"\"\"\n finish_reason = engine_finish_reason or \"stop\"\n forced_named_tool = request is not None and isinstance(\n request.tool_choice, ChatCompletionNamedToolChoiceParam\n )\n if tool_calls_made and finish_reason == \"stop\" and not forced_named_tool:\n return \"tool_calls\"\n return finish_reason"
},
"sglang_finish_reason": {
"repo": "sglang",
"path": "python/sglang/srt/entrypoints/openai/serving_chat.py",
"start": 3269,
"end": 3293,
"hl": [
3286,
3287,
3288
],
"sha": "1918da6349f9be1c62315503e1a7458a3957bc5f",
"url": "https://github.com/sgl-project/sglang/blob/1918da6349f9be1c62315503e1a7458a3957bc5f/python/sglang/srt/entrypoints/openai/serving_chat.py#L3269-L3293",
"note": "SGLang rewrites finish_reason[\"type\"] from \"stop\" to \"tool_calls\" when FunctionCallParser extracts non-empty calls.",
"code": " tool_calls = []\n for index, call_info in enumerate(call_info_list):\n tool_id = self._process_tool_call_id(\n call_info, history_tool_calls_cnt\n )\n # Call ordinal, as in the streaming deltas;\n # tool_index is the tool's position in the request.\n tool_calls.append(\n ToolCall(\n id=tool_id,\n index=index,\n function=FunctionResponse(\n name=call_info.name,\n arguments=call_info.parameters,\n ),\n )\n )\n if finish_reason[\"type\"] == \"stop\":\n finish_reason[\"type\"] = \"tool_calls\"\n finish_reason[\"matched\"] = None\n return ToolCallProcessingResult(tool_calls, text, finish_reason)\n except Exception as e:\n logger.error(f\"Tool call parsing error: {e}\")\n return ToolCallProcessingResult(None, text, finish_reason)\n"
},
"llama_cpp_finish": {
"repo": "llama.cpp",
"path": "tools/server/server-task.cpp",
"start": 825,
"end": 843,
"hl": [
834,
835,
836
],
"sha": "35c9b1f39ebe5a7bb83986d64415a079218be78d",
"url": "https://github.com/ggml-org/llama.cpp/blob/35c9b1f39ebe5a7bb83986d64415a079218be78d/tools/server/server-task.cpp#L825-L843",
"note": "In its OpenAI-compatible chat response adapter (to_json_oaicompat_chat), llama.cpp maps STOP_TYPE_WORD/EOS to finish_reason=\"tool_calls\" when parsed tool_calls exist.",
"code": "json server_task_result_cmpl_final::to_json_oaicompat_chat() {\n std::string finish_reason = \"length\";\n common_chat_msg msg;\n if (!oaicompat_msg.empty()) {\n msg = oaicompat_msg;\n } else {\n msg.role = \"assistant\";\n msg.content = content;\n }\n if (stop == STOP_TYPE_WORD || stop == STOP_TYPE_EOS) {\n finish_reason = msg.tool_calls.empty() ? \"stop\" : \"tool_calls\";\n }\n\n json choice {\n {\"finish_reason\", finish_reason},\n {\"index\", index},\n {\"message\", msg.to_json_oaicompat()},\n };\n"
},
"transformers_input": {
"repo": "transformers",
"path": "src/transformers/utils/chat_template_utils.py",
"start": 497,
"end": 521,
"hl": [
503,
504,
505,
506,
507
],
"sha": "4cac50ff5414dd0b591e6d5fc1c5ca3f32a20a16",
"url": "https://github.com/huggingface/transformers/blob/4cac50ff5414dd0b591e6d5fc1c5ca3f32a20a16/src/transformers/utils/chat_template_utils.py#L497-L521",
"note": "transformers passes dict tool schemas straight through into tool_schemas (only converting Python callables via get_json_schema) before rendering the Jinja template.",
"code": " # Compilation function uses a cache to avoid recompiling the same template\n compiled_template = _compile_jinja_template(chat_template)\n\n # We accept either JSON schemas or functions for tools. If we get functions, we convert them to schemas\n if tools is not None:\n tool_schemas = []\n for tool in tools:\n if isinstance(tool, dict):\n tool_schemas.append(tool)\n elif isfunction(tool) or inspect.ismethod(tool):\n tool_schemas.append(get_json_schema(tool))\n else:\n raise ValueError(\n \"Tools should either be a JSON schema, or a callable function with type hints \"\n \"and a docstring suitable for auto-conversion to a schema.\"\n )\n else:\n tool_schemas = None\n\n if documents is not None:\n for document in documents:\n if not isinstance(document, dict):\n raise TypeError(\"Documents should be a list of dicts with 'title' and 'text' keys!\")\n\n rendered = []"
},
"vllm_input": {
"repo": "vllm",
"path": "vllm/renderers/hf.py",
"start": 917,
"end": 948,
"hl": [
932,
933,
934,
935
],
"sha": "ef687f6179b752c028767e610addbda67ed36d03",
"url": "https://github.com/vllm-project/vllm/blob/ef687f6179b752c028767e610addbda67ed36d03/vllm/renderers/hf.py#L917-L948",
"note": "On the standard HF renderer path, vLLM delegates prompt rendering to tokenizer.apply_chat_template(tools=..., return_dict=False).",
"code": " resolved_kwargs = resolve_chat_template_kwargs(\n tokenizer=tokenizer,\n chat_template=chat_template,\n chat_template_kwargs=kwargs,\n )\n\n # transformers v5 changed the default of `return_dict` to True, which\n # makes `apply_chat_template(tokenize=True)` return a `BatchEncoding`\n # instead of `list[int]`. Force `return_dict=False` so downstream code\n # that expects a flat token list (e.g. `parse_dec_only_prompt`) works\n # consistently across v4 and v5.\n if tokenize and \"return_dict\" not in resolved_kwargs:\n resolved_kwargs[\"return_dict\"] = False\n\n try:\n plain = tokenizer.apply_chat_template(\n conversation=conversation, # type: ignore[arg-type]\n tools=tools, # type: ignore[arg-type]\n chat_template=chat_template,\n tokenize=tokenize,\n **resolved_kwargs,\n )\n except Exception as e:\n # Chat templates reject invalid user input (e.g. an unsupported\n # `reasoning_effort` value) by raising from within the template.\n # Surface those as a 400 Bad Request carrying the template's own\n # reason (which typically lists the supported values) instead of a\n # 500 or any generic upstream wrapper message.\n logger.warning(\"Chat template rejected the request: %s\", e)\n raise VLLMValidationError(_template_error_reason(e)) from e\n\n return plain"
}
},
"models": [
{
"key": "qwen38",
"id": "Qwen/Qwen3.8-27B",
"label": "Qwen3.8-27B",
"sub": "XML tags",
"sha": "37561816e66b5b9153b1b64c10968c18c1e6f4a0",
"created": "2026-08-05",
"likes": 20881,
"templateKind": "jinja",
"schemaEncoding": "JSON in <tools>",
"callSyntax": "<tool_call><function=…>",
"servingNote": "vLLM and SGLang render prompts via transformers apply_chat_template(tools=...) and parse <tool_call><function=...><parameter=...> blocks.",
"chatTemplate": "{%- set image_count = namespace(value=0) %}\n{%- set video_count = namespace(value=0) %}\n{%- macro render_content(content, do_vision_count, is_system_content=false) %}\n {%- if content is string %}\n {{- content }}\n {%- elif content is iterable and content is not mapping %}\n {%- for item in content %}\n {%- if 'image' in item or 'image_url' in item or item.type == 'image' %}\n {%- if is_system_content %}\n {{- raise_exception('System message cannot contain images.') }}\n {%- endif %}\n {%- if do_vision_count %}\n {%- set image_count.value = image_count.value + 1 %}\n {%- endif %}\n {%- if add_vision_id %}\n {{- 'Picture ' ~ image_count.value ~ ': ' }}\n {%- endif %}\n {{- '<|vision_start|><|image_pad|><|vision_end|>' }}\n {%- elif 'video' in item or item.type == 'video' %}\n {%- if is_system_content %}\n {{- raise_exception('System message cannot contain videos.') }}\n {%- endif %}\n {%- if do_vision_count %}\n {%- set video_count.value = video_count.value + 1 %}\n {%- endif %}\n {%- if add_vision_id %}\n {{- 'Video ' ~ video_count.value ~ ': ' }}\n {%- endif %}\n {{- '<|vision_start|><|video_pad|><|vision_end|>' }}\n {%- elif 'text' in item %}\n {{- item.text }}\n {%- else %}\n {{- raise_exception('Unexpected item type in content.') }}\n {%- endif %}\n {%- endfor %}\n {%- elif content is none or content is undefined %}\n {{- '' }}\n {%- else %}\n {{- raise_exception('Unexpected content type.') }}\n {%- endif %}\n{%- endmacro %}\n{%- if not messages %}\n {{- raise_exception('No messages provided.') }}\n{%- endif %}\n{%- set reasoning_instructions = '' %}\n{%- if enable_thinking is undefined or enable_thinking is true %}\n {%- set resolved_reasoning_effort = reasoning_effort|default('xhigh') %}\n {%- if resolved_reasoning_effort not in ('xhigh', 'medium', 'low') %}\n {{- raise_exception('Unexpected reasoning effort ' ~ reasoning_effort ~ '. Supported types are xhigh (default), medium, and low.') }}\n {%- endif %}\n {%- if resolved_reasoning_effort == 'xhigh' %}\n {%- set reasoning_instructions = 'Reasoning effort is set to xhigh. Please think carefully through the task, validate key assumptions, consider plausible alternatives, and prioritize correctness, consistency, and clarity in the final answer.' %}\n {%- elif resolved_reasoning_effort == 'low' %}\n {%- set reasoning_instructions = 'Reasoning effort is set to low. Keep your thinking brief and focused, moving directly to the conclusion without unnecessary elaboration.' %}\n {%- endif %}\n{%- endif %}\n{%- if tools and tools is iterable and tools is not mapping %}\n {{- '<|im_start|>system\\n' }}\n {%- if reasoning_instructions %}\n {{- reasoning_instructions + '\\n\\n' }}\n {%- endif %}\n {{- \"# Tools\\n\\nYou have access to the following functions:\\n\\n<tools>\" }}\n {%- for tool in tools %}\n {{- \"\\n\" }}\n {{- tool | tojson }}\n {%- endfor %}\n {{- \"\\n</tools>\" }}\n {{- '\\n\\nIf you choose to call a function ONLY reply in the following format with NO suffix:\\n\\n<tool_call>\\n<function=example_function_name>\\n<parameter=example_parameter_1>\\nvalue_1\\n</parameter>\\n<parameter=example_parameter_2>\\nThis is the value for the second parameter\\nthat can span\\nmultiple lines\\n</parameter>\\n</function>\\n</tool_call>\\n\\n<IMPORTANT>\\nReminder:\\n- Function calls MUST follow the specified format: an inner <function=...></function> block must be nested within <tool_call></tool_call> XML tags\\n- Required parameters MUST be specified\\n- You may provide optional reasoning for your function call in natural language BEFORE the function call, but NOT after\\n- If there is no function call available, answer the question like normal with your current knowledge and do not tell the user about function calls\\n</IMPORTANT>' }}\n {%- if messages[0].role == 'system' %}\n {%- set content = render_content(messages[0].content, false, true)|trim %}\n {%- if content %}\n {{- '\\n\\n' + content }}\n {%- endif %}\n {%- endif %}\n {{- '<|im_end|>\\n' }}\n{%- else %}\n {%- if messages[0].role == 'system' %}\n {%- set content = render_content(messages[0].content, false, true)|trim %}\n {%- if content %}\n {{- '<|im_start|>system\\n' + (reasoning_instructions + '\\n\\n' if reasoning_instructions else '') + content + '<|im_end|>\\n' }}\n {%- elif reasoning_instructions %}\n {{- '<|im_start|>system\\n' + reasoning_instructions + '<|im_end|>\\n' }}\n {%- endif %}\n {%- elif reasoning_instructions %}\n {{- '<|im_start|>system\\n' + reasoning_instructions + '<|im_end|>\\n' }}\n {%- endif %}\n{%- endif %}\n{%- set ns = namespace(multi_step_tool=true, last_query_index=messages|length - 1) %}\n{%- for message in messages[::-1] %}\n {%- set index = (messages|length - 1) - loop.index0 %}\n {%- if ns.multi_step_tool and message.role == \"user\" %}\n {%- set content = render_content(message.content, false)|trim %}\n {%- if not(content.startswith('<tool_response>') and content.endswith('</tool_response>')) %}\n {%- set ns.multi_step_tool = false %}\n {%- set ns.last_query_index = index %}\n {%- endif %}\n {%- endif %}\n{%- endfor %}\n{%- if ns.multi_step_tool %}\n {{- raise_exception('No user query found in messages.') }}\n{%- endif %}\n{%- for message in messages %}\n {%- set content = render_content(message.content, true)|trim %}\n {%- if message.role == \"system\" %}\n {%- if not loop.first %}\n {{- raise_exception('System message must be at the beginning.') }}\n {%- endif %}\n {%- elif message.role == \"user\" %}\n {{- '<|im_start|>' + message.role + '\\n' + content + '<|im_end|>' + '\\n' }}\n {%- elif message.role == \"assistant\" %}\n {%- set reasoning_content = '' %}\n {%- if message.reasoning_content is string %}\n {%- set reasoning_content = message.reasoning_content %}\n {%- endif %}\n {%- set reasoning_content = reasoning_content|trim %}\n {{- '<|im_start|>' + message.role + '\\n' }}\n {%- generation %}\n {%- if preserve_thinking is undefined or preserve_thinking is true or loop.index0 > ns.last_query_index %}\n {{- '<think>\\n' + reasoning_content + '\\n</think>\\n\\n' + content }}\n {%- else %}\n {{- content }}\n {%- endif %}\n {%- if message.tool_calls and message.tool_calls is iterable and message.tool_calls is not mapping %}\n {%- for tool_call in message.tool_calls %}\n {%- if tool_call.function is defined %}\n {%- set tool_call = tool_call.function %}\n {%- endif %}\n {%- if loop.first %}\n {%- if content|trim %}\n {{- '\\n\\n<tool_call>\\n<function=' + tool_call.name + '>\\n' }}\n {%- else %}\n {{- '<tool_call>\\n<function=' + tool_call.name + '>\\n' }}\n {%- endif %}\n {%- else %}\n {{- '\\n<tool_call>\\n<function=' + tool_call.name + '>\\n' }}\n {%- endif %}\n {%- if tool_call.arguments is defined and tool_call.arguments != '' %}\n {%- for args_name, args_value in tool_call.arguments|items %}\n {{- '<parameter=' + args_name + '>\\n' }}\n {%- set args_value = args_value | string if args_value is string else args_value | tojson | safe %}\n {{- args_value }}\n {{- '\\n</parameter>\\n' }}\n {%- endfor %}\n {%- endif %}\n {{- '</function>\\n</tool_call>' }}\n {%- endfor %}\n {%- endif %}\n {{- '<|im_end|>' }}\n {%- endgeneration %}\n {{- '\\n' }}\n {%- elif message.role == \"tool\" %}\n {%- if loop.previtem and loop.previtem.role != \"tool\" %}\n {{- '<|im_start|>user' }}\n {%- endif %}\n {{- '\\n<tool_response>\\n' }}\n {{- content }}\n {{- '\\n</tool_response>' }}\n {%- if not loop.last and loop.nextitem.role != \"tool\" %}\n {{- '<|im_end|>\\n' }}\n {%- elif loop.last %}\n {{- '<|im_end|>\\n' }}\n {%- endif %}\n {%- else %}\n {{- raise_exception('Unexpected message role.') }}\n {%- endif %}\n{%- endfor %}\n{%- if add_generation_prompt %}\n {{- '<|im_start|>assistant\\n' }}\n {%- if enable_thinking is defined and enable_thinking is false %}\n {{- '<think>\\n\\n</think>\\n\\n' }}\n {%- else %}\n {{- '<think>\\n' }}\n {%- endif %}\n{%- endif %}",
"templatePath": "chat_template.jinja",
"templateUrl": "https://huggingface.co/Qwen/Qwen3.8-27B/blob/37561816e66b5b9153b1b64c10968c18c1e6f4a0/chat_template.jinja",
"templateToolLines": [
57,
84
],
"templateHelperSource": null,
"templateHelperPath": null,
"templateHelperUrl": null,
"bosToken": "",
"eosToken": "<|im_end|>",
"padToken": "<|endoftext|>",
"unkToken": "",
"specialTokens": {
"<|endoftext|>": 248044,
"<|im_start|>": 248045,
"<|im_end|>": 248046,
"<|object_ref_start|>": 248047,
"<|object_ref_end|>": 248048,
"<|box_start|>": 248049,
"<|box_end|>": 248050,
"<|quad_start|>": 248051,
"<|quad_end|>": 248052,
"<|vision_start|>": 248053,
"<|vision_end|>": 248054,
"<|vision_pad|>": 248055,
"<|image_pad|>": 248056,
"<|video_pad|>": 248057,
"<tool_call>": 248058,
"</tool_call>": 248059,
"<|fim_prefix|>": 248060,
"<|fim_middle|>": 248061,
"<|fim_suffix|>": 248062,
"<|fim_pad|>": 248063,
"<|repo_name|>": 248064,
"<|file_sep|>": 248065,
"<tool_response>": 248066,
"</tool_response>": 248067,
"<think>": 248068,
"</think>": 248069,
"<|audio_start|>": 248070,
"<|audio_end|>": 248071,
"<tts_pad>": 248072,
"<tts_text_bos>": 248073,
"<tts_text_eod>": 248074,
"<tts_text_bos_single>": 248075,
"<|audio_pad|>": 248076
},
"stopTokenCall": "<|im_end|>",
"stopTokenText": "<|im_end|>",
"dedicatedStopToken": false,
"stopKind": "shared",
"eosNote": "Qwen3.8's generation_config lists <|im_end|> (248046) and <|endoftext|> (248044); both tool calls and plain replies close on shared <|im_end|>, so the server distinguishes them by parsing <tool_call>.",
"cap": "Qwen3.8 serializes each tool dict as a JSON line via <code>tool | tojson</code> inside <code><tools></code> tags in the system message. Every nested field, enum, and numeric bound survives intact, surrounded by explicit XML calling instructions.",
"outCap": "After closing <code></think></code>, Qwen3.8 emits XML <code><function=name></code> and <code><parameter=key></code> tags, then stops on the shared <code><|im_end|></code> token.",
"walkSteps": {
"s2": "Qwen3.8's Jinja template serializes each tool dict as a JSON line via tool | tojson inside <tools>...</tools>, keeping every nested object, enum, and numeric bound intact.",
"s3": "Around <tools>, the system block adds explicit prose and a full XML example showing <tool_call>, <function=...>, and <parameter=...> tags.",
"s4": "The rendered prompt ends with <|im_start|>assistant\\n<think>\\n, putting the model directly inside its reasoning block.",
"s5": "After </think>, the model emits special token <tool_call>, plain-text <function=name> and <parameter=key> XML tags, and closes with </tool_call>.",
"s6": "vLLM's Qwen3 parser and SGLang's Qwen3CoderDetector (with skip_special_tokens=False) match <tool_call>, <function=, and <parameter= and coerce parameter values using the schema.",
"s7": "Generation stops on shared <|im_end|> (248046); on an ordinary completed auto-tool turn with parsed calls, the serving layer rewrites engine 'stop' to API finish_reason='tool_calls'."
},
"lane": [
"Reasoning text closes with </think>",
"<tool_call> opens tool-call block",
"<function=…> names the target tool",
"<parameter=…> tags carry each argument value",
"</function> and </tool_call> close the block",
"<|im_end|> ends turn; sampler reports stop"
],
"laneText": [
"Reasoning text closes with </think>",
"Plain assistant answer text",
"<|im_end|> ends turn; sampler reports stop"
],
"excerpts": {
"vllm": [
{
"repo": "vllm",
"path": "vllm/parser/qwen3.py",
"start": 42,
"end": 69,
"hl": [
42,
43,
44,
45,
46,
47,
48,
49,
50
],
"sha": "ef687f6179b752c028767e610addbda67ed36d03",
"url": "https://github.com/vllm-project/vllm/blob/ef687f6179b752c028767e610addbda67ed36d03/vllm/parser/qwen3.py#L42-L69",
"note": "vLLM's Qwen3 parser defines exact <tool_call>, <function=, and <parameter= terminals.",
"code": "THINK_START = \"<think>\"\nTHINK_END = \"</think>\"\nTOOL_CALL_START = \"<tool_call>\"\nTOOL_CALL_END = \"</tool_call>\"\nCHATML_TURN_BOUNDARIES = frozenset((\"<|im_start|>\", \"<|im_end|>\"))\nFUNC_PREFIX = \"<function=\"\nFUNC_END = \"</function>\"\nPARAM_START = \"<parameter=\"\nPARAM_END = \"</parameter>\"\n\n_PARAM_RE = re.compile(\n r\"<\\s*parameter\\s*=\\s*([^>]*)>\"\n r\"(.*?)\"\n r\"(?:<\\s*/\\s*parameter\\s*>|(?=<\\s*parameter\\s*=))\",\n re.DOTALL,\n)\n_PARTIAL_PARAM_RE = re.compile(r\"<\\s*parameter\\s*=\\s*([^>]+)>(.*)$\", re.DOTALL)\n_PARAM_OPENER_RE = re.compile(r\"<\\s*parameter\\s*=\")\n\n\ndef _trim_wrapping_newlines(value: str) -> str:\n \"\"\"Strip one leading and one trailing newline (the Qwen3 template markup).\"\"\"\n if value.startswith(\"\\n\"):\n value = value[1:]\n if value.endswith(\"\\n\"):\n value = value[:-1]\n return value\n"
}
],
"sglang": [
{
"repo": "sglang",
"path": "python/sglang/srt/function_call/qwen3_coder_detector.py",
"start": 23,
"end": 47,
"hl": [
28,
29,
30,
31,
32,
33
],
"sha": "1918da6349f9be1c62315503e1a7458a3957bc5f",
"url": "https://github.com/sgl-project/sglang/blob/1918da6349f9be1c62315503e1a7458a3957bc5f/python/sglang/srt/function_call/qwen3_coder_detector.py#L23-L47",
"note": "SGLang's Qwen3CoderDetector defines sentinel tokens for <tool_call>, <function=, and <parameter= blocks.",
"code": "class Qwen3CoderDetector(BaseFormatDetector):\n def __init__(self):\n super().__init__()\n\n # Sentinel tokens\n self.tool_call_start_token: str = \"<tool_call>\"\n self.tool_call_end_token: str = \"</tool_call>\"\n self.tool_call_prefix: str = \"<function=\"\n self.function_end_token: str = \"</function>\"\n self.parameter_prefix: str = \"<parameter=\"\n self.parameter_end_token: str = \"</parameter>\"\n\n # Regex for non-streaming fallback\n self.tool_call_regex = re.compile(r\"<tool_call>(.*?)</tool_call>\", re.DOTALL)\n self.tool_call_function_regex = re.compile(\n r\"<function=(.*?)</function>|<function=(.*)$\", re.DOTALL\n )\n self.tool_call_parameter_regex = re.compile(\n r\"<parameter=(.*?)(?:</parameter>|(?=<parameter=)|(?=</function>)|$)\",\n re.DOTALL,\n )\n\n # Streaming State\n # Base class already initializes _buffer, we just use it directly\n # No need to check with hasattr - we control the lifecycle through inheritance"
}
]
}
},
{
"key": "kimi26",
"id": "moonshotai/Kimi-K2.6",
"label": "Kimi-K2.6",
"sub": "TypeScript hybrid",
"sha": "7eb5002f6aadc958aed6a9177b7ed26bb94011bb",
"created": "2026-04-14",
"likes": 1647,
"templateKind": "jinja+ts",
"schemaEncoding": "TS namespace (optional helper)",
"callSyntax": "<|tool_call_begin|>…<|tool_call_argument_begin|>",
"servingNote": "chat_template.jinja renders tools_ts_str when pre-formatted by Moonshot's optional tool_declaration_ts.py helper from the Hub repo (falling back to compact JSON otherwise); this page runs a JS port of that helper.",
"chatTemplate": "{%- macro render_content(msg) -%}\n {%- set c = msg.get('content') -%}\n {%- if c is string -%}\n {{ c }}\n {%- elif c is not none -%}\n {% for content in c -%}\n {% if content['type'] == 'image' or content['type'] == 'image_url' -%}\n <|media_begin|>image<|media_content|><|media_pad|><|media_end|>\n {% elif content['type'] == 'video' or content['type']== 'video_url'-%}\n <|kimi_k25_video_placeholder|>\n {% else -%}\n {{ content['text'] }}\n {%- endif -%}\n {%- endfor -%}\n {%- endif -%}\n{%- endmacro -%}\n\n{% macro set_roles(message) -%}\n {%- set role_name = message.get('name') or message['role'] -%}\n {%- if message['role'] == 'user' -%}\n <|im_user|>{{role_name}}<|im_middle|>\n {%- elif message['role'] == 'assistant' -%}\n <|im_assistant|>{{role_name}}<|im_middle|>\n {%- else -%}\n <|im_system|>{{role_name}}<|im_middle|>\n {%- endif -%}\n{%- endmacro -%}\n\n\n{%- macro render_toolcalls(message) -%}\n <|tool_calls_section_begin|>\n {%- for tool_call in message['tool_calls'] -%}\n {%- set formatted_id = tool_call['id'] -%}\n <|tool_call_begin|>{{ formatted_id }}<|tool_call_argument_begin|>{% if tool_call['function']['arguments'] is string %}{{ tool_call['function']['arguments'] }}{% else %}{{ tool_call['function']['arguments'] | tojson }}{% endif %}<|tool_call_end|>\n {%- endfor -%}\n <|tool_calls_section_end|>\n{%- endmacro -%}\n\n\n{%- set preserve_thinking = preserve_thinking | default(false) -%}\n{# Find last non-tool-call assistant message. If preserve_thinking, keep -1 so hist is empty and all msgs use suffix (retain reasoning). #}\n{%- set ns = namespace(last_non_tool_call_assistant_msg=-1) -%}\n{%- if not preserve_thinking -%}\n{%- for idx in range(messages|length-1, -1, -1) -%}\n {%- if messages[idx]['role'] == 'assistant' and not messages[idx].get('tool_calls') -%}\n {%- set ns.last_non_tool_call_assistant_msg = idx -%}\n {%- break -%}\n {%- endif -%}\n{%- endfor -%}\n{%- endif -%}\n\n{# split all messages into history & suffix, reasoning_content in suffix should be reserved.#}\n{%- set hist_msgs = messages[:ns.last_non_tool_call_assistant_msg+1] -%}\n{%- set suffix_msgs = messages[ns.last_non_tool_call_assistant_msg+1:] -%}\n\n{%- if tools -%}\n {%- if tools_ts_str -%}\n <|im_system|>tool_declare<|im_middle|>{{ tools_ts_str }}<|im_end|>\n {%- else -%}\n <|im_system|>tool_declare<|im_middle|>{{ tools | tojson(separators=(',', ':')) }}<|im_end|>\n {%- endif -%}\n{%- endif -%}\n\n \n{%- for message in hist_msgs -%}\n {{set_roles(message)}}\n {%- if message['role'] == 'assistant' -%}\n <think></think>{{render_content(message)}}\n {%- if message.get('tool_calls') -%}\n {{render_toolcalls(message)}}\n {%- endif -%}\n {%- elif message['role'] == 'tool' -%}\n {%- set tool_call_id = message.tool_call_id -%}\n ## Return of {{ tool_call_id }}\n{{render_content(message)}}\n {%- elif message['content'] is not none -%}\n {{render_content(message)}}\n {%- endif -%}\n <|im_end|>\n{%- endfor -%}\n\n{%- for message in suffix_msgs -%}\n {{set_roles(message)}}\n {%- if message['role'] == 'assistant' -%}\n {%- if thinking is defined and thinking is false and preserve_thinking is false -%}\n <think></think>{{render_content(message)}}\n {%- else -%}\n {%- set rc = message.get('reasoning', message.get('reasoning_content', '')) -%}\n <think>{{rc}}</think>{{render_content(message)}}\n {%- endif -%}\n {%- if message.get('tool_calls') -%}\n {{render_toolcalls(message)}}\n {%- endif -%}\n {%- elif message['role'] == 'tool' -%}\n {%- set tool_call_id = message.tool_call_id -%}\n ## Return of {{ tool_call_id }}\n{{render_content(message)}}\n {%- elif message['content'] is not none -%}\n {{render_content(message)}}\n {%- endif -%}\n <|im_end|>\n{%- endfor -%}\n\n\n{%- if add_generation_prompt -%}\n <|im_assistant|>assistant<|im_middle|>\n {%- if thinking is defined and thinking is false -%}\n <think></think>\n {%- else -%}\n <think>\n {%- endif -%}\n{%- endif -%}",
"templatePath": "chat_template.jinja",
"templateUrl": "https://huggingface.co/moonshotai/Kimi-K2.6/blob/7eb5002f6aadc958aed6a9177b7ed26bb94011bb/chat_template.jinja",
"templateToolLines": [
56,
63
],
"templateHelperSource": "\"\"\"\nEncode structured tool declaration to typescript style string.\n\"\"\"\nimport dataclasses\nimport json\nimport logging\nfrom collections.abc import Sequence\nfrom typing import Any\n\nlogger = logging.getLogger(__name__)\n\n_TS_INDENT = \" \"\n_TS_FIELD_DELIMITER = \",\\n\"\n\n\nclass _SchemaRegistry:\n \"\"\"Registry for schema definitions to handle $ref resolution\"\"\"\n\n def __init__(self):\n self.definitions = {}\n self.has_self_ref = False\n\n def register_definitions(self, defs: dict[str, Any]):\n \"\"\"Register schema definitions from $defs section\"\"\"\n if not defs:\n return\n for def_name, def_schema in defs.items():\n self.definitions[def_name] = def_schema\n\n def resolve_ref(self, ref: str) -> dict[str, Any]:\n \"\"\"Resolve a reference to its schema definition\"\"\"\n if ref == \"#\":\n self.has_self_ref = True\n return {\"$self_ref\": True}\n elif ref.startswith(\"#/$defs/\"):\n def_name = ref.split(\"/\")[-1]\n if def_name not in self.definitions:\n raise ValueError(f\"Reference not found: {ref}\")\n return self.definitions[def_name]\n else:\n raise ValueError(f\"Unsupported reference format: {ref}\")\n\n\ndef _format_description(description: str, indent: str = \"\") -> str:\n return \"\\n\".join([\n f\"{indent}// {line}\" if line else \"\"\n for line in description.split(\"\\n\")\n ])\n\n\nclass _BaseType:\n description: str\n constraints: dict[str, Any]\n\n def __init__(\n self,\n extra_props: dict[str, Any],\n *,\n allowed_constraint_keys: Sequence[str] = (),\n ):\n self.description = extra_props.get(\"description\", \"\")\n self.constraints = {\n k: v\n for k, v in extra_props.items() if k in allowed_constraint_keys\n }\n\n def to_typescript_style(self, indent: str = \"\") -> str:\n raise NotImplementedError\n\n def format_docstring(self, indent: str) -> str:\n lines = []\n if self.description:\n lines.append(_format_description(self.description, indent))\n if self.constraints:\n constraints_str = \", \".join(f\"{k}: {v}\" for k, v in sorted(\n self.constraints.items(), key=lambda kv: kv[0]))\n lines.append(f\"{indent}// {constraints_str}\")\n\n return \"\".join(x + \"\\n\" for x in lines)\n\n\nclass _ParameterTypeScalar(_BaseType):\n type: str\n\n def __init__(self, type: str, extra_props: dict[str, Any] | None = None):\n self.type = type\n\n allowed_constraint_keys: list[str] = []\n if self.type == \"string\":\n allowed_constraint_keys = [\"maxLength\", \"minLength\", \"pattern\"]\n elif self.type in (\"number\", \"integer\"):\n allowed_constraint_keys = [\"maximum\", \"minimum\"]\n\n super().__init__(extra_props or {},\n allowed_constraint_keys=allowed_constraint_keys)\n\n def to_typescript_style(self, indent: str = \"\") -> str:\n # Map integer to number in TypeScript\n if self.type == \"integer\":\n return \"number\"\n return self.type\n\n\nclass _ParameterTypeObject(_BaseType):\n properties: list[\"_Parameter\"]\n additional_properties: Any | None = None\n\n def __init__(self,\n json_schema_object: dict[str, Any],\n registry: _SchemaRegistry | None = None):\n super().__init__(json_schema_object)\n\n self.properties = []\n self.additional_properties = None\n\n if not json_schema_object:\n return\n\n if \"$defs\" in json_schema_object and registry:\n registry.register_definitions(json_schema_object[\"$defs\"])\n\n self.additional_properties = json_schema_object.get(\n \"additionalProperties\")\n if isinstance(self.additional_properties, dict):\n self.additional_properties = _parse_parameter_type(\n self.additional_properties, registry)\n\n if \"properties\" not in json_schema_object:\n return\n\n required_parameters = json_schema_object.get(\"required\", [])\n optional_parameters = set(\n json_schema_object[\"properties\"].keys()) - set(required_parameters)\n\n self.properties = [\n _Parameter(\n name=name,\n type=_parse_parameter_type(prop, registry),\n optional=name in optional_parameters,\n default=prop.get(\"default\")\n if isinstance(prop, dict) else None,\n ) for name, prop in json_schema_object[\"properties\"].items()\n ]\n\n def to_typescript_style(self, indent: str = \"\") -> str:\n # sort by optional, make the required parameters first\n parameters = [p for p in self.properties if not p.optional]\n opt_params = [p for p in self.properties if p.optional]\n\n parameters = sorted(parameters, key=lambda p: p.name)\n parameters.extend(sorted(opt_params, key=lambda p: p.name))\n\n param_strs = []\n for p in parameters:\n one = p.to_typescript_style(indent=indent + _TS_INDENT)\n param_strs.append(one)\n\n if self.additional_properties is not None:\n ap_type_str = \"any\"\n if self.additional_properties is True:\n ap_type_str = \"any\"\n elif self.additional_properties is False:\n ap_type_str = \"never\"\n elif isinstance(self.additional_properties, _ParameterType):\n ap_type_str = self.additional_properties.to_typescript_style(\n indent=indent + _TS_INDENT)\n else:\n raise ValueError(\n f\"Unknown additionalProperties: {self.additional_properties}\"\n )\n param_strs.append(\n f\"{indent + _TS_INDENT}[k: string]: {ap_type_str}\")\n\n if not param_strs:\n return \"{}\"\n\n params_str = _TS_FIELD_DELIMITER.join(param_strs)\n if params_str:\n # add new line before and after\n params_str = f\"\\n{params_str}\\n\"\n # always wrap with object\n return f\"{{{params_str}{indent}}}\"\n\n\nclass _ParameterTypeArray(_BaseType):\n item: \"_ParameterType\"\n\n def __init__(self,\n json_schema_object: dict[str, Any],\n registry: _SchemaRegistry | None = None):\n super().__init__(json_schema_object,\n allowed_constraint_keys=(\"minItems\", \"maxItems\"))\n if json_schema_object.get(\"items\"):\n self.item = _parse_parameter_type(json_schema_object[\"items\"],\n registry)\n else:\n self.item = _ParameterTypeScalar(type=\"any\")\n\n def to_typescript_style(self, indent: str = \"\") -> str:\n item_docstring = self.item.format_docstring(indent + _TS_INDENT)\n if item_docstring:\n return (\"Array<\\n\" + item_docstring + indent + _TS_INDENT +\n self.item.to_typescript_style(indent=indent + _TS_INDENT) +\n \"\\n\" + indent + \">\")\n else:\n return f\"Array<{self.item.to_typescript_style(indent=indent)}>\"\n\n\nclass _ParameterTypeEnum(_BaseType):\n # support scalar types only\n enum: list[str | int | float | bool | None]\n\n def __init__(self, json_schema_object: dict[str, Any]):\n super().__init__(json_schema_object)\n self.enum = json_schema_object[\"enum\"]\n\n # Validate enum values against declared type if present\n if \"type\" in json_schema_object:\n typ = json_schema_object[\"type\"]\n if isinstance(typ, list):\n if len(typ) == 1:\n typ = typ[0]\n elif len(typ) == 2:\n if \"null\" not in typ:\n raise ValueError(f\"Enum type {typ} is not supported\")\n else:\n typ = typ[0] if typ[0] != \"null\" else typ[1]\n else:\n raise ValueError(f\"Enum type {typ} is not supported\")\n for val in self.enum:\n if val is None:\n continue\n if typ == \"string\" and not isinstance(val, str):\n raise ValueError(f\"Enum value {val} is not a string\")\n elif typ == \"number\" and not isinstance(val, (int, float)):\n raise ValueError(f\"Enum value {val} is not a number\")\n elif typ == \"integer\" and not isinstance(val, int):\n raise ValueError(f\"Enum value {val} is not an integer\")\n elif typ == \"boolean\" and not isinstance(val, bool):\n raise ValueError(f\"Enum value {val} is not a boolean\")\n\n def to_typescript_style(self, indent: str = \"\") -> str:\n return \" | \".join(\n [f'\"{e}\"' if isinstance(e, str) else str(e) for e in self.enum])\n\n\nclass _ParameterTypeAnyOf(_BaseType):\n types: list[\"_ParameterType\"]\n\n def __init__(\n self,\n json_schema_object: dict[str, Any],\n registry: _SchemaRegistry | None = None,\n ):\n super().__init__(json_schema_object)\n self.types = [\n _parse_parameter_type(t, registry)\n for t in json_schema_object[\"anyOf\"]\n ]\n\n def to_typescript_style(self, indent: str = \"\") -> str:\n return \" | \".join(\n [t.to_typescript_style(indent=indent) for t in self.types])\n\n\nclass _ParameterTypeUnion(_BaseType):\n types: list[str]\n\n def __init__(self, json_schema_object: dict[str, Any]):\n super().__init__(json_schema_object)\n\n mapping = {\n \"string\": \"string\",\n \"number\": \"number\",\n \"integer\": \"number\",\n \"boolean\": \"boolean\",\n \"null\": \"null\",\n \"object\": \"{}\",\n \"array\": \"Array<any>\",\n }\n self.types = [mapping[t] for t in json_schema_object[\"type\"]]\n\n def to_typescript_style(self, indent: str = \"\") -> str:\n return \" | \".join(self.types)\n\n\nclass _ParameterTypeRef(_BaseType):\n ref_name: str\n is_self_ref: bool = False\n\n def __init__(self, json_schema_object: dict[str, Any],\n registry: _SchemaRegistry):\n super().__init__(json_schema_object)\n\n ref = json_schema_object[\"$ref\"]\n resolved_schema = registry.resolve_ref(ref)\n\n if resolved_schema.get(\"$self_ref\", False):\n self.ref_name = \"parameters\"\n self.is_self_ref = True\n else:\n self.ref_name = ref.split(\"/\")[-1]\n\n def to_typescript_style(self, indent: str = \"\") -> str:\n return self.ref_name\n\n\n_ParameterType = (_ParameterTypeScalar\n | _ParameterTypeObject\n | _ParameterTypeArray\n | _ParameterTypeEnum\n | _ParameterTypeAnyOf\n | _ParameterTypeUnion\n | _ParameterTypeRef)\n\n\n@dataclasses.dataclass\nclass _Parameter:\n \"\"\"\n A parameter in a function, or a field in a object.\n It consists of the type as well as the name.\n \"\"\"\n\n type: _ParameterType\n name: str = \"_\"\n optional: bool = True\n default: Any | None = None\n\n @classmethod\n def parse_extended(cls, attributes: dict[str, Any]) -> \"_Parameter\":\n if not attributes:\n raise ValueError(\"attributes is empty\")\n\n return cls(\n name=attributes.get(\"name\", \"_\"),\n type=_parse_parameter_type(attributes),\n optional=attributes.get(\"optional\", False),\n default=attributes.get(\"default\"),\n )\n\n def to_typescript_style(self, indent: str = \"\") -> str:\n comments = self.type.format_docstring(indent)\n\n if self.default is not None:\n default_repr = (json.dumps(self.default, ensure_ascii=False)\n if not isinstance(self.default, (int, float, bool))\n else repr(self.default))\n comments += f\"{indent}// Default: {default_repr}\\n\"\n\n return (\n comments +\n f\"{indent}{self.name}{'?' if self.optional else ''}: {self.type.to_typescript_style(indent=indent)}\"\n )\n\n\ndef _parse_parameter_type(\n json_schema_object: dict[str, Any] | bool,\n registry: _SchemaRegistry | None = None) -> _ParameterType:\n if isinstance(json_schema_object, bool):\n if json_schema_object:\n return _ParameterTypeScalar(type=\"any\")\n else:\n logger.warning(\n f\"Warning: Boolean value {json_schema_object} is not supported, use null instead.\"\n )\n return _ParameterTypeScalar(type=\"null\")\n\n if \"$ref\" in json_schema_object and registry:\n return _ParameterTypeRef(json_schema_object, registry)\n\n if \"anyOf\" in json_schema_object:\n return _ParameterTypeAnyOf(json_schema_object, registry)\n elif \"enum\" in json_schema_object:\n return _ParameterTypeEnum(json_schema_object)\n elif \"type\" in json_schema_object:\n typ = json_schema_object[\"type\"]\n if isinstance(typ, list):\n return _ParameterTypeUnion(json_schema_object)\n elif typ == \"object\":\n return _ParameterTypeObject(json_schema_object, registry)\n elif typ == \"array\":\n return _ParameterTypeArray(json_schema_object, registry)\n else:\n return _ParameterTypeScalar(typ, json_schema_object)\n elif json_schema_object == {}:\n return _ParameterTypeScalar(type=\"any\")\n else:\n raise ValueError(f\"Invalid JSON Schema object: {json_schema_object}\")\n\n\ndef _openai_function_to_typescript_style(function: dict[str, Any], ) -> str:\n \"\"\"Convert OpenAI function definition (dict) to TypeScript style string.\"\"\"\n registry = _SchemaRegistry()\n parameters = function.get(\"parameters\") or {}\n parsed = _ParameterTypeObject(parameters, registry)\n\n interfaces = []\n root_interface_name = None\n if registry.has_self_ref:\n root_interface_name = \"parameters\"\n params_str = _TS_FIELD_DELIMITER.join([\n p.to_typescript_style(indent=_TS_INDENT) for p in parsed.properties\n ])\n params_str = f\"\\n{params_str}\\n\" if params_str else \"\"\n interface_def = f\"interface {root_interface_name} {{{params_str}}}\"\n interfaces.append(interface_def)\n\n definitions_copy = dict(registry.definitions)\n for def_name, def_schema in definitions_copy.items():\n obj_type = _parse_parameter_type(def_schema, registry)\n params_str = obj_type.to_typescript_style()\n\n description_part = \"\"\n if obj_description := def_schema.get(\"description\", \"\"):\n description_part = _format_description(obj_description) + \"\\n\"\n\n interface_def = f\"{description_part}interface {def_name} {params_str}\"\n interfaces.append(interface_def)\n\n interface_str = \"\\n\".join(interfaces)\n function_name = function.get(\"name\", \"function\")\n if root_interface_name:\n type_def = f\"type {function_name} = (_: {root_interface_name}) => any;\"\n else:\n params_str = parsed.to_typescript_style()\n type_def = f\"type {function_name} = (_: {params_str}) => any;\"\n\n description = function.get(\"description\")\n return \"\\n\".join(\n filter(\n bool,\n [\n interface_str,\n ((description and _format_description(description)) or \"\"),\n type_def,\n ],\n ))\n\n\ndef encode_tools_to_typescript_style(tools: list[dict[str, Any]], ) -> str:\n \"\"\"\n Convert tools (list of dict) to TypeScript style string.\n \n Supports OpenAI format: {\"type\": \"function\", \"function\": {...}}\n \n Args:\n tools: List of tool definitions in dict format\n \n Returns:\n TypeScript style string representation of the tools\n \"\"\"\n if not tools:\n return \"\"\n\n functions = []\n\n for tool in tools:\n tool_type = tool.get(\"type\")\n if tool_type == \"function\":\n func_def = tool.get(\"function\", {})\n if func_def:\n functions.append(\n _openai_function_to_typescript_style(func_def))\n else:\n # Skip unsupported tool types (like \"_plugin\")\n continue\n\n if not functions:\n return \"\"\n\n functions_str = \"\\n\".join(functions)\n result = \"# Tools\\n\\n\"\n\n if functions_str:\n result += \"## functions\\nnamespace functions {\\n\"\n result += functions_str + \"\\n\"\n result += \"}\\n\"\n\n return result\n",
"templateHelperPath": "tool_declaration_ts.py",
"templateHelperUrl": "https://huggingface.co/moonshotai/Kimi-K2.6/blob/7eb5002f6aadc958aed6a9177b7ed26bb94011bb/tool_declaration_ts.py",
"bosToken": "[BOS]",
"eosToken": "[EOS]",
"padToken": "[PAD]",
"unkToken": "[UNK]",
"specialTokens": {
"[BOS]": 163584,
"[EOS]": 163585,
"<|im_end|>": 163586,
"<|im_user|>": 163587,
"<|im_assistant|>": 163588,
"<|start_header_id|>": 163590,
"<|end_header_id|>": 163591,
"[EOT]": 163593,
"<|im_system|>": 163594,
"<|tool_calls_section_begin|>": 163595,
"<|tool_calls_section_end|>": 163596,
"<|tool_call_begin|>": 163597,
"<|tool_call_argument_begin|>": 163598,
"<|tool_call_end|>": 163599,
"<|im_middle|>": 163601,
"<|media_begin|>": 163602,
"<|media_content|>": 163603,
"<|media_end|>": 163604,
"<|media_pad|>": 163605,
"<think>": 163606,
"</think>": 163607,
"[UNK]": 163838,
"[PAD]": 163839
},
"stopTokenCall": "<|im_end|>",
"stopTokenText": "<|im_end|>",
"dedicatedStopToken": false,
"stopKind": "shared",
"eosNote": "Kimi-K2.6 terminates both tool calls and normal replies with shared <|im_end|> (id 163586); tool calls are framed inside <|tool_calls_section_begin|>...<|tool_calls_section_end|>.",
"cap": "<code>chat_template.jinja</code> renders <code>tools_ts_str</code> when pre-formatted by Moonshot's optional <code>tool_declaration_ts.py</code> helper from the Hub repo (falling back to compact JSON otherwise). That helper rewrites JSON Schema into a TypeScript <code>namespace functions</code> block with <code>//</code> doc comments, converts <code>integer</code> to <code>number</code>, and moves <code>minimum</code>/<code>maximum</code> into comments.",
"outCap": "Kimi-K2.6 uses dedicated special tokens for the section, call wrapper, and argument boundary around plain-text <code>functions.name:0</code> and JSON arguments, then stops on shared <code><|im_end|></code>.",
"walkSteps": {
"s2": "When tools_ts_str is supplied by Moonshot's tool_declaration_ts.py helper, schemas become TypeScript interfaces in namespace functions (integer → number, bounds → // comments); otherwise chat_template.jinja falls back to compact JSON.",
"s3": "The template writes almost no extra calling prose—just a minimal # Tools header and the tool declarations inside <|im_system|>.",
"s4": "The rendered prompt ends with <|im_assistant|>assistant<|im_middle|><think>, opening the assistant's thinking channel.",
"s5": "After </think>, the model emits <|tool_calls_section_begin|><|tool_call_begin|>functions.<name>:0<|tool_call_argument_begin|>{json}<|tool_call_end|><|tool_calls_section_end|>.",
"s6": "vLLM's KimiK2 parser and SGLang's KimiK2Detector (keeping special tokens) split on <|tool_call_begin|> and <|tool_call_argument_begin|> to extract the ID and JSON arguments.",
"s7": "Generation stops on shared <|im_end|> (163586); on an ordinary completed auto-tool turn with parsed calls, the serving layer rewrites engine 'stop' to API finish_reason='tool_calls'."
},
"lane": [
"Reasoning text closes with </think>",
"<|tool_calls_section_begin|> opens tool section",
"<|tool_call_begin|> + functions.…:0 names the call",
"<|tool_call_argument_begin|> + JSON argument object",
"<|tool_call_end|> and <|tool_calls_section_end|> close section",
"<|im_end|> ends turn; sampler reports stop"
],
"laneText": [
"Reasoning text closes with </think>",
"Plain assistant answer text",
"<|im_end|> ends turn; sampler reports stop"
],
"excerpts": {
"vllm": [
{
"repo": "vllm",
"path": "vllm/parser/kimi_k2.py",
"start": 41,
"end": 66,
"hl": [
43,
44,
45,
46,
47,
49
],
"sha": "ef687f6179b752c028767e610addbda67ed36d03",
"url": "https://github.com/vllm-project/vllm/blob/ef687f6179b752c028767e610addbda67ed36d03/vllm/parser/kimi_k2.py#L41-L66",
"note": "vLLM's KimiK2 parser defines <|tool_calls_section_begin|>, <|tool_call_begin|>, <|tool_call_argument_begin|>, and the call-ID regex.",
"code": "THINK_START = \"<think>\"\nTHINK_END = \"</think>\"\nTOOL_SECTION_START = \"<|tool_calls_section_begin|>\"\nTOOL_SECTION_END = \"<|tool_calls_section_end|>\"\nTOOL_CALL_START = \"<|tool_call_begin|>\"\nTOOL_CALL_END = \"<|tool_call_end|>\"\nTOOL_ARG_START = \"<|tool_call_argument_begin|>\"\n\n_TOOL_ID_RE = re.compile(r\"(?P<id>.+:\\d+)\")\n\n\n@functools.cache\ndef kimi_k2_config(thinking: bool = True) -> ParserEngineConfig:\n reasoning_terminals = (\n {\n \"THINK_START\": THINK_START,\n \"THINK_END\": THINK_END,\n }\n if thinking\n else {}\n )\n reasoning_transitions = (\n {\n (ParserState.REASONING, \"THINK_START\"): Transition(\n ParserState.REASONING,\n (),"
}
],
"sglang": [
{
"repo": "sglang",
"path": "python/sglang/srt/function_call/kimik2_detector.py",
"start": 40,
"end": 64,
"hl": [
46,
47,
48,
62,
63
],
"sha": "1918da6349f9be1c62315503e1a7458a3957bc5f",
"url": "https://github.com/sgl-project/sglang/blob/1918da6349f9be1c62315503e1a7458a3957bc5f/python/sglang/srt/function_call/kimik2_detector.py#L40-L64",
"note": "SGLang's KimiK2Detector frames calls between <|tool_calls_section_begin|> and <|tool_calls_section_end|>.",
"code": "class KimiK2Detector(BaseFormatDetector):\n \"\"\"\n Detector for Kimi K2 / K2.5 model function call format.\n\n Format Structure (standard):\n ```\n <|tool_calls_section_begin|>\n <|tool_call_begin|>functions.{func_name}:{index}<|tool_call_argument_begin|>{json_args}<|tool_call_end|>\n <|tool_calls_section_end|>\n ```\n\n Format Structure (bare counter — model omits function name):\n ```\n <|tool_call_begin|>{counter}<|tool_call_argument_begin|>{json_args}<|tool_call_end|>\n ```\n\n Reference: https://huggingface.co/moonshotai/Kimi-K2-Instruct/blob/main/docs/tool_call_guidance.md\n \"\"\"\n\n def __init__(self):\n super().__init__()\n\n self.bot_token: str = \"<|tool_calls_section_begin|>\"\n self.eot_token: str = \"<|tool_calls_section_end|>\"\n"
}
]
}
},
{
"key": "kimi31",
"id": "moonshotai/Kimi-K3.1-Pro",
"label": "Kimi-K3.1-Pro",
"sub": "Python XTML",
"sha": "d9e99b0792a5e93b78ea9bea62a68167e36ddd9e",
"created": "2026-11-02",
"likes": 2424,
"templateKind": "python-xtml",
"schemaEncoding": "Deep-sorted JSON in XTML",
"callSyntax": "<|open|>call tool=…<|sep|>",
"servingNote": "Kimi-K3.1-Pro ships no Jinja template; vLLM (vllm/renderers/kimi_k3.py) and SGLang call encoding_k3.py's native Python XTML encoder directly.",
"chatTemplate": "\"\"\"Kimi K3 XTML encoding helpers.\n\nThis module keeps chat rendering in Python.\nCallers that need token IDs should consume ``EncodeSegment`` objects directly:\nstructural markers may be encoded as tiktoken special tokens, while user/tool\ntext and attribute values are encoded as ordinary text.\n\"\"\"\n\nfrom __future__ import annotations\n\nimport json\nfrom dataclasses import dataclass\nfrom typing import Any, Iterable, Optional\n\nOPEN_TOKEN = \"<|open|>\"\nCLOSE_TOKEN = \"<|close|>\"\nSEP_TOKEN = \"<|sep|>\"\nEND_OF_MSG_TOKEN = \"<|end_of_msg|>\"\nIMAGE_PLACEHOLDER = \"<|kimi_image_placeholder|>\"\n\n_VALID_THINKING_EFFORTS = {\"low\", \"high\", \"max\"}\n\n\n@dataclass(frozen=True)\nclass EncodeSegment:\n text: str\n allow_special: bool = False\n\n\nclass _ImagePromptState:\n\n def __init__(self, image_prompts: Optional[list[str]] = None):\n self.image_prompts = image_prompts\n self.index = 0\n\n def next_prompt(self) -> str:\n if self.image_prompts is None:\n return IMAGE_PLACEHOLDER\n if self.index >= len(self.image_prompts):\n raise ValueError(\"More image placeholders than image prompts.\")\n prompt = self.image_prompts[self.index]\n self.index += 1\n return prompt\n\n def assert_consumed(self) -> None:\n if self.image_prompts is None:\n return\n if self.index != len(self.image_prompts):\n raise ValueError(\n f\"image prompt count {len(self.image_prompts)} != \"\n f\"consumed placeholder count {self.index}\")\n\n\ndef _segment(text: Any, *, allow_special: bool = False) -> list[EncodeSegment]:\n text = str(text)\n if not text:\n return []\n return [EncodeSegment(text, allow_special=allow_special)]\n\n\ndef _control(text: str) -> list[EncodeSegment]:\n return _segment(text, allow_special=True)\n\n\ndef _text(text: Any) -> list[EncodeSegment]:\n return _segment(text, allow_special=False)\n\n\ndef _append_text(\n segments: list[EncodeSegment],\n text: Any,\n image_state: _ImagePromptState,\n) -> None:\n text = str(text)\n if text == \"\":\n return\n if image_state.image_prompts is None or IMAGE_PLACEHOLDER not in text:\n segments.extend(_text(text))\n return\n\n parts = text.split(IMAGE_PLACEHOLDER)\n for i, part in enumerate(parts):\n segments.extend(_text(part))\n if i < len(parts) - 1:\n segments.extend(\n _segment(image_state.next_prompt(), allow_special=True))\n\n\ndef _escape_attr_value(value: Any) -> str:\n return str(value).replace(\"&\", \"&\").replace('\"', \""\")\n\n\ndef _attr(key: str, value: Any) -> list[EncodeSegment]:\n return (_text(f\" {key}\") + _text('=\"') + _text(_escape_attr_value(value)) +\n _text('\"'))\n\n\ndef _open_tag(\n tag: str, attrs: Iterable[tuple[str, Any]] = ()) -> list[EncodeSegment]:\n segments: list[EncodeSegment] = []\n segments.extend(_control(OPEN_TOKEN))\n segments.extend(_text(tag))\n for key, value in attrs:\n segments.extend(_attr(key, value))\n segments.extend(_control(SEP_TOKEN))\n return segments\n\n\ndef _close_tag(tag: str) -> list[EncodeSegment]:\n segments: list[EncodeSegment] = []\n segments.extend(_control(CLOSE_TOKEN))\n segments.extend(_text(tag))\n segments.extend(_control(SEP_TOKEN))\n return segments\n\n\ndef _end_of_msg() -> list[EncodeSegment]:\n return _control(END_OF_MSG_TOKEN)\n\n\ndef _json_compact(value: Any) -> str:\n return json.dumps(value, ensure_ascii=False, separators=(\",\", \":\"))\n\n\ndef _is_mapping(value: Any) -> bool:\n return isinstance(value, dict)\n\n\ndef _xtml_type(value: Any) -> str:\n if isinstance(value, bool):\n return \"boolean\"\n if value is None:\n return \"null\"\n if isinstance(value, (int, float)) and not isinstance(value, bool):\n return \"number\"\n if isinstance(value, str):\n return \"string\"\n if _is_mapping(value):\n return \"object\"\n return \"array\"\n\n\ndef _xtml_value(value: Any) -> str:\n if isinstance(value, str):\n return value\n return json.dumps(value, ensure_ascii=False)\n\n\ndef _get_value(obj: Any, key: str, default: Any = None) -> Any:\n if isinstance(obj, dict):\n return obj.get(key, default)\n return getattr(obj, key, default)\n\n\ndef extract_response_schema(response_format: Any) -> Any:\n if response_format is None:\n return None\n\n json_schema = _get_value(response_format, \"json_schema\")\n if json_schema is None:\n return None\n\n if isinstance(json_schema, dict):\n return json_schema.get(\n \"schema\",\n json_schema.get(\"json_schema\", json_schema),\n )\n\n schema = _get_value(json_schema, \"schema\")\n if schema is not None:\n return schema\n\n schema = _get_value(json_schema, \"json_schema\")\n if schema is not None:\n return schema\n\n return json_schema\n\n\ndef deep_sort_dict(obj: Any) -> Any:\n if isinstance(obj, dict):\n return {k: deep_sort_dict(v) for k, v in sorted(obj.items())}\n if isinstance(obj, list):\n return [deep_sort_dict(item) for item in obj]\n return obj\n\n\n# One normalized tool-call argument: (key, XTML type, rendered text). The\n# text keeps the original JSON literal for non-string values and is the\n# decoded string for string values.\nXtmlArgument = tuple[str, str, str]\n\n\ndef _parse_arguments_object(s: str) -> list[XtmlArgument]:\n \"\"\"Parse a JSON object string one level deep.\n\n Each top-level key-value pair yields one ``(key, type, text)`` triple. The\n text keeps the original JSON literal for non-string values (``1e2`` stays\n ``1e2``, ``[1,2]`` keeps its exact bytes) and is the decoded (unescaped)\n string for string values. Nested values are never re-serialized. Anything\n after the closing ``}`` is ignored. Raises ``ValueError`` on malformed\n input (including a valid non-object JSON document).\n \"\"\"\n idx = 0\n\n def _skip_whitespaces() -> None:\n nonlocal idx\n while idx < len(s) and s[idx] in (\" \", \"\\t\", \"\\n\", \"\\r\"):\n idx += 1\n\n def _next_char() -> Optional[str]:\n nonlocal idx\n if idx < len(s):\n c = s[idx]\n idx += 1\n return c\n return None\n\n _skip_whitespaces()\n if _next_char() != \"{\":\n raise ValueError(\"JSON arguments must be an object\")\n _skip_whitespaces()\n\n parsed: list[XtmlArgument] = []\n\n if idx >= len(s):\n raise ValueError(\"Unexpected end of JSON object\")\n if s[idx] == \"}\":\n return parsed\n\n json_decoder = json.JSONDecoder(strict=False)\n\n def _raw_decode(start_idx: int) -> tuple[Any, int]:\n try:\n return json_decoder.raw_decode(s, idx=start_idx)\n except json.JSONDecodeError as e:\n raise ValueError(str(e)) from e\n\n while True:\n decoded_key, idx = _raw_decode(idx)\n if not isinstance(decoded_key, str):\n raise ValueError(\n f\"JSON object key must be a string, got {decoded_key!r}\")\n _skip_whitespaces()\n if _next_char() != \":\":\n raise ValueError(f\"Expects ':' after {decoded_key}\")\n _skip_whitespaces()\n\n value_start_idx = idx\n decoded_value, idx = _raw_decode(idx)\n value_end_idx = idx\n\n text = (decoded_value if isinstance(decoded_value, str) else\n s[value_start_idx:value_end_idx])\n parsed.append((decoded_key, _xtml_type(decoded_value), text))\n\n _skip_whitespaces()\n c = _next_char()\n _skip_whitespaces()\n\n if c == \"}\":\n break\n elif c == \",\":\n continue\n else:\n raise ValueError(f\"Expect '}}' or ',', got {c!r}\")\n\n return parsed\n\n\ndef normalize_tool_arguments(\n arguments: Any, ) -> tuple[list[XtmlArgument], Optional[str]]:\n \"\"\"Normalize tool call arguments for XTML rendering.\n\n Returns ``(argument_triples, raw_json_block)``. String arguments are parsed\n one level deep so non-string values keep their original JSON literal text,\n and anything after the closing ``}`` is discarded; dict arguments (already\n Python objects) are serialized on the spot. Any string that is not a\n well-formed JSON object -- unparsable, whitespace only, or valid\n non-object JSON -- falls back to the raw ``<json>`` block.\n \"\"\"\n if arguments is None:\n return [], None\n if isinstance(arguments, dict):\n return [(str(key), _xtml_type(value), _xtml_value(value))\n for key, value in arguments.items()], None\n if isinstance(arguments, str):\n if arguments == \"\":\n return [], None\n try:\n return _parse_arguments_object(arguments), None\n except ValueError:\n return [], arguments\n raise TypeError(\n \"Kimi K3 tool call arguments must be a dict or a JSON object string.\")\n\n\ndef normalize_message(message: Any) -> Any:\n if not isinstance(message, dict):\n return message\n\n normalized = dict(message)\n\n tools = normalized.get(\"tools\")\n if tools is not None:\n normalized[\"tools\"] = deep_sort_dict(tools)\n\n tool_calls = normalized.get(\"tool_calls\")\n if not tool_calls:\n return normalized\n\n normalized_calls = []\n for tool_call in tool_calls:\n if not isinstance(tool_call, dict):\n normalized_calls.append(tool_call)\n continue\n\n tc = dict(tool_call)\n function = tc.get(\"function\")\n if isinstance(function, dict):\n fn = dict(function)\n arguments, json_block = normalize_tool_arguments(\n fn.get(\"arguments\"))\n fn[\"arguments\"] = arguments\n if json_block is None:\n fn.pop(\"_xtml_json_block\", None)\n else:\n fn[\"_xtml_json_block\"] = json_block\n tc[\"function\"] = fn\n else:\n arguments, json_block = normalize_tool_arguments(\n tc.get(\"arguments\"))\n tc[\"arguments\"] = arguments\n if json_block is None:\n tc.pop(\"_xtml_json_block\", None)\n else:\n tc[\"_xtml_json_block\"] = json_block\n normalized_calls.append(tc)\n\n normalized[\"tool_calls\"] = normalized_calls\n return normalized\n\n\ndef normalize_conversation(conversation: Any) -> Any:\n if not isinstance(conversation, list):\n return conversation\n\n def normalize_messages(messages: list[Any]) -> list[Any]:\n return [normalize_message(message) for message in messages]\n\n if conversation and isinstance(conversation[0], list):\n return [normalize_messages(messages) for messages in conversation]\n return normalize_messages(conversation)\n\n\ndef _tool_call_id_index(tool_calls: Any) -> dict:\n \"\"\"Map assistant ``tool_calls[].id`` to ``(1-based position, function name)``.\n\n The position mirrors the chat template's enumeration over ``tool_calls``\n (every entry advances the position, even an id-less one). Duplicate ids keep\n their first occurrence.\n \"\"\"\n index: dict = {}\n if not isinstance(tool_calls, list):\n return index\n for position, tool_call in enumerate(tool_calls, start=1):\n if not isinstance(tool_call, dict):\n continue\n call_id = tool_call.get(\"id\")\n if call_id is None:\n continue\n key = str(call_id)\n if key in index:\n continue\n function = tool_call.get(\"function\")\n name = (function.get(\"name\")\n if isinstance(function, dict) else tool_call.get(\"name\"))\n index[key] = (position, name)\n return index\n\n\ndef normalize_xtml_tool_result_messages(messages: list[Any]) -> list[Any]:\n \"\"\"Re-sort K3 XTML tool results into assistant ``tool_calls`` order.\n\n Serving frameworks generally deliver tool results already in call order. A\n direct Transformers caller, however, may pass OpenAI-style tool messages in any\n order, so each run of consecutive tool messages is matched against the most\n recent preceding assistant ``tool_calls`` by opaque ``tool_call_id`` ==\n ``tool_calls[].id`` (K3 drops the ``func:index`` format requirement) and\n sorted by the matched 1-based position. The matched call is authoritative,\n so each matched message's ``tool`` is set to that call's function name --\n this keeps an explicit (and possibly stale) ``tool``/``name`` from drifting\n out of sync with the reordered position. ``index`` is still derived from the\n rendered position by the chat template. A run that cannot be fully matched is\n left untouched. Re-running is idempotent.\n\n This function is side-effect free: matched tool messages are shallow-copied\n before their ``tool``/``name`` is rewritten, and every other message is\n appended to the output as-is. The input list and its message objects are\n never mutated.\n \"\"\"\n if not isinstance(messages, list):\n return messages\n\n output: list[Any] = []\n current_index: dict = {}\n i = 0\n n = len(messages)\n\n while i < n:\n message = messages[i]\n\n if isinstance(message, dict) and message.get(\"role\") == \"assistant\":\n tool_calls = message.get(\"tool_calls\")\n current_index = _tool_call_id_index(\n tool_calls) if tool_calls else {}\n output.append(message)\n i += 1\n continue\n\n if not isinstance(message, dict) or message.get(\"role\") != \"tool\":\n output.append(message)\n i += 1\n continue\n\n run: list[tuple] = [] # (position, original_offset, message, name)\n unresolved = False\n offset = 0\n while (i < n and isinstance(messages[i], dict)\n and messages[i].get(\"role\") == \"tool\"):\n tool_message = messages[i]\n call_id = tool_message.get(\"tool_call_id\", tool_message.get(\"id\"))\n matched = current_index.get(\n str(call_id)) if call_id is not None else None\n if matched is None:\n unresolved = True\n run.append((None, offset, tool_message, None))\n else:\n position, name = matched\n run.append((position, offset, tool_message, name))\n offset += 1\n i += 1\n\n if unresolved:\n output.extend(item[2] for item in run)\n else:\n run.sort(key=lambda item: (item[0], item[1]))\n for _, _, tool_message, name in run:\n if name is None:\n output.append(tool_message)\n continue\n # The id-matched call is authoritative: align tool (and any\n # explicit name) so the rendered XTML tool attribute cannot\n # disagree with the reordered position. Copy first so the\n # caller's message object is never mutated.\n resolved = dict(tool_message)\n resolved[\"tool\"] = name\n if \"name\" in resolved:\n resolved[\"name\"] = name\n output.append(resolved)\n\n return output\n\n\ndef is_batched_conversation(conversation: Any) -> bool:\n return (isinstance(conversation, list) and bool(conversation)\n and isinstance(conversation[0], list))\n\n\ndef _render_content_segments(\n content: Any,\n image_state: _ImagePromptState,\n) -> list[EncodeSegment]:\n segments: list[EncodeSegment] = []\n if isinstance(content, str):\n _append_text(segments, content, image_state)\n elif content is not None:\n for part in content:\n if part[\"type\"] in [\"image\", \"image_url\"]:\n segments.extend(\n _segment(image_state.next_prompt(), allow_special=True))\n else:\n _append_text(segments, part[\"text\"], image_state)\n return segments\n\n\ndef _internal_system_message(message_type: str,\n body: str) -> list[EncodeSegment]:\n segments: list[EncodeSegment] = []\n segments.extend(\n _open_tag(\"message\", [(\"role\", \"system\"), (\"type\", message_type)]))\n segments.extend(_text(body.strip()))\n segments.extend(_close_tag(\"message\"))\n segments.extend(_end_of_msg())\n return segments\n\n\ndef _render_assistant_segments(\n message: dict[str, Any],\n image_state: _ImagePromptState,\n thinking: bool = True,\n) -> list[EncodeSegment]:\n segments: list[EncodeSegment] = []\n # The <think> channel is structural: in thinking mode every assistant\n # message carries the open/close tags even when there is no reasoning\n # content to fill in. In non-thinking mode the channel is dropped\n # entirely.\n if thinking:\n reasoning_content = message.get(\"reasoning_content\") or message.get(\n \"reasoning\")\n segments.extend(_open_tag(\"think\"))\n # Only an empty string counts as no reasoning, so whitespace-only\n # reasoning is still rendered into the think channel.\n if reasoning_content is not None and str(reasoning_content) != \"\":\n _append_text(segments, reasoning_content, image_state)\n segments.extend(_close_tag(\"think\"))\n\n segments.extend(_open_tag(\"response\"))\n segments.extend(\n _render_content_segments(message.get(\"content\"), image_state))\n segments.extend(_close_tag(\"response\"))\n\n tool_calls = message.get(\"tool_calls\")\n if tool_calls:\n segments.extend(_open_tag(\"tools\"))\n for index, tool_call in enumerate(tool_calls, start=1):\n fn = tool_call.get(\"function\", tool_call)\n segments.extend(\n _open_tag(\"call\", [(\"tool\", fn[\"name\"]), (\"index\", index)]))\n args = fn.get(\"arguments\", [])\n json_block = fn.get(\"_xtml_json_block\")\n if json_block is not None:\n segments.extend(_open_tag(\"json\", [(\"type\", \"object\")]))\n _append_text(segments, json_block, image_state)\n segments.extend(_close_tag(\"json\"))\n else:\n for key, arg_type, arg_text in args:\n segments.extend(\n _open_tag(\"argument\", [(\"key\", key),\n (\"type\", arg_type)]))\n _append_text(segments, arg_text, image_state)\n segments.extend(_close_tag(\"argument\"))\n segments.extend(_close_tag(\"call\"))\n segments.extend(_close_tag(\"tools\"))\n\n return segments\n\n\ndef _render_tool_declare(tools: Any,\n *,\n dynamic: bool = False) -> list[EncodeSegment]:\n if dynamic:\n body = (\n \"## New Tools Available\\n\"\n \"The system dynamically extends the toolset via lazy-loading.\\n\"\n \"You have access to all existing and extended tools.\\n\"\n \"Here are the specs for the extended tools.\\n\\n\"\n \"```json\\n\"\n f\"{_json_compact(tools)}\\n\"\n \"```\")\n else:\n body = (\"# Tools\\n\"\n \"Here are the available tools, described in JSONSchema.\\n\\n\"\n \"```json\\n\"\n f\"{_json_compact(tools)}\\n\"\n \"```\")\n segments: list[EncodeSegment] = []\n segments.extend(\n _open_tag(\"message\", [(\"role\", \"system\"), (\"type\", \"tool-declare\")]))\n segments.extend(_text(body))\n segments.extend(_close_tag(\"message\"))\n segments.extend(_end_of_msg())\n return segments\n\n\ndef build_chat_segments(\n messages: list[Any],\n tools: Optional[list[dict]] = None,\n *,\n add_generation_prompt: bool = True,\n thinking: bool = True,\n image_prompts: Optional[list[str]] = None,\n **kwargs: Any,\n) -> list[EncodeSegment]:\n # Re-sort tool results by tool_call_id at the lowest layer so every caller\n # (processor or direct tokenizer) gets correctly ordered XTML. The helper is\n # side-effect free, so the caller's message objects are left untouched.\n messages = normalize_xtml_tool_result_messages(messages)\n messages = normalize_conversation(messages)\n tools = deep_sort_dict(tools)\n\n kwargs = dict(kwargs)\n response_format = kwargs.get(\"response_format\")\n if \"response_schema\" not in kwargs:\n response_schema = extract_response_schema(response_format)\n if response_schema is not None:\n kwargs[\"response_schema\"] = response_schema\n if kwargs.get(\"response_schema\") is not None:\n kwargs[\"response_schema\"] = deep_sort_dict(kwargs[\"response_schema\"])\n\n image_state = _ImagePromptState(image_prompts)\n segments: list[EncodeSegment] = []\n\n tool_calls = None\n tool_index = 0\n\n if tools:\n segments.extend(_render_tool_declare(tools))\n\n thinking_effort = kwargs.get(\"thinking_effort\")\n if thinking and thinking_effort is not None:\n assert thinking_effort in _VALID_THINKING_EFFORTS, (\n f\"Unsupported thinking_effort={thinking_effort!r}; \"\n f\"supported values are {sorted(_VALID_THINKING_EFFORTS)}.\")\n if thinking and thinking_effort in _VALID_THINKING_EFFORTS:\n segments.extend(\n _internal_system_message(\n \"thinking-effort\",\n \"`thinking_effort` guides on how much to think in your \"\n \"thinking channel (not including the response channel), \"\n \"supported values include `low`, `medium`, `high`, and `max`.\\n\"\n f\"Now the system is invoked with `thinking_effort={thinking_effort}`.\",\n ))\n\n for message_index, message in enumerate(messages):\n # Malformed messages are rejected instead of being silently skipped.\n if not isinstance(message, dict):\n raise ValueError(\n f\"Kimi K3 messages must be dicts, got {type(message).__name__} \"\n f\"at index {message_index}.\")\n\n role = message.get(\"role\")\n if role == \"user\":\n attrs = [(\"role\", \"user\")]\n if message.get(\"name\"):\n attrs.append((\"name\", message[\"name\"]))\n segments.extend(_open_tag(\"message\", attrs))\n segments.extend(\n _render_content_segments(message.get(\"content\"), image_state))\n segments.extend(_close_tag(\"message\"))\n segments.extend(_end_of_msg())\n elif role == \"system\" and message.get(\"tools\"):\n segments.extend(\n _render_tool_declare(message[\"tools\"], dynamic=True))\n elif role == \"system\":\n attrs = [(\"role\", \"system\")]\n if message.get(\"name\"):\n attrs.append((\"name\", message[\"name\"]))\n segments.extend(_open_tag(\"message\", attrs))\n segments.extend(\n _render_content_segments(message.get(\"content\"), image_state))\n segments.extend(_close_tag(\"message\"))\n segments.extend(_end_of_msg())\n elif role == \"tool\":\n tool_index += 1\n tool_name = message.get(\"tool\", message.get(\"name\"))\n if (tool_name is None and tool_calls is not None\n and tool_index <= len(tool_calls)):\n tc = tool_calls[tool_index - 1]\n fn = tc.get(\"function\", tc)\n tool_name = fn[\"name\"]\n if tool_name is None:\n raise ValueError(\n \"Kimi K3 tool messages need a resolvable tool name: \"\n \"carry `tool`/`name`, or match a preceding assistant \"\n \"tool_call by order.\")\n segments.extend(\n _open_tag(\n \"message\",\n [(\"role\", \"tool\"), (\"tool\", tool_name),\n (\"index\", tool_index)],\n ))\n segments.extend(\n _render_content_segments(message.get(\"content\"), image_state))\n segments.extend(_close_tag(\"message\"))\n segments.extend(_end_of_msg())\n elif role == \"assistant\":\n tool_calls = message.get(\"tool_calls\")\n tool_index = 0\n attrs = [(\"role\", \"assistant\")]\n if message.get(\"name\"):\n attrs.append((\"name\", message[\"name\"]))\n segments.extend(_open_tag(\"message\", attrs))\n segments.extend(\n _render_assistant_segments(message, image_state, thinking))\n segments.extend(_close_tag(\"message\"))\n segments.extend(_end_of_msg())\n else:\n raise ValueError(\n f\"Unknown message role {role!r} at index {message_index}.\")\n\n tool_choice = kwargs.get(\"tool_choice\")\n if tool_choice == \"required\":\n segments.extend(\n _internal_system_message(\n \"tool-choice\",\n \"The system is invoked with `tool_choice=required`.\\n\"\n \"You MUST call tools in the next message.\",\n ))\n elif tool_choice == \"none\":\n segments.extend(\n _internal_system_message(\n \"tool-choice\",\n \"The system is invoked with `tool_choice=none`.\\n\"\n \"You MUST NOT call any tools in the next message.\",\n ))\n\n rf = kwargs.get(\"response_format\")\n rf_type = _get_value(rf, \"type\", rf) if isinstance(rf, dict) else rf\n if rf_type == \"json_object\":\n segments.extend(\n _internal_system_message(\n \"response-format\",\n \"The system is invoked with `response_format=json_object`.\\n\"\n \"Your response must be raw JSON data without markdown code \"\n \"blocks (```json) or any additional formatting.\",\n ))\n elif rf_type == \"json_schema\":\n schema = _json_compact(kwargs.get(\"response_schema\"))\n segments.extend(\n _internal_system_message(\n \"response-format\",\n \"The system is invoked with `response_format=json_schema`.\\n\"\n \"Your response must be raw JSON data without markdown code \"\n \"blocks (```json) or any additional formatting.\\n\"\n \"The JSON data must match the following schema:\\n\"\n f\"```json\\n{schema}\\n```\",\n ))\n\n if add_generation_prompt:\n segments.extend(_open_tag(\"message\", [(\"role\", \"assistant\")]))\n segments.extend(_open_tag(\"think\" if thinking else \"response\"))\n\n image_state.assert_consumed()\n return segments\n",
"templatePath": "encoding_k3.py",
"templateUrl": "https://huggingface.co/moonshotai/Kimi-K3.1-Pro/blob/d9e99b0792a5e93b78ea9bea62a68167e36ddd9e/encoding_k3.py",
"templateToolLines": [
549,
574
],
"templateHelperSource": null,
"templateHelperPath": null,
"templateHelperUrl": null,
"bosToken": "[BOS]",
"eosToken": "[EOS]",
"padToken": "[PAD]",
"unkToken": "[UNK]",
"specialTokens": {
"[BOS]": 163584,
"[EOS]": 163585,
"<|end_of_msg|>": 163586,
"<|open|>": 163587,
"<|close|>": 163588,
"<|sep|>": 163589,
"[start_header_id]": 163590,
"[end_header_id]": 163591,
"[EOT]": 163593,
"<|media_begin|>": 163602,
"<|media_content|>": 163603,
"<|media_end|>": 163604,
"<|media_pad|>": 163605,
"<osagent_mode>": 163649,
"[UNK]": 163838,
"[PAD]": 163839
},
"stopTokenCall": "<|end_of_msg|>",
"stopTokenText": "<|end_of_msg|>",
"dedicatedStopToken": false,
"stopKind": "shared",
"eosNote": "Kimi-K3.1-Pro ends every assistant message with <|close|>message<|sep|><|end_of_msg|> (id 163586), whether or not an <|open|>tools<|sep|> block appeared.",
"cap": "Kimi-K3.1-Pro drops Jinja and TypeScript altogether, using Python <code>encoding_k3.py</code> to emit XTML control tokens (<code><|open|></code>, <code><|sep|></code>, <code><|close|></code>). Tools are deep-key-sorted and serialized as compact JSON inside a <code>type=\"tool-declare\"</code> system message.",
"outCap": "Every assistant turn emits <code><|open|>think</code>, <code><|open|>response</code>, and optionally <code><|open|>tools</code> with typed <code><|open|>argument key=... type=...</code> elements.",
"walkSteps": {
"s2": "encoding_k3.py recursively sorts all schema keys with deep_sort_dict() and serializes the tools array as compact JSON inside a Markdown ```json fence.",
"s3": "It adds a brief two-line # Tools header inside <|open|>message role=\"system\" type=\"tool-declare\"<|sep|> without verbose calling examples.",
"s4": "The rendered prompt ends with <|open|>message role=\"assistant\"<|sep|><|open|>think<|sep|>, opening the assistant thinking element.",
"s5": "After closing think and response, the model opens <|open|>tools<|sep|><|open|>call tool=\"…\" index=\"1\"<|sep|> with typed <|open|>argument key=\"…\" type=\"…\"<|sep|> elements.",
"s6": "vLLM's KimiK3ToolParser and SGLang's KimiK3Detector match XTML control-token tags (<|open|>, <|sep|>, <|close|>) and unescape attribute entities.",
"s7": "The turn closes with <|close|>message<|sep|><|end_of_msg|> (163586) for both calls and text; parsed calls rewrite engine 'stop' to API finish_reason='tool_calls'."
},
"lane": [
"<|open|>think<|sep|> … <|close|>think<|sep|> reasoning + empty response",
"<|open|>tools<|sep|> opens tool block",
"<|open|>call tool=\"…\" index=\"1\"<|sep|> names the tool",
"<|open|>argument key=\"…\" type=\"…\"<|sep|> typed values",
"<|close|>call<|sep|> and <|close|>tools<|sep|> close tool block",
"<|close|>message<|sep|><|end_of_msg|> ends turn; sampler reports stop"
],
"laneText": [
"<|open|>think<|sep|> … <|close|>think<|sep|> reasoning",
"<|open|>response<|sep|> … <|close|>response<|sep|> answer text",
"<|close|>message<|sep|><|end_of_msg|> ends turn; sampler reports stop"
],
"excerpts": {
"vllm": [
{
"repo": "vllm",
"path": "vllm/tool_parsers/kimi_k3_tool_parser.py",
"start": 82,
"end": 108,
"hl": [
85,
86,
101,
102,
106
],
"sha": "ef687f6179b752c028767e610addbda67ed36d03",
"url": "https://github.com/vllm-project/vllm/blob/ef687f6179b752c028767e610addbda67ed36d03/vllm/tool_parsers/kimi_k3_tool_parser.py#L82-L108",
"note": "vLLM's KimiK3ToolParser defines XTML open/close markers and regexes for tools and call tags.",
"code": " def __init__(self, tokenizer: TokenizerLike, tools: list[Tool] | None = None):\n super().__init__(tokenizer, tools)\n\n self.tools_open = \"<|open|>tools<|sep|>\"\n self.tools_close = \"<|close|>tools<|sep|>\"\n self.response_open = \"<|open|>response<|sep|>\"\n self.response_close = \"<|close|>response<|sep|>\"\n\n # Regexes operate on detokenized text. The XTML markers reach us as the\n # literal strings <|open|>/<|close|>/<|sep|>. adjust_request keeps them\n # from being stripped and suppresses spacing between adjacent token\n # pieces. As DEFENSE-IN-DEPTH we still tolerate optional whitespace\n # WITHIN a marker (e.g. \"<|open|> tools <|sep|>\") in case some serving\n # path leaves vLLM's added-token spacing on -- this `\\s*` is a no-op on\n # clean input, so the normal byte-exact path is unaffected. We do NOT\n # strip body whitespace, so clean content stays byte-exact.\n # All bodies use non-greedy (.*?) so each block stops at its own first\n # closing marker -- see the module-level KNOWN LIMITATION about\n # literal-marker values.\n self._tools_open_re = re.compile(_O + r\"\\s*tools\\s*\" + _S)\n self._tools_close_re = re.compile(_C + r\"\\s*tools\\s*\" + _S)\n self._response_open_re = re.compile(_O + r\"\\s*response\\s*\" + _S)\n self._response_close_re = re.compile(_C + r\"\\s*response\\s*\" + _S)\n self._message_close_re = re.compile(_C + r\"\\s*message\\s*\" + _S)\n self._call_re = re.compile(\n _O\n + r\"\\s*call\\s+(?P<attrs>\""
}
],
"sglang": [
{
"repo": "sglang",
"path": "python/sglang/srt/function_call/kimik3_format.py",
"start": 3,
"end": 24,
"hl": [
7,
8,
10,
11,
12
],
"sha": "1918da6349f9be1c62315503e1a7458a3957bc5f",
"url": "https://github.com/sgl-project/sglang/blob/1918da6349f9be1c62315503e1a7458a3957bc5f/python/sglang/srt/function_call/kimik3_format.py#L3-L24",
"note": "SGLang's kimik3_format defines exact XTML open/close constants for streaming detection.",
"code": "THINK_OPEN = \"<|open|>think<|sep|>\"\nTHINK_CLOSE = \"<|close|>think<|sep|>\"\nRESPONSE_OPEN = \"<|open|>response<|sep|>\"\nRESPONSE_CLOSE = \"<|close|>response<|sep|>\"\nTOOLS_OPEN = \"<|open|>tools<|sep|>\"\nTOOLS_CLOSE = \"<|close|>tools<|sep|>\"\nMESSAGE_CLOSE = \"<|close|>message<|sep|>\"\nCALL_OPEN = \"<|open|>call\"\nCALL_CLOSE = \"<|close|>call<|sep|>\"\nARGUMENT_CLOSE = \"<|close|>argument<|sep|>\"\n\n# max_tokens can stop after an XTML control token or channel name, before <|sep|>.\n_PARTIAL_MARKER_SUFFIXES = (\n \"<|open|>\",\n \"<|close|>\",\n THINK_CLOSE.removesuffix(\"<|sep|>\"),\n RESPONSE_OPEN.removesuffix(\"<|sep|>\"),\n RESPONSE_CLOSE.removesuffix(\"<|sep|>\"),\n TOOLS_OPEN.removesuffix(\"<|sep|>\"),\n TOOLS_CLOSE.removesuffix(\"<|sep|>\"),\n MESSAGE_CLOSE.removesuffix(\"<|sep|>\"),\n)"
}
]
}
},
{
"key": "glm53",
"id": "zai-org/GLM-5.3-Flash",
"label": "GLM-5.3-Flash",
"sub": "arg_key / arg_value",
"sha": "46a050bec13002ad29ee795c16e61cf4fa3c4a9c",
"created": "2026-08-25",
"likes": 3306,
"templateKind": "jinja",
"schemaEncoding": "JSON in <tools>",
"callSyntax": "<tool_call>fn<arg_key>…",
"servingNote": "vLLM (glm47_moe) and SGLang (glm47_moe_detector) parse <tool_call>name<arg_key>k</arg_key><arg_value>v</arg_value></tool_call> with schema-driven type coercion.",
"chatTemplate": "[gMASK]<sop>\n{%- set effective_reasoning_effort = reasoning_effort if reasoning_effort is defined and reasoning_effort in ['low', 'high'] else 'max' -%}\n{%- if effective_reasoning_effort is not none -%}<|system|>Reasoning Effort: {{ effective_reasoning_effort | capitalize }}{%- endif -%}\n{%- set clear_thinking = clear_thinking if clear_thinking is defined else false -%}\n{%- if tools -%}\n{%- macro tool_to_json(tool) -%}\n {%- set ns_tool = namespace(first=true) -%}\n {{ '{' -}}\n {%- for k, v in tool.items() -%}\n {%- if k != 'defer_loading' and k != 'strict' -%}\n {%- if not ns_tool.first -%}{{- ', ' -}}{%- endif -%}\n {%- set ns_tool.first = false -%}\n \"{{ k }}\": {{ v | tojson(ensure_ascii=False) }}\n {%- endif -%}\n {%- endfor -%}\n {{- '}' -}}\n{%- endmacro -%}\n{%- macro tool_references_to_response(refs) -%}\n {{- '<tool_response><tools>\\n' -}}\n {%- for tr in refs -%}\n {%- for tool in tools -%}\n {%- if 'function' in tool -%}\n {%- set tool = tool['function'] -%}\n {%- endif -%}\n {%- if tool.name == tr.name -%}\n {{- tool_to_json(tool) + '\\n' -}}\n {%- endif -%}\n {%- endfor -%}\n {%- endfor -%}\n {{- '</tools></tool_response>' -}}\n{%- endmacro -%}\n<|system|>\n# Tools\n\nYou may call one or more functions to assist with the user query.\n\nYou are provided with function signatures within <tools></tools> XML tags:\n<tools>\n{% for tool in tools %}\n{%- if 'function' in tool -%}\n {%- set tool = tool['function'] -%}\n{%- endif -%}\n{% if tool.defer_loading is not defined or not tool.defer_loading %}\n{{ tool_to_json(tool) }}\n{% endif %}\n{% endfor %}\n</tools>\n\nFor each function call, output the function name and arguments within the following XML format:\n<tool_call>{function-name}<arg_key>{arg-key-1}</arg_key><arg_value>{arg-value-1}</arg_value><arg_key>{arg-key-2}</arg_key><arg_value>{arg-value-2}</arg_value>...</tool_call>{%- endif -%}\n{%- macro emit_image() -%}<|begin_of_image|><|image|><|end_of_image|>{%- endmacro -%}\n{%- macro emit_video() -%}<|begin_of_video|><|video|><|end_of_video|>{%- endmacro -%}\n{%- macro emit_audio() -%}<|begin_of_audio|><|end_of_audio|>{%- endmacro -%}\n{%- macro visible_text(content) -%}\n {%- if content is string -%}\n {{- content -}}\n {%- elif content is iterable and content is not mapping -%}\n {%- for item in content -%}\n {%- if item is mapping and item.type == 'text' -%}\n {{- item.text -}}\n {%- elif item is string -%}\n {{- item -}}\n {%- elif item is mapping and item.type in ['image', 'image_url'] -%}\n {{- emit_image() -}}\n {%- elif item is mapping and item.type in ['video', 'video_url'] -%}\n {{- emit_video() -}}\n {%- elif item is mapping and item.type in ['audio', 'audio_url', 'input_audio'] -%}\n {{- emit_audio() -}}\n {%- endif -%}\n {%- endfor -%}\n {%- elif content is not none -%}\n {{- content -}}\n {%- endif -%}\n{%- endmacro -%}\n{%- macro tool_response(text) -%}\n{{- '<tool_response>' + text + '</tool_response>' -}}\n{%- endmacro -%}\n{%- macro render_tool_response(m) -%}\n{%- if m.content is string -%}\n {{- tool_response(m.content) -}}\n{%- elif m.content and m.content is not mapping and m.content.0.type == \"tool_reference\" -%}\n {{- tool_references_to_response(m.content) -}}\n{%- elif is_list_of_outputs(m) -%}\n {%- for tr in m.content -%}\n {%- if tr.output is iterable and tr.output is not string and tr.output is not mapping and tr.output and tr.output.0.type == \"tool_reference\" -%}\n {{- tool_references_to_response(tr.output) -}}\n {%- else -%}\n {{- tool_response(visible_text(tr.output)) -}}\n {%- endif -%}\n {%- endfor -%}\n{%- else -%}\n {{- tool_response(visible_text(m.content)) -}}\n{%- endif -%}\n{%- endmacro -%}\n{%- macro id_of(obj) -%}\n {%- if obj.tool_call_id -%}\n {{- obj.tool_call_id -}}\n {%- elif obj.id -%}\n {{- obj.id -}}\n {%- endif -%}\n{%- endmacro -%}\n{%- macro is_list_of_outputs(m) -%}\n {%- if m.content and m.content.0.output is defined -%}1{%- endif -%}\n{%- endmacro -%}\n{%- macro has_dup_tool_result_id(lo, hi, target) -%}\n {%- set ns_cnt = namespace(n=0) -%}\n {%- for k in range(lo, hi + 1) -%}\n {%- set m = messages[k] -%}\n {%- if is_list_of_outputs(m) -%}\n {%- for entry in m.content -%}\n {%- if id_of(entry) == target -%}\n {%- set ns_cnt.n = ns_cnt.n + 1 -%}\n {%- endif -%}\n {%- endfor -%}\n {%- elif id_of(m) == target -%}\n {%- set ns_cnt.n = ns_cnt.n + 1 -%}\n {%- endif -%}\n {%- if ns_cnt.n > 1 -%}{%- break -%}{%- endif -%}\n {%- endfor -%}\n {%- if ns_cnt.n > 1 -%}1{%- endif -%}\n{%- endmacro -%}\n{%- macro tc_id_exists(tcs, target) -%}\n {%- set ns_f = namespace(found=false) -%}\n {%- for tc in tcs -%}\n {%- if id_of(tc) == target -%}\n {%- set ns_f.found = true -%}\n {%- break -%}\n {%- endif -%}\n {%- endfor -%}\n {%- if ns_f.found -%}1{%- endif -%}\n{%- endmacro -%}\n{%- set ns = namespace(last_user_index=-1) -%}\n{%- for m in messages %}\n {%- if m.role == 'user' %}\n {%- set ns.last_user_index = loop.index0 -%}\n {%- endif %}\n{%- endfor %}\n{%- for m in messages -%}\n{%- if m.role == 'user' -%}<|user|>{{ visible_text(m.content) }}\n{%- elif m.role == 'assistant' -%}\n<|assistant|>\n{%- set content = visible_text(m.content) %}\n{%- if m.reasoning_content is string %}\n {%- set reasoning_content = m.reasoning_content %}\n{%- elif '</think>' in content %}\n {%- set reasoning_content = content.split('</think>')[0].split('<think>')[-1] %}\n {%- set content = content.split('</think>')[-1] %}\n{%- endif %}\n{%- if (not clear_thinking or loop.index0 > ns.last_user_index) and reasoning_content is defined -%}\n{{ '<think>' + reasoning_content + '</think>'}}\n{%- else -%}\n{{ '<think></think>' }}\n{%- endif -%}\n{%- if content.strip() -%}\n{{ content.strip() }}\n{%- endif -%}\n{% if m.tool_calls %}\n{% for tc in m.tool_calls %}\n{%- if tc.function %}\n {%- set tc = tc.function %}\n{%- endif %}\n{{- '<tool_call>' ~ tc.name -}}\n{% set _args = tc.arguments %}{% for k, v in _args.items() %}<arg_key>{{ k }}</arg_key><arg_value>{{ v | tojson(ensure_ascii=False) if v is not string else v }}</arg_value>{% endfor %}</tool_call>{% endfor %}\n{% endif %}\n{%- elif m.role == 'tool' -%}\n{%- if loop.first or (messages[loop.index0 - 1].role != \"tool\") %}\n {{- '<|observation|>' -}}\n {%- set block_start = loop.index0 -%}\n {%- set ns_blk = namespace(end=block_start) -%}\n {%- for j in range(block_start, messages|length) -%}\n {%- if messages[j].role == 'tool' -%}\n {%- set ns_blk.end = j -%}\n {%- else -%}\n {%- break -%}\n {%- endif -%}\n {%- endfor -%}\n {%- set ns_a = namespace(tool_calls=none) -%}\n {%- if block_start > 0 and messages[block_start - 1].role == 'assistant' and messages[block_start - 1].tool_calls -%}\n {%- set ns_a.tool_calls = messages[block_start - 1].tool_calls -%}\n {%- endif -%}\n {%- set ns_chk = namespace(can_sort=true, res=[], mk=[], ek=[], tcs=[]) -%}\n {%- for k in range(block_start, ns_blk.end + 1) -%}\n {%- set m = messages[k] -%}\n {%- if is_list_of_outputs(m) -%}\n {%- for entry in m.content -%}\n {%- set ns_chk.res = ns_chk.res + [id_of(entry)] -%}\n {%- set ns_chk.mk = ns_chk.mk + [k] -%}\n {%- set ns_chk.ek = ns_chk.ek + [loop.index0] -%}\n {%- endfor -%}\n {%- else -%}\n {%- set ns_chk.res = ns_chk.res + [id_of(m)] -%}\n {%- set ns_chk.mk = ns_chk.mk + [k] -%}\n {%- set ns_chk.ek = ns_chk.ek + [-1] -%}\n {%- endif -%}\n {%- endfor -%}\n {%- if not ns_a.tool_calls -%}\n {%- set ns_chk.can_sort = false -%}\n {%- else -%}\n {%- for tc in ns_a.tool_calls -%}\n {%- set ns_chk.tcs = ns_chk.tcs + [id_of(tc)] -%}\n {%- endfor -%}\n {%- if '' in ns_chk.res or '' in ns_chk.tcs -%}\n {%- set ns_chk.can_sort = false -%}\n {%- elif ns_chk.res | unique(case_sensitive=true) | list | length != ns_chk.res | length -%}\n {%- set ns_chk.can_sort = false -%}\n {%- elif ns_chk.tcs | unique(case_sensitive=true) | list | length != ns_chk.tcs | length -%}\n {%- set ns_chk.can_sort = false -%}\n {%- else -%}\n {%- for eid in ns_chk.res -%}\n {%- if eid not in ns_chk.tcs -%}\n {%- set ns_chk.can_sort = false -%}\n {%- break -%}\n {%- endif -%}\n {%- endfor -%}\n {%- endif -%}\n {%- endif -%}\n {%- if ns_chk.can_sort -%}\n {%- set ns_ord = namespace(res=[], tcs=[], j=0, pairs=[]) -%}\n {%- for eid in ns_chk.res -%}\n {%- set ns_ord.res = ns_ord.res + [{'id': eid, 'p': loop.index0}] -%}\n {%- endfor -%}\n {%- for tc_id in ns_chk.tcs -%}\n {%- set ns_ord.tcs = ns_ord.tcs + [{'id': tc_id, 'i': loop.index0}] -%}\n {%- endfor -%}\n {%- set ns_ord.res = ns_ord.res | sort(attribute='id', case_sensitive=true) -%}\n {%- for tc in ns_ord.tcs | sort(attribute='id', case_sensitive=true) -%}\n {%- if ns_ord.j < ns_ord.res | length and ns_ord.res[ns_ord.j].id == tc.id -%}\n {%- set ns_ord.pairs = ns_ord.pairs + [{'i': tc.i, 'p': ns_ord.res[ns_ord.j].p}] -%}\n {%- set ns_ord.j = ns_ord.j + 1 -%}\n {%- endif -%}\n {%- endfor -%}\n {%- for pair in ns_ord.pairs | sort(attribute='i') -%}\n {%- set m = messages[ns_chk.mk[pair.p]] -%}\n {%- if ns_chk.ek[pair.p] >= 0 -%}\n {%- set entry = m.content[ns_chk.ek[pair.p]] -%}\n {%- if entry.output is iterable and entry.output is not string and entry.output is not mapping and entry.output and entry.output.0.type == \"tool_reference\" -%}\n {{- tool_references_to_response(entry.output) -}}\n {%- else -%}\n {{- tool_response(visible_text(entry.output)) -}}\n {%- endif -%}\n {%- else -%}\n {{- render_tool_response(m) -}}\n {%- endif -%}\n {%- endfor -%}\n {%- else -%}\n {%- for k in range(block_start, ns_blk.end + 1) -%}\n {{- render_tool_response(messages[k]) -}}\n {%- endfor -%}\n {%- endif -%}\n{% endif -%}\n{%- elif m.role == 'system' -%}\n<|system|>{{ visible_text(m.content) }}\n{%- endif -%}\n{%- endfor -%}\n{%- if add_generation_prompt -%}\n <|assistant|>{{- '<think>' -}}\n{%- endif -%}\n",
"templatePath": "chat_template.jinja",
"templateUrl": "https://huggingface.co/zai-org/GLM-5.3-Flash/blob/46a050bec13002ad29ee795c16e61cf4fa3c4a9c/chat_template.jinja",
"templateToolLines": [
35,
50
],
"templateHelperSource": null,
"templateHelperPath": null,
"templateHelperUrl": null,
"bosToken": "",
"eosToken": "<|endoftext|>",
"padToken": "<|endoftext|>",
"unkToken": "",
"specialTokens": {
"<|endoftext|>": 154820,
"[MASK]": 154821,
"[gMASK]": 154822,
"[sMASK]": 154823,
"<sop>": 154824,
"<eop>": 154825,
"<|system|>": 154826,
"<|user|>": 154827,
"<|assistant|>": 154828,
"<|observation|>": 154829,
"<|begin_of_image|>": 154830,
"<|end_of_image|>": 154831,
"<|begin_of_video|>": 154832,
"<|end_of_video|>": 154833,
"<|begin_of_audio|>": 154834,
"<|end_of_audio|>": 154835,
"<|begin_of_transcription|>": 154836,
"<|end_of_transcription|>": 154837,
"<|code_prefix|>": 154838,
"<|code_middle|>": 154839,
"<|code_suffix|>": 154840,
"<think>": 154841,
"</think>": 154842,
"<tool_call>": 154843,
"</tool_call>": 154844,
"<tool_response>": 154845,
"</tool_response>": 154846,
"<arg_key>": 154847,
"</arg_key>": 154848,
"<arg_value>": 154849,
"</arg_value>": 154850,
"/nothink": 154851,
"<|begin_of_box|>": 154852,
"<|end_of_box|>": 154853,
"<|image|>": 154854,
"<|video|>": 154855
},
"stopTokenCall": "<|observation|>",
"stopTokenText": "<|user|>",
"dedicatedStopToken": false,
"stopKind": "role-boundary",
"eosNote": "GLM-5.3-Flash's generation_config lists three EOS IDs: <|endoftext|> (154820), <|user|> (154827), and <|observation|> (154829). <|observation|> and <|user|> are next-role boundary tokens in eos_token_id rather than a dedicated call-only token like Harmony <|call|>.",
"cap": "GLM-5.3-Flash serializes each tool as compact JSON via <code>tojson</code> inside <code><tools>...</tools></code> under <code><|system|></code>. All JSON Schema keywords survive intact, and the system prompt prescribes exact <code><arg_key></code>/<code><arg_value></code> syntax.",
"outCap": "GLM-5.3-Flash writes the function name directly after <code><tool_call></code>, pairs each argument in <code><arg_key></code>/<code><arg_value></code> tags, and hands off at the <code><|observation|></code> role boundary.",
"walkSteps": {
"s2": "The Jinja template serializes each tool dict via tojson inside <tools>...</tools> under [gMASK]<sop><|system|>, preserving nested schemas, enums, defaults, and bounds.",
"s3": "Surrounding system prose explains the <tool_call>{name}<arg_key>{k}</arg_key><arg_value>{v}</arg_value></tool_call> format.",
"s4": "The rendered prompt ends with <|assistant|><think>, starting directly inside the assistant reasoning block.",
"s5": "After </think>, the model emits special tokens <tool_call>, <arg_key>/<arg_value> pairs, and </tool_call>.",
"s6": "vLLM's Glm47Moe parser and SGLang's Glm47MoeDetector (keeping special tokens) match those XML tag tokens and coerce argument values to schema types.",
"s7": "Generation stops at the <|observation|> (154829) role boundary (one of three EOS IDs alongside <|user|> and <|endoftext|>); parsed calls rewrite engine 'stop' to API finish_reason='tool_calls'."
},
"lane": [
"Reasoning text closes with </think>",
"<tool_call> opens tool-call block",
"Bare function name follows <tool_call>",
"<arg_key>…</arg_key><arg_value>…</arg_value> pairs",
"</tool_call> closes tool-call block",
"<|observation|> role boundary ends turn; sampler reports stop"
],
"laneText": [
"Reasoning text closes with </think>",
"Plain assistant answer text",
"<|user|> role boundary ends turn; sampler reports stop"
],
"excerpts": {
"vllm": [
{
"repo": "vllm",
"path": "vllm/parser/glm47_moe.py",
"start": 39,
"end": 63,
"hl": [
41,
42,
43,
44,
45,
46
],
"sha": "ef687f6179b752c028767e610addbda67ed36d03",
"url": "https://github.com/vllm-project/vllm/blob/ef687f6179b752c028767e610addbda67ed36d03/vllm/parser/glm47_moe.py#L39-L63",
"note": "vLLM's GLM-4.7/5 MoE parser defines <tool_call>, <arg_key>, and <arg_value> terminals.",
"code": "THINK_START = \"<think>\"\nTHINK_END = \"</think>\"\nTOOL_CALL_START = \"<tool_call>\"\nTOOL_CALL_END = \"</tool_call>\"\nARG_KEY_START = \"<arg_key>\"\nARG_KEY_END = \"</arg_key>\"\nARG_VALUE_START = \"<arg_value>\"\nARG_VALUE_END = \"</arg_value>\"\n\n# Special tokens that delimit conversation turns in a rendered GLM prompt.\n# Reasoning markers belonging to earlier turns must not be mistaken for the\n# state of the turn currently being generated.\nGLM_TURN_BOUNDARIES = frozenset(\n (\"<|system|>\", \"<|user|>\", \"<|assistant|>\", \"<|observation|>\")\n)\n\n_ARG_RE = re.compile(\n r\"<arg_key>(?P<key>.*?)</arg_key>\\s*\"\n r\"<arg_value>(?P<value>.*?)</arg_value>\",\n re.DOTALL,\n)\n_PARTIAL_ARG_RE = re.compile(\n r\"<arg_key>(?P<key>.*?)</arg_key>\\s*\"\n r\"<arg_value>(?P<value>.*)$\",\n re.DOTALL,"
}
],
"sglang": [
{
"repo": "sglang",
"path": "python/sglang/srt/function_call/glm47_moe_detector.py",
"start": 39,
"end": 58,
"hl": [
42,
43,
44,
45,
46
],
"sha": "1918da6349f9be1c62315503e1a7458a3957bc5f",
"url": "https://github.com/sgl-project/sglang/blob/1918da6349f9be1c62315503e1a7458a3957bc5f/python/sglang/srt/function_call/glm47_moe_detector.py#L39-L58",
"note": "SGLang's Glm47MoeDetector defines a 5-state FSM enum for streaming <arg_key>/<arg_value> pairs.",
"code": "class StreamState(str, Enum):\n \"\"\"State machine states for XML to JSON streaming conversion.\"\"\"\n\n INIT = \"INIT\"\n BETWEEN = \"BETWEEN\"\n IN_KEY = \"IN_KEY\"\n WAITING_VALUE = \"WAITING_VALUE\"\n IN_VALUE = \"IN_VALUE\"\n\n\n_UNSET = object()\n\n\ndef _json_type(value: Any) -> str:\n if isinstance(value, float) and value.is_integer():\n return \"integer\"\n return {\n type(None): \"null\",\n bool: \"boolean\",\n int: \"integer\","
}
]
}
},
{
"key": "hy4",
"id": "tencent/Hy4-flash",
"label": "Hy4-flash",
"sub": "Namespaced XML",
"sha": "b2498eba6a1a3f9bbcab4190bc1313a3c7010c2f",
"created": "2026-11-17",
"likes": 618,
"templateKind": "jinja",
"schemaEncoding": "JSON in <tools> (custom macro)",
"callSyntax": "<tool_calls:opensource>",
"servingNote": "Hy4-flash namespaces its chat and tool structural tokens with :opensource; vLLM's hy_v4_tool_parser and SGLang's HunyuanDetector detect the suffix from the tokenizer vocabulary.",
"chatTemplate": "{#- ----------‑‑‑ special token variables ‑‑‑---------- -#}\n{%- set HYTK = ':opensource' %}\n{%- set hy_start_token = '<|hy_start{}|>'.format(HYTK) %}\n{%- set hy_middle_token = '<|hy_middle{}|>'.format(HYTK) %}\n{%- set hy_end_token = '<|hy_end{}|>'.format(HYTK) %}\n{%- set image_start_token = '<|hy_image▁start{}|>'.format(HYTK) %}\n{%- set image_pad_token = '<|hy_image▁pad{}|>'.format(HYTK) %}\n{%- set image_end_token = '<|hy_image▁end{}|>'.format(HYTK) %}\n{%- set video_start_token = '<|hy_video▁start{}|>'.format(HYTK) %}\n{%- set video_pad_token = '<|hy_video▁pad{}|>'.format(HYTK) %}\n{%- set video_end_token = '<|hy_video▁end{}|>'.format(HYTK) %}\n{%- set think_begin_token = '<think{}>'.format(HYTK) %}\n{%- set think_end_token = '</think{}>'.format(HYTK) %}\n{%- set toolcalls_begin_token = '<tool_calls{}>'.format(HYTK) %}\n{%- set toolcalls_end_token = '</tool_calls{}>'.format(HYTK) %}\n{%- set toolcall_begin_token = '<tool_call{}>'.format(HYTK) %}\n{%- set toolcall_end_token = '</tool_call{}>'.format(HYTK) %}\n{%- set argkey_begin_token = '<arg_key{}>'.format(HYTK) %}\n{%- set argkey_end_token = '</arg_key{}>'.format(HYTK) %}\n{%- set argvalue_begin_token = '<arg_value{}>'.format(HYTK) %}\n{%- set argvalue_end_token = '</arg_value{}>'.format(HYTK) %}\n{%- set toolresponse_begin_token = '<tool_response{}>'.format(HYTK) %}\n{%- set toolresponse_end_token = '</tool_response{}>'.format(HYTK) %}\n{%- set reasoning_mode_token = '<|reasoning_mode{}|>'.format(HYTK) %}\n\n{#- ----------‑‑‑ hyperparameters variables ‑‑‑---------- -#}\n{%- if not add_generation_prompt is defined %}\n {%- set add_generation_prompt = false %}\n{%- endif %}\n{%- if not preserved_thinking is defined %}\n {%- if not tools %}\n {%- set preserved_thinking = false %}\n {%- else %}\n {%- set preserved_thinking = true %}\n {%- endif %}\n{%- endif %}\n\n{%- if not reasoning_effort is defined %}\n {%- set reasoning_effort = 'high' %}\n{%- elif reasoning_effort not in ['no_think', 'high'] %}\n {%- if reasoning_effort is none %}\n {{- raise_exception('reasoning_effort error : None, should be no_think/high') }}\n {%- else %}\n {{- raise_exception('reasoning_effort error : ' + reasoning_effort + ', should be no_think/high') }}\n {%- endif %}\n{%- endif %}\n\n{%- if fallback_strategy is defined and fallback_strategy == 'reasoning_toolcall_retry' %}\n {%- set reasoning_effort = 'high' %}\n {%- set add_generation_prompt = false %}\n{%- endif %}\n{%- if not raw_last_assistant is defined %}\n {%- set raw_last_assistant = false %}\n{%- endif %}\n{%- if not add_vision_id is defined %}\n {%- set add_vision_id = false %}\n{%- endif %}\n{%- set image_count = namespace(value=0) %}\n{%- set video_count = namespace(value=0) %}\n\n{%- macro tool_to_json(tool) -%}\n {%- set ns_tool = namespace(first=true) -%}\n {{- '{' -}}\n {%- for k, v in tool.items() -%}\n {%- if k != 'defer_loading' and k != 'strict' -%}\n {%- if not ns_tool.first -%}{{- ', ' -}}{%- endif -%}\n {%- set ns_tool.first = false -%}\n {{- '\"' ~ k ~ '\": ' ~ (v | tojson(ensure_ascii=False)) -}}\n {%- endif -%}\n {%- endfor -%}\n {{- '}' -}}\n{%- endmacro -%}\n\n{%- macro render_content(content, do_vision_count=true, is_system_content=false) -%}\n {%- if content is string -%}\n {{- content -}}\n {%- elif content is iterable and content is not mapping -%}\n {%- for item in content -%}\n {%- if item is mapping and item.type == 'text' -%}\n {{- item.text -}}\n {%- elif item is mapping and ('image' in item or 'image_url' in item or item.type in ['image', 'image_url']) -%}\n {%- if is_system_content -%}\n {{- raise_exception('System message cannot contain images.') -}}\n {%- endif -%}\n {%- if do_vision_count -%}\n {%- set image_count.value = image_count.value + 1 -%}\n {%- endif -%}\n {%- if add_vision_id -%}\n {{- 'Picture ' ~ image_count.value ~ ': ' -}}\n {%- endif -%}\n {{- image_start_token ~ image_pad_token ~ image_end_token -}}\n {%- elif item is mapping and ('video' in item or 'video_url' in item or item.type in ['video', 'video_url']) -%}\n {%- if is_system_content -%}\n {{- raise_exception('System message cannot contain videos.') -}}\n {%- endif -%}\n {%- if do_vision_count -%}\n {%- set video_count.value = video_count.value + 1 -%}\n {%- endif -%}\n {%- if add_vision_id -%}\n {{- 'Video ' ~ video_count.value ~ ': ' -}}\n {%- endif -%}\n {{- video_start_token ~ video_pad_token ~ video_end_token -}}\n {%- elif item is string -%}\n {{- item -}}\n {%- else -%}\n {{- item | string -}}\n {%- endif -%}\n {%- endfor -%}\n {%- elif content is none -%}\n {{- '' -}}\n {%- else -%}\n {{- content | string -}}\n {%- endif -%}\n{%- endmacro -%}\n\n{%- macro render_tools_prompt() -%}\n {{- '# Tools\\n\\nYou may call one or more functions to assist with the user query.' -}}\n {{- '\\n\\nYou are provided with function signatures within <tools></tools> XML tags:' -}}\n {{- '\\n<tools>\\n' -}}\n {%- set tool_ns = namespace(first=true) -%}\n {%- for tool in tools -%}\n {%- set t = tool['function'] if tool is mapping and 'function' in tool else tool -%}\n {%- if t.defer_loading is not defined or not t.defer_loading -%}\n {%- if not tool_ns.first -%}{{- '\\n' -}}{%- endif -%}\n {%- set tool_ns.first = false -%}\n {{- tool_to_json(t) -}}\n {%- endif -%}\n {%- endfor -%}\n {{- '\\n</tools>\\n\\n' -}}\n {{- 'For function call returns, you should first print ' ~ toolcalls_begin_token -}}\n {{- '\\nFor each function call, you should return object like:\\n' -}}\n {{- toolcall_begin_token ~ '{function-name}' -}}\n {{- argkey_begin_token ~ '{arg-key-1}' ~ argkey_end_token -}}\n {{- argvalue_begin_token ~ '{arg-value-1}' ~ argvalue_end_token -}}\n {{- argkey_begin_token ~ '{arg-key-2}' ~ argkey_end_token -}}\n {{- argvalue_begin_token ~ '{arg-value-2}' ~ argvalue_end_token -}}\n {{- '...' -}}\n {{- toolcall_end_token -}}\n {{- '\\nAt the end of function call returns, you should print ' ~ toolcalls_end_token -}}\n{%- endmacro -%}\n\n{#- adjacent tool_search_output parts share one <tools> block, so a tool search result has the same shape as the tools prompt -#}\n{%- macro render_tool_response(message) -%}\n {%- set content = message['content'] -%}\n {{- toolresponse_begin_token -}}\n {%- if content is string -%}\n {{- content -}}\n {%- elif content is iterable and content is not mapping -%}\n {%- set tools_ns = namespace(open=false) -%}\n {%- for item in content -%}\n {%- set is_search_output = item is mapping and item.type is defined and item.type == 'tool_search_output' -%}\n {%- if is_search_output and not tools_ns.open -%}\n {{- '<tools>\\n' -}}\n {%- set tools_ns.open = true -%}\n {%- elif not is_search_output and tools_ns.open -%}\n {{- '</tools>' -}}\n {%- set tools_ns.open = false -%}\n {%- endif -%}\n {%- if is_search_output -%}\n {%- if item.tools is defined and item.tools is iterable -%}\n {%- for tool in item.tools -%}\n {%- set t = tool['function'] if tool is mapping and 'function' in tool else tool -%}\n {{- tool_to_json(t) ~ '\\n' -}}\n {%- endfor -%}\n {%- endif -%}\n {%- elif item is mapping and item.output is defined -%}\n {{- render_content(item.output) -}}\n {%- else -%}\n {{- render_content([item]) -}}\n {%- endif -%}\n {%- endfor -%}\n {%- if tools_ns.open -%}\n {{- '</tools>' -}}\n {%- endif -%}\n {%- else -%}\n {{- render_content(content) -}}\n {%- endif -%}\n {{- toolresponse_end_token -}}\n{%- endmacro -%}\n\n{#- consecutive tool messages are clustered into a single tool message whose content is the list of the original tool messages; the result is written to merged_ns.messages (a macro cannot return a list) -#}\n{%- set merged_ns = namespace(messages=[]) %}\n{%- macro merge_tool_responses(messages) -%}\n {%- set merge_ns = namespace(result=[], cluster=[]) -%}\n {%- for message in messages -%}\n {%- if message['role'] == 'tool' -%}\n {%- set merge_ns.cluster = merge_ns.cluster + [message] -%}\n {%- else -%}\n {%- if merge_ns.cluster -%}\n {%- set merge_ns.result = merge_ns.result + [{'role': 'tool', 'content': merge_ns.cluster}] -%}\n {%- set merge_ns.cluster = [] -%}\n {%- endif -%}\n {%- set merge_ns.result = merge_ns.result + [message] -%}\n {%- endif -%}\n {%- endfor -%}\n {%- if merge_ns.cluster -%}\n {%- set merge_ns.result = merge_ns.result + [{'role': 'tool', 'content': merge_ns.cluster}] -%}\n {%- endif -%}\n {%- set merged_ns.messages = merge_ns.result -%}\n{%- endmacro -%}\n\n{#- render one tool cluster, reordered to follow the tool_call order of the preceding assistant turn; any missing / ambiguous id falls back to the original tool message order for the whole cluster -#}\n{%- macro render_tool_responses(tool_messages, tool_call_ids) -%}\n {%- set order_ns = namespace(ordered=[], matched=true) -%}\n {%- if tool_call_ids and tool_call_ids | length == tool_messages | length -%}\n {%- for tool_call_id in tool_call_ids -%}\n {%- set hit_ns = namespace(count=0, message=none) -%}\n {%- for tool_message in tool_messages -%}\n {%- set message_id = tool_message['tool_call_id'] if tool_message['tool_call_id'] is defined else tool_message['id'] -%}\n {%- if message_id is defined and message_id == tool_call_id -%}\n {%- set hit_ns.count = hit_ns.count + 1 -%}\n {%- set hit_ns.message = tool_message -%}\n {%- endif -%}\n {%- endfor -%}\n {%- if hit_ns.count == 1 -%}\n {%- set order_ns.ordered = order_ns.ordered + [hit_ns.message] -%}\n {%- else -%}\n {%- set order_ns.matched = false -%}\n {%- endif -%}\n {%- endfor -%}\n {%- else -%}\n {%- set order_ns.matched = false -%}\n {%- endif -%}\n {%- for tool_message in (order_ns.ordered if order_ns.matched else tool_messages) -%}\n {{- render_tool_response(tool_message) -}}\n {%- endfor -%}\n{%- endmacro -%}\n\n{%- set _ = merge_tool_responses(messages) %}\n{%- set normed_messages = merged_ns.messages %}\n\n{%- set ns = namespace(last_user_index=-1, has_leading_system=false) %}\n{%- if normed_messages and normed_messages[0].role == 'system' %}\n {%- set ns.has_leading_system = true %}\n{%- endif %}\n{%- for message in normed_messages %}\n {%- if message['role'] == 'user' %}\n {%- set ns.last_user_index = loop.index0 %}\n {%- endif %}\n{%- endfor %}\n\n{#- no leading system: synthesize one for tools and/or reasoning_mode -#}\n{%- if not ns.has_leading_system %}\n {{- hy_start_token ~ 'system' ~ hy_middle_token -}}\n {%- if tools %}\n {{- render_tools_prompt() -}}\n {%- endif %}\n {{- reasoning_mode_token ~ 'reasoning_effort:' ~ reasoning_effort -}}\n {{- hy_end_token -}}\n{%- endif %}\n\n{%- set last_ns = namespace(last_is_assistant=false) %}\n{%- set prev_ns = namespace(tool_call_ids=[]) %}\n{%- for message in normed_messages %}\n {%- if message['role'] == 'system' %}\n {{- hy_start_token ~ 'system' ~ hy_middle_token -}}\n {#- tools / reasoning_mode only attach to the leading system (messages[0]) -#}\n {%- if loop.first %}\n {%- if tools %}\n {{- render_tools_prompt() -}}\n {%- endif %}\n {%- set content = render_content(message['content']) -%}\n {%- if tools and content -%}\n {{- '\\n\\n' -}}\n {%- endif -%}\n {{- content -}}\n {{- reasoning_mode_token ~ 'reasoning_effort:' ~ reasoning_effort -}}\n {%- else %}\n {{- render_content(message['content']) -}}\n {%- endif %}\n {{- hy_end_token -}}\n {%- elif message['role'] == 'user' %}\n {{- hy_start_token ~ 'user' ~ hy_middle_token -}}\n {{- render_content(message['content']) -}}\n {{- hy_end_token -}}\n {%- elif message['role'] == 'assistant' %}\n {%- set content_body = render_content(message['content']) -%}\n {#- 'reasoning' takes precedence, fall back to 'reasoning_content' when it is empty -#}\n {%- set reasoning_text = '' %}\n {%- if message['reasoning'] is defined and message['reasoning'] is string and message['reasoning'] %}\n {%- set reasoning_text = message['reasoning'] %}\n {%- elif message['reasoning_content'] is defined and message['reasoning_content'] is string and message['reasoning_content'] %}\n {%- set reasoning_text = message['reasoning_content'] %}\n {%- endif %}\n {#- no_think overrides preserved_thinking: history is always emitted with empty think tags -#}\n {%- if reasoning_effort != 'no_think' and (preserved_thinking or loop.index0 > ns.last_user_index) and reasoning_text %}\n {%- set content = think_begin_token ~ reasoning_text ~ think_end_token ~ content_body %}\n {%- else %}\n {%- set content = think_begin_token ~ think_end_token ~ content_body %}\n {%- endif %}\n {{- hy_start_token ~ 'assistant' ~ hy_middle_token -}}\n {%- if message['tool_calls'] is defined and message['tool_calls'] %}\n {#- remember the tool_call ids of this turn to order the following tool responses; an incomplete id set means \"do not reorder\" -#}\n {%- set ids_ns = namespace(ids=[], complete=true) %}\n {%- for tool in message['tool_calls'] %}\n {%- set tool_call_id = tool['id'] if tool['id'] is defined and tool['id'] else tool['tool_call_id'] %}\n {%- if tool_call_id is defined and tool_call_id %}\n {%- set ids_ns.ids = ids_ns.ids + [tool_call_id] %}\n {%- else %}\n {%- set ids_ns.complete = false %}\n {%- endif %}\n {%- endfor %}\n {%- set prev_ns.tool_call_ids = ids_ns.ids if ids_ns.complete else [] %}\n {{- content -}}\n {{- toolcalls_begin_token -}}\n {%- for tool in message['tool_calls'] -%}\n {%- set func = tool['function'] if tool is mapping and 'function' in tool else tool -%}\n {%- set arguments = func['arguments'] -%}\n {{- toolcall_begin_token ~ func['name'] -}}\n {%- for key, value in arguments.items() -%}\n {{- argkey_begin_token ~ key ~ argkey_end_token -}}\n {%- if value is not string -%}\n {%- set value = value | tojson(ensure_ascii=False) -%}\n {%- endif -%}\n {{- argvalue_begin_token ~ value ~ argvalue_end_token -}}\n {%- endfor -%}\n {{- toolcall_end_token -}}\n {%- endfor -%}\n {{- toolcalls_end_token -}}\n {%- else %}\n {%- if loop.last and raw_last_assistant %}\n {{- content_body -}}\n {%- else %}\n {{- content -}}\n {%- endif %}\n {%- endif %}\n {#- continuation / prefill: last assistant is still open, do not close with hy_end -#}\n {%- if not (loop.last and raw_last_assistant) and not (loop.last and fallback_strategy is defined and fallback_strategy == 'reasoning_toolcall_retry') %}\n {{- hy_end_token -}}\n {%- endif %}\n {%- elif message['role'] == 'tool' %}\n {{- hy_start_token ~ 'tool' ~ hy_middle_token -}}\n {{- render_tool_responses(message['content'], prev_ns.tool_call_ids) -}}\n {{- hy_end_token -}}\n {%- else %}\n {{- hy_start_token ~ message['role'] ~ hy_middle_token -}}\n {{- render_content(message['content']) -}}\n {{- hy_end_token -}}\n {%- endif %}\n {%- if message['role'] != 'assistant' or not (message['tool_calls'] is defined and message['tool_calls']) %}\n {%- set prev_ns.tool_call_ids = [] %}\n {%- endif %}\n {%- if loop.last and message['role'] == 'assistant' %}\n {%- set last_ns.last_is_assistant = true %}\n {%- endif %}\n{%- endfor %}\n{%- if add_generation_prompt %}\n {%- if not last_ns.last_is_assistant %}\n {%- if reasoning_effort == 'no_think' %}\n {{- hy_start_token ~ 'assistant' ~ hy_middle_token ~ think_begin_token ~ think_end_token -}}\n {%- else %}\n {{- hy_start_token ~ 'assistant' ~ hy_middle_token ~ think_begin_token -}}\n {%- endif %}\n {%- endif %}\n{%- endif %}\n",
"templatePath": "chat_template.jinja",
"templateUrl": "https://huggingface.co/tencent/Hy4-flash/blob/b2498eba6a1a3f9bbcab4190bc1313a3c7010c2f/chat_template.jinja",
"templateToolLines": [
117,
134
],
"templateHelperSource": null,
"templateHelperPath": null,
"templateHelperUrl": null,
"bosToken": "<|hy_start:opensource|>",
"eosToken": "<|hy_end:opensource|>",
"padToken": "<|hy_pad:opensource|>",
"unkToken": "",
"specialTokens": {
"<|hy_start:opensource|>": 120000,
"<|hy_middle:opensource|>": 120001,
"<|hy_pad:opensource|>": 120002,
"<|hy_fim▁hole|>": 120003,
"<|hy_fim▁begin|>": 120004,
"<|hy_fim▁end|>": 120005,
"<|hy_EOT|>": 120008,
"<|hy_end:opensource|>": 120025,
"<think:opensource>": 120029,
"</think:opensource>": 120030,
"<tool_call:opensource>": 120033,
"</tool_call:opensource>": 120034,
"<tool_calls:opensource>": 120035,
"</tool_calls:opensource>": 120036,
"<tool_response:opensource>": 120037,
"</tool_response:opensource>": 120038,
"<|reasoning_mode:opensource|>": 120039,
"<arg_key:opensource>": 120040,
"</arg_key:opensource>": 120041,
"<arg_value:opensource>": 120042,
"</arg_value:opensource>": 120043,
"<|hy_image▁start:opensource|>": 120118,
"<|hy_image▁end:opensource|>": 120119,
"<|hy_image▁pad:opensource|>": 120120,
"<|hy_image▁newline:opensource|>": 120121,
"<|hy_video▁start:opensource|>": 120122,
"<|hy_video▁end:opensource|>": 120123,
"<|hy_video▁pad:opensource|>": 120124
},
"stopTokenCall": "<|hy_end:opensource|>",
"stopTokenText": "<|hy_end:opensource|>",
"dedicatedStopToken": false,
"stopKind": "shared",
"eosNote": "Hy4-flash's generation_config sets EOS to <|hy_end:opensource|> (id 120025), shared across tool calls and plain replies; <tool_calls:opensource> signals tool invocation.",
"cap": "Hy4-flash uses a custom Jinja macro (<code>tool_to_json</code>) to serialize each function as JSON inside <code><tools></code> under <code><|hy_start:opensource|>system</code>, excluding internal keys like <code>defer_loading</code> and <code>strict</code>. Structural chat and tool tags carry a <code>:opensource</code> suffix.",
"outCap": "Hy4-flash wraps calls in <code><tool_calls:opensource></code>, pairs arguments with <code><arg_key:opensource></code> / <code><arg_value:opensource></code> special tokens, and stops on shared <code><|hy_end:opensource|></code> (120025).",
"walkSteps": {
"s2": "chat_template.jinja serializes each tool into <tools> via its custom tool_to_json macro, preserving nested properties, enums, and numeric bounds.",
"s3": "The system prompt wraps <tools> with calling instructions specifying the :opensource-suffixed tool and argument tags.",
"s4": "The rendered prompt ends with <|hy_start:opensource|>assistant<|hy_middle:opensource|><think:opensource>, opening the namespaced reasoning block.",
"s5": "After </think:opensource>, the model emits <tool_calls:opensource><tool_call:opensource>name with <arg_key:opensource>/<arg_value:opensource> pairs.",
"s6": "vLLM's hy_v4_tool_parser and SGLang's HunyuanDetector discover the :opensource suffix from the tokenizer vocab (skip_special_tokens=False) and parse the key/value pairs.",
"s7": "Generation stops on shared <|hy_end:opensource|> (120025); on an ordinary completed auto-tool turn with parsed calls, the serving layer rewrites engine 'stop' to API finish_reason='tool_calls'."
},
"lane": [
"Reasoning text closes with </think:opensource>",
"<tool_calls:opensource><tool_call:opensource> opens call",
"Bare function name follows <tool_call:opensource>",
"<arg_key:opensource> / <arg_value:opensource> pairs",
"</tool_call:opensource></tool_calls:opensource> closes call",
"<|hy_end:opensource|> ends turn; sampler reports stop"
],
"laneText": [
"Reasoning text closes with </think:opensource>",
"Plain assistant answer text",
"<|hy_end:opensource|> ends turn; sampler reports stop"
],
"excerpts": {
"vllm": [
{
"repo": "vllm",
"path": "vllm/tool_parsers/hy_v4_tool_parser.py",
"start": 121,
"end": 145,
"hl": [
122,
123,
125,
126,
128
],
"sha": "ef687f6179b752c028767e610addbda67ed36d03",
"url": "https://github.com/vllm-project/vllm/blob/ef687f6179b752c028767e610addbda67ed36d03/vllm/tool_parsers/hy_v4_tool_parser.py#L121-L145",
"note": "vLLM's HyV4 parser scans tokenizer vocab to discover the :opensource suffix on structural tags.",
"code": "\n structural_token_re = re.compile(\n r\"<(?:think|tool_calls|tool_call|arg_key|arg_value)(:[^\\s>]+)?>\"\n )\n for token in tokenizer.get_vocab():\n match = structural_token_re.fullmatch(token)\n if match:\n return match.group(1) or \"\"\n\n return \"\"\n\n\n# =============================================================================\n# Argument-value parsing utilities (stateless, pure functions)\n#\n# These map the model's raw ``<arg_value>`` text to typed Python values using\n# the tool's JSON Schema. They do not touch any parser state, so they live at\n# module level instead of tangling up HYV4ToolExtractor.\n# =============================================================================\n\n_TYPE_ALIASES: dict[str, str] = {\n \"str\": \"string\",\n \"text\": \"string\",\n \"varchar\": \"string\",\n \"char\": \"string\","
}
],
"sglang": [
{
"repo": "sglang",
"path": "python/sglang/srt/function_call/hunyuan_detector.py",
"start": 21,
"end": 44,
"hl": [
23,
24,
25,
32,
33
],
"sha": "1918da6349f9be1c62315503e1a7458a3957bc5f",
"url": "https://github.com/sgl-project/sglang/blob/1918da6349f9be1c62315503e1a7458a3957bc5f/python/sglang/srt/function_call/hunyuan_detector.py#L21-L44",
"note": "SGLang's HunyuanDetector defines _HUNYUAN_TOKEN_RE to match suffixed tags like <tool_calls:opensource>.",
"code": "# a shared suffix to each (e.g. ``<tool_calls:opensource>``); resolve the real\n# token string from the vocab at runtime and fall back to these literals.\n_HUNYUAN_TOKEN_NAMES = (\n \"tool_calls\",\n \"tool_call\",\n \"tool_sep\",\n \"arg_key\",\n \"arg_value\",\n \"think\",\n)\n\n_HUNYUAN_TOKEN_RE = re.compile(\n r\"^<(?P<name>\" + \"|\".join(_HUNYUAN_TOKEN_NAMES) + r\")(?::[^>]+)?>$\"\n)\n\n\ndef resolve_hunyuan_tokens(tokenizer) -> Dict[str, str]:\n \"\"\"Map bare token names to their real (possibly suffixed) strings in vocab.\n\n Returns ``{name: token_str}`` for each name found. A bare literal is used\n when the tokenizer carries no suffixed form, so the same detector serves\n both the preview (suffix-less) and shipping (suffixed) Hy3 tokenizers.\n \"\"\"\n tokens: Dict[str, str] = {}"
}
]
}
},
{
"key": "deepseek41",
"id": "deepseek-ai/DeepSeek-V4.1-Flash-1017",
"label": "DeepSeek-V4.1-Flash",
"sub": "Spaced DSML",
"sha": "08c8657f02291e11b6f6b63e0e16014f8e748518",
"created": "2026-10-17",
"likes": 5863,
"templateKind": "jinja",
"schemaEncoding": "JSON lines in ## Tools",
"callSyntax": "<|DSML| calls>",
"servingNote": "DeepSeek-V4.1 changed V4's tag names to include a leading space (<|DSML| calls>, <|DSML| invoke>, <|DSML| parameter>); both vLLM (deepseek_v41) and SGLang (DeepSeekV41Detector) ship dedicated subclasses.",
"chatTemplate": "{#- DeepSeek-V4.1 chat template, ported from encoding/encoding.py in the model repo.\n Extra kwargs: thinking_mode (\"thinking\" | \"chat\", default \"thinking\"; thinking=true/false and enable_thinking=true/false\n are accepted as aliases), drop_thinking (default true), reasoning_effort (int in [1, 100] or \"low\"/\"high\"/\"max\",\n default \"high\"; the OpenAI values \"none\"/\"minimal\"/\"medium\"/\"xhigh\" map like DeepSeek's Chat Completions adapter, and\n \"none\" turns thinking off unless it is set explicitly). Assistant reasoning is read from reasoning_content, or from\n thinking as an alias. Tool call arguments must be dicts. -#}\n{%- set IMG = \"<|deepseek_image|>\" -%}\n{%- set DSML = \"|DSML|\" -%}\n\n{%- if thinking_mode is not defined -%}\n {%- if thinking is defined and thinking is not none -%}\n {%- set thinking_mode = \"thinking\" if thinking else \"chat\" -%}\n {%- elif enable_thinking is defined and enable_thinking is not none -%}\n {%- set thinking_mode = \"thinking\" if enable_thinking else \"chat\" -%}\n {%- else -%}\n {%- set thinking_mode = \"chat\" if (reasoning_effort is defined and reasoning_effort == \"none\") else \"thinking\" -%}\n {%- endif -%}\n{%- endif -%}\n{%- if thinking_mode not in [\"chat\", \"thinking\"] -%}\n {{- raise_exception(\"Invalid thinking_mode `\" ~ thinking_mode ~ \"`, should be \\\"chat\\\" or \\\"thinking\\\"\") -}}\n{%- endif -%}\n{%- if drop_thinking is not defined -%}{%- set drop_thinking = true -%}{%- endif -%}\n{%- if add_generation_prompt is not defined -%}{%- set add_generation_prompt = false -%}{%- endif -%}\n{%- if tools is not defined -%}{%- set tools = none -%}{%- endif -%}\n\n{%- if reasoning_effort is not defined or reasoning_effort is none -%}{%- set reasoning_effort = \"high\" -%}{%- endif -%}\n{%- set effort_map = {\"none\": 75, \"minimal\": 50, \"low\": 50, \"medium\": 75, \"high\": 75, \"xhigh\": 75, \"max\": 100} -%}\n{%- if reasoning_effort is string and reasoning_effort in effort_map -%}\n {%- set budget = effort_map[reasoning_effort] -%}\n{%- elif reasoning_effort is integer and 1 <= reasoning_effort <= 100 -%}\n {%- set budget = reasoning_effort -%}\n{%- else -%}\n {{- raise_exception(\"Invalid reasoning effort: \" ~ reasoning_effort ~ \", should be int within [1,100] or one of \\\"low\\\", \\\"high\\\", \\\"max\\\"\") -}}\n{%- endif -%}\n\n{#- Text of text/image blocks joined by blank lines; other block types are dropped. -#}\n{%- macro joined_text(blocks) -%}\n {%- set jt = namespace(parts=[]) -%}\n {%- for b in blocks -%}\n {%- if b.type == \"text\" -%}\n {%- if IMG in (b.text or \"\") -%}{{- raise_exception(\"Text block contains image placeholder \" ~ IMG ~ \". Images should be separate content blocks.\") -}}{%- endif -%}\n {%- set jt.parts = jt.parts + [b.text or \"\"] -%}\n {%- elif b.type in [\"image\", \"image_url\"] -%}\n {%- set jt.parts = jt.parts + [IMG] -%}\n {%- endif -%}\n {%- endfor -%}\n {{- jt.parts | join(\"\\n\\n\") -}}\n{%- endmacro -%}\n\n{#- Splits/validates \"ns::name\" against an explicit namespace and returns the qualified name. -#}\n{%- macro qualified_name(name, ns) -%}\n {%- if ns is mapping -%}{%- set ns = ns.name -%}{%- endif -%}\n {%- set parts = name.split(\"::\", 1) -%}\n {%- if parts | length == 2 -%}\n {%- if ns is not none and ns != parts[0] -%}{{- raise_exception(\"Conflicting tool namespaces: \" ~ ns ~ \" != \" ~ parts[0]) -}}{%- endif -%}\n {%- set ns = parts[0] -%}\n {%- set name = parts[1] -%}\n {%- endif -%}\n {%- if \"::\" in name -%}{{- raise_exception(\"Tool name must not contain '::': \" ~ name) -}}{%- endif -%}\n {%- if ns is not none and \"::\" in ns -%}{{- raise_exception(\"Tool namespace must not contain '::': \" ~ ns) -}}{%- endif -%}\n {{- name if ns is none else ns ~ \"::\" ~ name -}}\n{%- endmacro -%}\n\n{%- macro render_tools(tool_list) -%}\n {%- set ts = namespace(schemas=[]) -%}\n {%- for tool in tool_list -%}\n {%- set fn = tool.function if tool.function is defined else tool -%}\n {%- set ns = tool.namespace if tool.namespace is defined and tool.namespace is not none else fn.get(\"namespace\") -%}\n {%- set schema = namespace(d={}) -%}\n {%- for k, v in fn.items() if k != \"namespace\" -%}{%- set schema.d = dict(schema.d, **{k: v}) -%}{%- endfor -%}\n {%- set schema.d = dict(schema.d, name=qualified_name(fn.name, ns)) -%}\n {%- if ns is mapping and ns.description -%}\n {%- set schema.d = dict(schema.d, description=ns.description ~ \"\\n\" ~ (fn.description or \"\")) -%}\n {%- endif -%}\n {%- set ts.schemas = ts.schemas + [schema.d | tojson] -%}\n {%- endfor -%}\n {{- \"## Tools\\n\\nYou have access to a set of tools to help answer the user's question. You can invoke tools by writing a \\\"<|DSML| calls>\\\" block like the following:\\n\\n<|DSML| calls>\\n<|DSML| invoke name=\\\"$TOOL_NAME\\\">\\n<|DSML| parameter name=\\\"$PARAMETER_NAME\\\" string=\\\"true|false\\\">$PARAMETER_VALUE</|DSML| parameter>\\n...\\n</|DSML| invoke>\\n<|DSML| invoke name=\\\"$TOOL_NAME2\\\">\\n...\\n</|DSML| invoke>\\n</|DSML| calls>\\n\\nString parameters should be specified as is and set `string=\\\"true\\\"`. For all other types (numbers, booleans, arrays, objects), pass the value in JSON format and set `string=\\\"false\\\"`.\\n\\nIf thinking_mode is enabled (triggered by <think>), you MUST output your complete reasoning inside <think>...</think> BEFORE any tool calls or final response.\\n\\nOtherwise, output directly after </think> with tool calls or final response.\\n\\n### Available Tool Schemas\\n\\n\" -}}\n {{- ts.schemas | join(\"\\n\") -}}\n {{- \"\\n\\nYou MUST strictly follow the above defined tool name and parameter schemas to invoke tool calls.\\n\" -}}\n{%- endmacro -%}\n\n{#- 1. Merge tool results (and consecutive user turns) into user messages made of content blocks. -#}\n{%- set mns = namespace(list=[]) -%}\n{%- for msg in messages -%}\n {%- set content = msg.get(\"content\") -%}\n {%- if msg.role == \"user\" and msg.get(\"content_blocks\") is not none -%}\n {%- set content = msg.content_blocks -%}\n {%- elif msg.role == \"tool\" and msg.get(\"content_blocks\") and content is not string -%}\n {%- set content = msg.content_blocks -%}\n {%- endif -%}\n {%- set is_blocks = content is iterable and content is not string and content is not mapping -%}\n {%- if content is string and IMG in content -%}\n {{- raise_exception(\"Message content contains image special token \" ~ IMG ~ \". Images should be provided as image content blocks.\") -}}\n {%- endif -%}\n {%- set rc = msg.reasoning_content if msg.get(\"reasoning_content\") is not none else msg.get(\"thinking\") -%}\n {%- if rc is string and IMG in rc -%}\n {{- raise_exception(\"reasoning_content contains image special token \" ~ IMG) -}}\n {%- endif -%}\n {%- set prev = mns.list[-1] if mns.list else none -%}\n {%- if msg.role == \"tool\" -%}\n {%- set tblock = {\"type\": \"tool_result\", \"tool_use_id\": msg.get(\"tool_call_id\", \"\"), \"content\": joined_text(content) if is_blocks else (content or \"\")} -%}\n {%- if prev is not none and prev.role == \"user\" -%}\n {%- set mns.list = mns.list[:-1] + [dict(prev, content_blocks=prev.content_blocks + [tblock])] -%}\n {%- else -%}\n {%- set mns.list = mns.list + [{\"role\": \"user\", \"content_blocks\": [tblock]}] -%}\n {%- endif -%}\n {%- elif msg.role == \"user\" -%}\n {%- set blocks = content if is_blocks else [{\"type\": \"text\", \"text\": content or \"\"}] -%}\n {%- if prev is not none and prev.role == \"user\" and prev.get(\"task\") is none -%}\n {%- set mns.list = mns.list[:-1] + [dict(prev, content_blocks=prev.content_blocks + blocks)] -%}\n {%- else -%}\n {%- set mns.list = mns.list + [dict(msg, content_blocks=blocks)] -%}\n {%- endif -%}\n {%- else -%}\n {%- set mns.list = mns.list + [msg] -%}\n {%- endif -%}\n{%- endfor -%}\n\n{#- Top-level tools attach to a leading system message, or to a new empty one. -#}\n{%- if tools -%}\n {%- if mns.list and mns.list[0].role == \"system\" -%}\n {%- if not mns.list[0].get(\"tools\") -%}{%- set mns.list = [dict(mns.list[0], tools=tools)] + mns.list[1:] -%}{%- endif -%}\n {%- else -%}\n {%- set mns.list = [{\"role\": \"system\", \"content\": \"\", \"tools\": tools}] + mns.list -%}\n {%- endif -%}\n{%- endif -%}\n\n{#- 2. Reorder tool results to match the tool_calls order of the preceding assistant message. -#}\n{%- set sns = namespace(list=[], ids=[]) -%}\n{%- for m in mns.list -%}\n {%- if m.role == \"assistant\" and m.get(\"tool_calls\") -%}\n {%- set sns.ids = [] -%}\n {%- for tc in m.tool_calls -%}\n {%- set sns.ids = sns.ids + [tc.get(\"id\") or tc.get(\"function\", {}).get(\"id\", \"\")] -%}\n {%- endfor -%}\n {%- set sns.list = sns.list + [m] -%}\n {%- elif m.role == \"user\" and m.content_blocks -%}\n {%- set tb = namespace(blocks=[]) -%}\n {%- for b in m.content_blocks if b.type == \"tool_result\" -%}\n {%- set order = namespace(idx=0) -%}\n {%- for tc_id in sns.ids -%}\n {%- if tc_id and tc_id == b.get(\"tool_use_id\", \"\") -%}{%- set order.idx = loop.index0 -%}{%- endif -%}\n {%- endfor -%}\n {%- set tb.blocks = tb.blocks + [dict(b, _order=order.idx)] -%}\n {%- endfor -%}\n {%- if tb.blocks | length > 1 -%}\n {%- set sorted_blocks = tb.blocks | sort(attribute=\"_order\") -%}\n {%- set rb = namespace(blocks=[], i=0) -%}\n {%- for b in m.content_blocks -%}\n {%- if b.type == \"tool_result\" -%}\n {%- set rb.blocks = rb.blocks + [sorted_blocks[rb.i]] -%}\n {%- set rb.i = rb.i + 1 -%}\n {%- else -%}\n {%- set rb.blocks = rb.blocks + [b] -%}\n {%- endif -%}\n {%- endfor -%}\n {%- set sns.list = sns.list + [dict(m, content_blocks=rb.blocks)] -%}\n {%- else -%}\n {%- set sns.list = sns.list + [m] -%}\n {%- endif -%}\n {%- else -%}\n {%- set sns.list = sns.list + [m] -%}\n {%- endif -%}\n{%- endfor -%}\n{%- set msgs = sns.list -%}\n\n{#- Mid-conversation system messages count as user turns; user messages holding only tool results do not.\n Tools anywhere disable drop_thinking. -#}\n{%- set state = namespace(last_user=-1, has_tools=false) -%}\n{%- for m in msgs -%}\n {%- set starts_turn = (m.role == \"system\" and loop.index0 > 0) -%}\n {%- if m.role == \"user\" -%}\n {%- set turn = namespace(found=not m.content_blocks) -%}\n {%- for b in m.content_blocks or [] -%}\n {%- if b.type in [\"text\", \"image\", \"image_url\"] -%}{%- set turn.found = true -%}{%- endif -%}\n {%- endfor -%}\n {%- set starts_turn = turn.found -%}\n {%- endif -%}\n {%- if starts_turn -%}{%- set state.last_user = loop.index0 -%}{%- endif -%}\n {%- if m.get(\"tools\") -%}{%- set state.has_tools = true -%}{%- endif -%}\n{%- endfor -%}\n{%- set effective_drop = drop_thinking and not state.has_tools -%}\n{%- set thinking = thinking_mode == \"thinking\" -%}\n\n{{- \"<|begin▁of▁sentence|>\" -}}\n{#- 3. Render each message. -#}\n{%- for m in msgs -%}\n {%- set idx = loop.index0 -%}\n {%- set content = m.get(\"content\") -%}\n {%- if content is iterable and content is not string and content is not mapping -%}{%- set content = joined_text(content) -%}{%- endif -%}\n\n {%- if idx == 0 -%}\n {%- if thinking or m.role == \"system\" -%}{{- \"<|System|>\" -}}{%- endif -%}\n {%- if thinking -%}{{- \"Reasoning Effort: \" ~ budget ~ \" (range 1-100, the higher the value, the more thorough the reasoning)\\n\\n\" -}}{%- endif -%}\n {%- endif -%}\n\n {%- if m.role == \"system\" -%}\n {%- if idx > 0 -%}{{- \"<|System|>\" -}}{%- endif -%}\n {{- content or \"\" -}}\n {%- if m.get(\"tools\") -%}{{- \"\\n\\n\" ~ render_tools(m.tools) -}}{%- endif -%}\n {%- if m.get(\"response_format\") -%}\n {{- \"\\n\\n## Response Format:\\n\\nYou MUST strictly adhere to the following schema to reply:\\n\" ~ (m.response_format | tojson) -}}\n {%- endif -%}\n\n {%- elif m.role == \"user\" -%}\n {{- \"<|User|>\" -}}\n {%- set up = namespace(parts=[]) -%}\n {%- for b in m.content_blocks -%}\n {%- if b.type == \"text\" -%}\n {%- if IMG in (b.text or \"\") -%}{{- raise_exception(\"Text block contains image placeholder \" ~ IMG ~ \". Images should be separate content blocks.\") -}}{%- endif -%}\n {%- set up.parts = up.parts + [b.text or \"\"] -%}\n {%- elif b.type in [\"image\", \"image_url\"] -%}\n {%- set up.parts = up.parts + [IMG] -%}\n {%- elif b.type == \"tool_result\" -%}\n {%- set tc = b.get(\"content\", \"\") -%}\n {%- if tc is iterable and tc is not string and tc is not mapping -%}\n {%- set sub = namespace(parts=[]) -%}\n {%- for s in tc -%}\n {%- if s.type == \"text\" -%}{%- set sub.parts = sub.parts + [s.get(\"text\", \"\")] -%}\n {%- elif s.type in [\"image\", \"image_url\"] -%}{%- set sub.parts = sub.parts + [IMG] -%}\n {%- else -%}{%- set sub.parts = sub.parts + [\"[Unsupported \" ~ s.type ~ \"]\"] -%}\n {%- endif -%}\n {%- endfor -%}\n {%- set tc = sub.parts | join(\"\\n\\n\") -%}\n {%- endif -%}\n {%- set up.parts = up.parts + [\"<tool_result>\" ~ tc ~ \"</tool_result>\"] -%}\n {%- else -%}\n {%- set up.parts = up.parts + [\"[Unsupported \" ~ b.type ~ \"]\"] -%}\n {%- endif -%}\n {%- endfor -%}\n {{- up.parts | join(\"\\n\\n\") -}}\n\n {%- elif m.role == \"latest_reminder\" -%}\n {{- \"<|latest_reminder|>\" ~ content -}}\n\n {%- elif m.role == \"assistant\" -%}\n {%- set prev_has_task = idx > 0 and msgs[idx - 1].get(\"task\") is not none -%}\n {%- if thinking and not prev_has_task and (not effective_drop or idx > state.last_user) -%}\n {{- ((m.reasoning_content if m.get(\"reasoning_content\") is not none else m.get(\"thinking\")) or \"\") ~ \"</think>\" -}}\n {%- endif -%}\n {{- content or \"\" -}}\n {%- if m.get(\"tool_calls\") -%}\n {%- set tcs = namespace(lines=[]) -%}\n {%- for tc in m.tool_calls -%}\n {%- set fn = tc.function -%}\n {%- set params = namespace(lines=[]) -%}\n {%- if fn.arguments is string -%}{{- raise_exception(\"Tool call arguments must be a dict, not a JSON string\") -}}{%- endif -%}\n {%- set args = fn.arguments if fn.arguments is mapping else {\"arguments\": fn.arguments} -%}\n {%- for k, v in args.items() -%}\n {%- set params.lines = params.lines + [\"<\" ~ DSML ~ \" parameter name=\\\"\" ~ k ~ \"\\\" string=\\\"\" ~ (\"true\" if v is string else \"false\") ~ \"\\\">\" ~ (v if v is string else v | tojson) ~ \"</\" ~ DSML ~ \" parameter>\"] -%}\n {%- endfor -%}\n {%- set name = qualified_name(fn.name, tc.get(\"namespace\") or fn.get(\"namespace\")) -%}\n {%- set tcs.lines = tcs.lines + [\"<\" ~ DSML ~ \" invoke name=\\\"\" ~ name ~ \"\\\">\\n\" ~ params.lines | join(\"\\n\") ~ \"\\n</\" ~ DSML ~ \" invoke>\"] -%}\n {%- endfor -%}\n {{- \"\\n\\n<\" ~ DSML ~ \" calls>\\n\" ~ tcs.lines | join(\"\\n\") ~ \"\\n</\" ~ DSML ~ \" calls>\" -}}\n {%- endif -%}\n {%- if not m.get(\"wo_eos\", false) -%}{{- \"<|end▁of▁sentence|>\" -}}{%- endif -%}\n\n {%- else -%}\n {{- raise_exception(\"Unknown role: \" ~ m.role) -}}\n {%- endif -%}\n\n {#- Transition tokens, only when the next message is an assistant/latest_reminder turn or this is the last one. -#}\n {%- if loop.last or msgs[idx + 1].role in [\"assistant\", \"latest_reminder\"] -%}\n {%- set task = m.get(\"task\") -%}\n {%- if task is not none -%}\n {%- set task_tokens = {\"action\": \"<|action|>\", \"query\": \"<|query|>\", \"authority\": \"<|authority|>\", \"domain\": \"<|domain|>\", \"title\": \"<|title|>\", \"read_url\": \"<|read_url|>\"} -%}\n {%- if task not in task_tokens -%}{{- raise_exception(\"Invalid task: '\" ~ task ~ \"'\") -}}{%- endif -%}\n {%- if task == \"action\" -%}{{- \"<|Assistant|>\" ~ (\"<think>\" if thinking else \"</think>\") -}}{%- endif -%}\n {{- task_tokens[task] -}}\n {%- elif (m.role == \"user\" or (m.role == \"system\" and idx > 0)) and (add_generation_prompt or not loop.last) -%}\n {{- \"<|Assistant|>\" ~ (\"<think>\" if thinking and (not effective_drop or idx >= state.last_user) else \"</think>\") -}}\n {%- endif -%}\n {%- endif -%}\n{%- endfor -%}\n",
"templatePath": "chat_template.jinja",
"templateUrl": "https://huggingface.co/deepseek-ai/DeepSeek-V4.1-Flash-1017/blob/08c8657f02291e11b6f6b63e0e16014f8e748518/chat_template.jinja",
"templateToolLines": [
75,
130
],
"templateHelperSource": null,
"templateHelperPath": null,
"templateHelperUrl": null,
"bosToken": "<|begin▁of▁sentence|>",
"eosToken": "<|end▁of▁sentence|>",
"padToken": "<|end▁of▁sentence|>",
"unkToken": "",
"specialTokens": {
"<|begin▁of▁sentence|>": 0,
"<|end▁of▁sentence|>": 1,
"<|▁pad▁|>": 2,
"<|System|>": 128799,
"<|fim▁hole|>": 128800,
"<|fim▁begin|>": 128801,
"<|fim▁end|>": 128802,
"<|User|>": 128803,
"<|Assistant|>": 128804,
"<|EOT|>": 128805,
"<|tool▁calls▁begin|>": 128806,
"<|tool▁calls▁end|>": 128807,
"<|tool▁call▁begin|>": 128808,
"<|tool▁call▁end|>": 128809,
"<|tool▁outputs▁begin|>": 128810,
"<|tool▁outputs▁end|>": 128811,
"<|tool▁output▁begin|>": 128812,
"<|tool▁output▁end|>": 128813,
"<|tool▁sep|>": 128814,
"<|begin▁of▁repo▁name|>": 128815,
"<|end▁of▁repo▁name|>": 128816,
"<|begin▁of▁file▁name|>": 128817,
"<|end▁of▁file▁name|>": 128818,
"<|begin▁of▁file|>": 128819,
"<|end▁of▁file|>": 128820,
"<think>": 128821,
"</think>": 128822,
"|DSML|": 128825,
"<|begin▁sys|>": 128826,
"<|end▁sys|>": 128827,
"<|latest_reminder|>": 128828,
"<|action|>": 128829,
"<|query|>": 128830,
"<|authority|>": 128831,
"<|domain|>": 128832,
"<|task|>": 128833,
"<|political|>": 128834,
"<|entity|>": 128835,
"<|title|>": 128836,
"<|safety|>": 128837,
"<|answer|>": 128838,
"<|search|>": 128839,
"<dsml:": 128840,
"</dsml:": 128841,
"<|search▁begin|>": 128842,
"<|search▁end|>": 128843,
"<|extracted_url|>": 128844,
"<|read_url|>": 128845,
"<|end_of_query|>": 128846,
"<|rl_image_pad|>": 129262,
"<|rl_image_start|>": 129263,
"<|deepseek_image|>": 129264,
"<|/polygon|>": 129271,
"<|polygon|>": 129272,
"<|/point|>": 129273,
"<|point|>": 129274,
"<|/box|>": 129275,
"<|box|>": 129276,
"<|/ref|>": 129277,
"<|ref|>": 129278
},
"stopTokenCall": "<|end▁of▁sentence|>",
"stopTokenText": "<|end▁of▁sentence|>",
"dedicatedStopToken": false,
"stopKind": "shared",
"eosNote": "No generation_config.json is pinned in the repo; tokenizer_config.json and chat_template.jinja use shared <|end▁of▁sentence|> (id 1) for both DSML tool calls and plain text replies.",
"cap": "DeepSeek-V4.1 prints each tool as a newline-delimited JSON line under <code>## Tools</code> / <code>### Available Tool Schemas</code> inside <code><|System|></code>. Its Jinja template uses Python's <code>.format()</code> to inject the <code>|DSML|</code> marker prefix into every example tag.",
"outCap": "DeepSeek-V4.1 emits spaced DSML tags (<code><|DSML| calls></code>, <code><|DSML| invoke></code>, <code><|DSML| parameter name=... string=\"true|false\"></code>) and stops on shared <code><|end▁of▁sentence|></code>.",
"walkSteps": {
"s2": "chat_template.jinja serializes each tool as a JSON line under ## Tools / ### Available Tool Schemas, preserving every nested object, enum, and constraint.",
"s3": "Below the schemas, the template appends detailed DSML formatting rules and spaced-tag examples injected via Python .format().",
"s4": "The rendered prompt ends with <|Assistant|><think>, placing the model inside its thinking block.",
"s5": "After </think>, the model writes plain-text spaced DSML tags (<|DSML| calls>, <|DSML| invoke>, <|DSML| parameter name=… string=\"true|false\">).",
"s6": "vLLM's deepseek_v41 and SGLang's DeepSeekV41Detector match the intentionally spaced tag names and JSON-decode parameters marked string=\"false\".",
"s7": "Generation stops on shared <|end▁of▁sentence|> (id 1); on an ordinary completed auto-tool turn with parsed calls, the server rewrites engine 'stop' to API finish_reason='tool_calls'."
},
"lane": [
"Reasoning text closes with </think>",
"<|DSML| calls> opens DSML call block",
"<|DSML| invoke name=\"…\"> names the tool",
"<|DSML| parameter name=\"…\" string=\"…\"> typed values",
"</|DSML| invoke> and </|DSML| calls> close block",
"<|end▁of▁sentence|> ends turn; sampler reports stop"
],
"laneText": [
"Reasoning text closes with </think>",
"Plain assistant answer text",
"<|end▁of▁sentence|> ends turn; sampler reports stop"
],
"excerpts": {
"vllm": [
{
"repo": "vllm",
"path": "vllm/parser/deepseek_v41.py",
"start": 17,
"end": 42,
"hl": [
17,
20,
21,
22,
23,
24
],
"sha": "ef687f6179b752c028767e610addbda67ed36d03",
"url": "https://github.com/vllm-project/vllm/blob/ef687f6179b752c028767e610addbda67ed36d03/vllm/parser/deepseek_v41.py#L17-L42",
"note": "vLLM's DeepSeek V4.1 parser overrides V4's terminals with V4.1's spaced <|DSML| calls> tags.",
"code": "DSML_TOOL_START = \"<|DSML| calls>\"\n# V4's ``tool_calls`` wrapper name with V4.1's spacing (#62051).\nDSML_TOOL_START_VARIANTS: tuple[str, ...] = (\"<|DSML| tool_calls>\",)\nDSML_TOOL_END = \"</|DSML| calls>\"\nDSML_INVOKE_PREFIX = '<|DSML| invoke name=\"'\nDSML_INVOKE_END = \"</|DSML| invoke>\"\nDSML_PARAM_START = \"<|DSML| parameter\"\nDSML_PARAM_CLOSE = \"</|DSML| parameter>\"\n# Turn markers, so a prompt-closed reasoning block is only honored in the\n# current turn (continue_final_message, or a template that skips thinking).\nDEEPSEEK_TURN_BOUNDARY_TOKENS = frozenset({\"<|User|>\", \"<|Assistant|>\"})\n\n_PARAM_RE, _PARTIAL_PARAM_RE = _param_patterns(DSML_PARAM_START, DSML_PARAM_CLOSE)\n\n\n@functools.cache\ndef deepseek_v41_config(thinking: bool = False) -> ParserEngineConfig:\n config = deepseek_v4_config(thinking=thinking)\n terminal_overrides = {\n \"TOOL_START\": DSML_TOOL_START,\n \"TOOL_END\": DSML_TOOL_END,\n \"INVOKE_PREFIX\": DSML_INVOKE_PREFIX,\n \"INVOKE_END\": DSML_INVOKE_END,\n \"PARAM_START\": DSML_PARAM_START,\n \"PARAM_CLOSE\": DSML_PARAM_CLOSE,\n }"
}
],
"sglang": [
{
"repo": "sglang",
"path": "python/sglang/srt/function_call/deepseekv41_detector.py",
"start": 6,
"end": 17,
"hl": [
12,
13,
14
],
"sha": "1918da6349f9be1c62315503e1a7458a3957bc5f",
"url": "https://github.com/sgl-project/sglang/blob/1918da6349f9be1c62315503e1a7458a3957bc5f/python/sglang/srt/function_call/deepseekv41_detector.py#L6-L17",
"note": "SGLang's DeepSeekV41Detector subclasses DeepSeekV32Detector to override the leading-space DSML tag names.",
"code": "class DeepSeekV41Detector(DeepSeekV32Detector):\n \"\"\"DeepSeek V4.1 DSML detector.\n\n The leading space in each tag name below is intentional, not a typo.\n \"\"\"\n\n tool_calls_block_name = \" calls\"\n invoke_tag_name = \" invoke\"\n parameter_tag_name = \" parameter\"\n\n def get_structural_tag_name(self) -> Optional[str]:\n return \"deepseek_v4_1\""
}
]
}
},
{
"key": "inkling2",
"id": "thinkingmachines/Inkling-2-Small",
"label": "Inkling-2-Small",
"sub": "Typed content tokens",
"sha": "885d78bfca61a7e9a498e33cfa7ad35850533b8c",
"created": "2026-11-04",
"likes": 684,
"templateKind": "jinja",
"schemaEncoding": "Sorted JSON in <|content_xml|>",
"callSyntax": "<|content_invoke_tool_json|>",
"servingNote": "Inkling-2 frames every block with dedicated special tokens (<|message_model|>, <|content_invoke_tool_json|>, <|end_message|>, <|content_model_end_sampling|>); vLLM (vllm/parser/inkling.py) and SGLang (Inkling2Detector) parse the typed JSON wrapper.",
"chatTemplate": "{%- set effort_map = {\"none\": 0.0, \"minimal\": 0.1, \"low\": 0.2, \"medium\": 0.7, \"high\": 0.9, \"xhigh\": 0.99, \"max\": 0.99} -%}\n{%- set role_token = {\"user\": \"<|message_user|>\", \"assistant\": \"<|message_model|>\", \"system\": \"<|message_system|>\", \"tool\": \"<|message_tool|>\"} -%}\n\n{%- macro emit_thinking_effort() -%}\n {%- set eff = reasoning_effort if reasoning_effort is defined and reasoning_effort is not none else 0.9 -%}\n {%- if eff is string -%}\n {%- set key = eff | trim -%}\n {%- if key not in effort_map -%}\n {{- raise_exception(\"Unknown reasoning_effort: \" ~ eff) -}}\n {%- endif -%}\n {%- set num = effort_map[key] -%}\n {%- else -%}\n {%- set num = eff | float -%}\n {%- endif -%}\n {%- if num < 0.0 or num > 0.99 -%}\n {{- raise_exception(\"reasoning_effort must be in [0.0, 0.99]\") -}}\n {%- endif -%}\n {{- \"<|message_system|><|content_text|>Thinking effort level: \" -}}\n {%- if num == 0.0 -%}0{%- else -%}{{ num }}{%- endif -%}\n {{- \"<|end_message|>\" -}}\n{%- endmacro -%}\n\n{%- if tools -%}\n {%- set tool_state = namespace(specs=[]) -%}\n {%- for tool in tools -%}\n {%- set fn = tool.function if tool.function is defined else tool -%}\n {%- set spec = {\n \"description\": (fn.description if fn.description is defined and fn.description else \"\"),\n \"name\": fn.name,\n \"parameters\": (fn.parameters if fn.parameters is defined and fn.parameters else {}),\n \"type\": (tool.type if tool.type is defined and tool.type else \"function\"),\n } -%}\n {%- set tool_state.specs = tool_state.specs + [spec] -%}\n {%- endfor -%}\n {{- \"<|message_system|>tool_declare<|content_xml|>\" -}}\n {{- tool_state.specs | tojson(sort_keys=true, separators=(\",\", \":\")) -}}\n {{- \"<|end_message|>\" -}}\n{%- endif -%}\n\n{%- set state = namespace(effort_emitted=false) -%}\n{%- for message in messages -%}\n {%- if message.role not in role_token -%}\n {{- raise_exception(\"Unknown message role: \" ~ message.role) -}}\n {%- endif -%}\n {%- if not state.effort_emitted and message.role != \"system\" -%}\n {{- emit_thinking_effort() -}}\n {%- set state.effort_emitted = true -%}\n {%- endif -%}\n\n {%- set header = namespace(text=role_token[message.role]) -%}\n {%- if message.role == \"tool\" -%}\n {%- if message.name is defined and message.name -%}\n {%- set header.text = header.text ~ message.name -%}\n {%- elif message.tool_call_id is defined and message.tool_call_id -%}\n {%- for prev in messages -%}\n {%- if prev.role == \"assistant\" and prev.tool_calls -%}\n {%- for tc in prev.tool_calls -%}\n {%- if tc.id is defined and tc.id == message.tool_call_id and tc.function.name is defined -%}\n {%- set header.text = header.text ~ tc.function.name -%}\n {%- endif -%}\n {%- endfor -%}\n {%- endif -%}\n {%- endfor -%}\n {%- endif -%}\n {%- elif message.role == \"assistant\" and message.name is defined and message.name -%}\n {%- set header.text = header.text ~ message.name -%}\n {%- endif -%}\n {%- set rtok = header.text -%}\n {%- set rendered -%}\n\n {%- if message.role == \"assistant\" and message.reasoning_content is defined and message.reasoning_content -%}\n {{- rtok ~ \"<|content_thinking|>\" ~ message.reasoning_content ~ \"<|end_message|>\" -}}\n {%- endif -%}\n\n {%- if message.content is string and (message.content or not (message.role == \"assistant\" and (message.tool_calls or message.reasoning_content))) -%}\n {{- rtok ~ \"<|content_text|>\" ~ message.content ~ \"<|end_message|>\" -}}\n {%- elif message.content -%}\n {%- for part in message.content -%}\n {%- if part is string -%}\n {{- rtok ~ \"<|content_text|>\" ~ part ~ \"<|end_message|>\" -}}\n {%- elif part.type is not defined or part.type in (\"text\", \"input_text\") -%}\n {%- set text_part = (part.text if part.text is defined and part.text is string else \"\") -%}\n {{- rtok ~ \"<|content_text|>\" ~ text_part ~ \"<|end_message|>\" -}}\n {%- elif part.type in (\"image\", \"input_image\", \"image_url\") -%}\n {%- if message.role not in (\"user\", \"tool\") -%}\n {{- raise_exception(\"Image content is only supported for user and tool messages\") -}}\n {%- endif -%}\n {{- rtok ~ \"<|content_image|><|unused_200054|><|end_message|>\" -}}\n {%- elif part.type in (\"audio\", \"input_audio\", \"audio_url\") -%}\n {{- raise_exception(\"Inkling 2 does not accept audio input\") -}}\n {%- else -%}\n {{- raise_exception(\"Unsupported content part type: \" ~ part.type) -}}\n {%- endif -%}\n {%- endfor -%}\n {%- endif -%}\n\n {%- if message.role == \"assistant\" and message.tool_calls -%}\n {%- for tc in message.tool_calls -%}\n {%- set fn = tc.function -%}\n {%- if fn.name is not defined or fn.name is not string -%}\n {{- raise_exception(\"tool call function name must be a string\") -}}\n {%- endif -%}\n {%- if message.name is defined and message.name and message.name != fn.name -%}\n {{- raise_exception(\"assistant name \" ~ message.name ~ \" does not match its tool call \" ~ fn.name) -}}\n {%- endif -%}\n {%- set args = fn.arguments if fn.arguments is defined and fn.arguments else {} -%}\n {%- if args is string -%}\n {{- raise_exception(\"tool call arguments must be a parsed object, not a JSON string; canonicalize upstream\") -}}\n {%- endif -%}\n {%- if args is not mapping -%}\n {{- raise_exception(\"tool call arguments must be an object\") -}}\n {%- endif -%}\n {{- \"<|message_model|>\" ~ fn.name ~ \"<|content_invoke_tool_json|>\" -}}\n {{- '{\"name\":' ~ (fn.name | tojson(sort_keys=true, separators=(\",\", \":\"))) ~ ',\"args\":' -}}\n {{- \"{\" -}}\n {%- for key, value in args | dictsort(case_sensitive=true) -%}\n {{- (key | tojson) ~ \":\" ~ (value | tojson(separators=(\",\", \":\"))) -}}\n {%- if not loop.last -%},{%- endif -%}\n {%- endfor -%}\n {{- \"}}<|end_message|>\" -}}\n {%- endfor -%}\n {%- endif -%}\n\n {%- if message.role == \"assistant\" -%}\n {{- \"<|content_model_end_sampling|>\" -}}\n {%- endif -%}\n {%- endset -%}\n {%- if message.role == \"assistant\" -%}\n {%- generation -%}{{- rendered -}}{%- endgeneration -%}\n {%- else -%}\n {{- rendered -}}\n {%- endif -%}\n{%- endfor -%}\n\n{%- if not state.effort_emitted -%}\n {{- emit_thinking_effort() -}}\n{%- endif -%}\n",
"templatePath": "chat_template.jinja",
"templateUrl": "https://huggingface.co/thinkingmachines/Inkling-2-Small/blob/885d78bfca61a7e9a498e33cfa7ad35850533b8c/chat_template.jinja",
"templateToolLines": [
23,
40
],
"templateHelperSource": null,
"templateHelperPath": null,
"templateHelperUrl": null,
"bosToken": "",
"eosToken": "<|content_model_end_sampling|>",
"padToken": "<|endoftext|>",
"unkToken": "",
"specialTokens": {
"<|unused|>": 199998,
"<|endoftext|>": 199999,
"<|message_user|>": 200000,
"<|message_model|>": 200001,
"<|message_system|>": 200002,
"<|message_tool|>": 200003,
"<|content_text|>": 200004,
"<|content_image|>": 200005,
"<|content_model_end_sampling|>": 200006,
"<|unused_200007|>": 200007,
"<|content_thinking|>": 200008,
"<|unused_200009|>": 200009,
"<|end_message|>": 200010,
"<|unused_200011|>": 200011,
"<|unused_200012|>": 200012,
"<|unused_200013|>": 200013,
"<|unused_200014|>": 200014,
"<|unused_200015|>": 200015,
"<|unused_200016|>": 200016,
"<|unused_200017|>": 200017,
"<|unused_200018|>": 200018,
"<|unused_200019|>": 200019,
"<|unused_200020|>": 200020,
"<|unused_200021|>": 200021,
"<|content_tool_error|>": 200022,
"<|unused_200023|>": 200023,
"<|content_xml|>": 200024,
"<|unused_200025|>": 200025,
"<|unused_200026|>": 200026,
"<|unused_200027|>": 200027,
"<|begin_of_text|>": 200028,
"<|unused_200029|>": 200029,
"<|unused_200030|>": 200030,
"<|unused_200031|>": 200031,
"<|unused_200032|>": 200032,
"<|unused_200033|>": 200033,
"<|unused_200034|>": 200034,
"<|unused_200035|>": 200035,
"<|unused_200036|>": 200036,
"<|unused_200037|>": 200037,
"<|unused_200038|>": 200038,
"<|unused_200039|>": 200039,
"<|unused_200040|>": 200040,
"<|unused_200041|>": 200041,
"<|unused_200042|>": 200042,
"<|unused_200043|>": 200043,
"<|unused_200044|>": 200044,
"<|unused_200045|>": 200045,
"<|unused_200046|>": 200046,
"<|unused_200047|>": 200047,
"<|unused_200048|>": 200048,
"<|content_invoke_tool_json|>": 200049,
"<|unused_200050|>": 200050,
"<|unused_200051|>": 200051,
"<|unused_200052|>": 200052,
"<|unused_200053|>": 200053,
"<|unused_200054|>": 200054,
"<|unused_200055|>": 200055,
"<|unused_200056|>": 200056,
"<|content_invoke_tool_text|>": 200057
},
"stopTokenCall": "<|content_model_end_sampling|>",
"stopTokenText": "<|content_model_end_sampling|>",
"dedicatedStopToken": false,
"stopKind": "shared",
"eosNote": "Inkling-2's generation_config sets EOS to <|content_model_end_sampling|> (id 200006), shared by both tool calls and text replies; <|end_message|> (200019) closes each internal message block.",
"cap": "Inkling-2 declares tools inside <code><|message_system|>tool_declare<|content_xml|></code>—despite the token name, the payload is a compact, key-sorted JSON array of function schemas. Every constraint and nested object is preserved.",
"outCap": "Inkling-2 switches to <code><|content_invoke_tool_json|></code>, writes <code>{\"name\":\"...\",\"args\":{...}}</code> with sorted argument keys, closes with <code><|end_message|></code>, and halts on shared <code><|content_model_end_sampling|></code>.",
"walkSteps": {
"s2": "chat_template.jinja serializes tools as a key-sorted compact JSON array inside <|message_system|>tool_declare<|content_xml|>, preserving every nested schema and constraint.",
"s3": "The template writes zero prose instructions or calling examples—only special framing tokens around the JSON array.",
"s4": "There is no separate assistant generation prefix: the prompt stops directly after the user turn's <|end_message|>, and the model emits its own <|message_model|> opener.",
"s5": "After a <|content_thinking|> block, the model emits <|message_model|>{name}<|content_invoke_tool_json|>{\"name\":…,\"args\":{…}}<|end_message|>.",
"s6": "vLLM's Inkling parser and SGLang's InklingDetector (keeping special tokens) anchor on <|content_invoke_tool_json|> and <|end_message|> to parse the JSON payload.",
"s7": "Sampling stops on shared <|content_model_end_sampling|> (200006); on an ordinary completed auto-tool turn with parsed calls, the server rewrites engine 'stop' to API finish_reason='tool_calls'."
},
"lane": [
"<|message_model|><|content_thinking|> … <|end_message|> reasoning",
"<|message_model|> + tool name opens call message",
"<|content_invoke_tool_json|> switches to JSON call mode",
"{\"name\":…,\"args\":{…}} compact JSON payload",
"<|end_message|> closes invocation message",
"<|content_model_end_sampling|> ends turn; sampler reports stop"
],
"laneText": [
"<|message_model|><|content_thinking|> … <|end_message|> reasoning",
"<|message_model|><|content_text|> plain answer text",
"<|end_message|><|content_model_end_sampling|> ends turn; sampler reports stop"
],
"excerpts": {
"vllm": [
{
"repo": "vllm",
"path": "vllm/parser/inkling.py",
"start": 79,
"end": 98,
"hl": [
80,
81,
82,
83,
86,
87
],
"sha": "ef687f6179b752c028767e610addbda67ed36d03",
"url": "https://github.com/vllm-project/vllm/blob/ef687f6179b752c028767e610addbda67ed36d03/vllm/parser/inkling.py#L79-L98",
"note": "vLLM's Inkling parser imports dedicated framing tokens including <|content_invoke_tool_json|> and <|content_model_end_sampling|>.",
"code": "INKLING_SPECIAL_TOKENS = (\n MESSAGE_MODEL,\n CONTENT_TEXT,\n CONTENT_THINKING,\n CONTENT_INVOKE_TOOL_JSON,\n CONTENT_INVOKE_TOOL_TEXT,\n CONTENT_TOOL_ERROR,\n CONTENT_MODEL_END_SAMPLING,\n END_MESSAGE,\n)\n\n# Every framing token; free text in a grammar never contains one.\nINKLING_CONTROL_TOKENS = (\n END_OF_TEXT,\n MESSAGE_USER,\n MESSAGE_SYSTEM,\n MESSAGE_TOOL,\n CONTENT_IMAGE,\n CONTENT_XML,\n CONTENT_AUDIO_INPUT,"
}
],
"sglang": [
{
"repo": "sglang",
"path": "python/sglang/srt/function_call/inkling_detector.py",
"start": 33,
"end": 52,
"hl": [
43,
44
],
"sha": "1918da6349f9be1c62315503e1a7458a3957bc5f",
"url": "https://github.com/sgl-project/sglang/blob/1918da6349f9be1c62315503e1a7458a3957bc5f/python/sglang/srt/function_call/inkling_detector.py#L33-L52",
"note": "SGLang's InklingDetector sets bot_token=<|content_invoke_tool_json|> and eot_token=<|end_message|>.",
"code": "class InklingDetector(BaseFormatDetector):\n \"\"\"\n Detector for Inkling structured tool calls.\n\n Format:\n <|message_model|>name<|content_invoke_tool_json|>{\"name\":\"...\",\"args\":{...}}<|end_message|>\n \"\"\"\n\n def __init__(self):\n super().__init__()\n self.bot_token = CONTENT_INVOKE_TOOL_JSON\n self.eot_token = END_MESSAGE\n # Streaming: index of the next call to emit; once a call fails to frame,\n # the rest of the response streams through verbatim.\n self._stream_call_index = 0\n self._raw_passthrough = False\n\n def has_tool_call(self, text: str) -> bool:\n return self.bot_token in text or CONTENT_INVOKE_TOOL_TEXT in text\n"
}
]
}
},
{
"key": "gptoss",
"id": "openai/gpt-oss-120b",
"label": "gpt-oss-120b",
"sub": "Harmony TypeScript",
"sha": "b5c939de8f754692c1647ca79fbf85e8c1e70f8a",
"created": "2025-08-04",
"likes": 5553,
"templateKind": "jinja",
"schemaEncoding": "TS macro (lossy on nested)",
"callSyntax": "<|channel|>commentary … <|call|>",
"servingNote": "vLLM (harmony.py) accepts both header orders (to=functions.x<|channel|>commentary and <|channel|>commentary to=functions.x); SGLang's gpt_oss_detector.py uses its own HarmonyParser and expects <|channel|>commentary before to=functions.x<|constrain|>json.",
"chatTemplate": "{#-\n In addition to the normal inputs of `messages` and `tools`, this template also accepts the\n following kwargs:\n - \"builtin_tools\": A list, can contain \"browser\" and/or \"python\".\n - \"model_identity\": A string that optionally describes the model identity.\n - \"reasoning_effort\": A string that describes the reasoning effort, defaults to \"medium\".\n #}\n\n{#- Tool Definition Rendering ============================================== #}\n{%- macro render_typescript_type(param_spec, required_params, is_nullable=false) -%}\n {%- if param_spec.type == \"array\" -%}\n {%- if param_spec['items'] -%}\n {%- if param_spec['items']['type'] == \"string\" -%}\n {{- \"string[]\" }}\n {%- elif param_spec['items']['type'] == \"number\" -%}\n {{- \"number[]\" }}\n {%- elif param_spec['items']['type'] == \"integer\" -%}\n {{- \"number[]\" }}\n {%- elif param_spec['items']['type'] == \"boolean\" -%}\n {{- \"boolean[]\" }}\n {%- else -%}\n {%- set inner_type = render_typescript_type(param_spec['items'], required_params) -%}\n {%- if inner_type == \"object | object\" or inner_type|length > 50 -%}\n {{- \"any[]\" }}\n {%- else -%}\n {{- inner_type + \"[]\" }}\n {%- endif -%}\n {%- endif -%}\n {%- if param_spec.nullable -%}\n {{- \" | null\" }}\n {%- endif -%}\n {%- else -%}\n {{- \"any[]\" }}\n {%- if param_spec.nullable -%}\n {{- \" | null\" }}\n {%- endif -%}\n {%- endif -%}\n {%- elif param_spec.type is defined and param_spec.type is iterable and param_spec.type is not string and param_spec.type is not mapping and param_spec.type[0] is defined -%}\n {#- Handle array of types like [\"object\", \"object\"] from Union[dict, list] #}\n {%- if param_spec.type | length > 1 -%}\n {{- param_spec.type | join(\" | \") }}\n {%- else -%}\n {{- param_spec.type[0] }}\n {%- endif -%}\n {%- elif param_spec.oneOf -%}\n {#- Handle oneOf schemas - check for complex unions and fallback to any #}\n {%- set has_object_variants = false -%}\n {%- for variant in param_spec.oneOf -%}\n {%- if variant.type == \"object\" -%}\n {%- set has_object_variants = true -%}\n {%- endif -%}\n {%- endfor -%}\n {%- if has_object_variants and param_spec.oneOf|length > 1 -%}\n {{- \"any\" }}\n {%- else -%}\n {%- for variant in param_spec.oneOf -%}\n {{- render_typescript_type(variant, required_params) -}}\n {%- if variant.description %}\n {{- \"// \" + variant.description }}\n {%- endif -%}\n {%- if variant.default is defined %}\n {{ \"// default: \" + variant.default|tojson }}\n {%- endif -%}\n {%- if not loop.last %}\n {{- \" | \" }}\n {% endif -%}\n {%- endfor -%}\n {%- endif -%}\n {%- elif param_spec.type == \"string\" -%}\n {%- if param_spec.enum -%}\n {{- '\"' + param_spec.enum|join('\" | \"') + '\"' -}}\n {%- else -%}\n {{- \"string\" }}\n {%- if param_spec.nullable %}\n {{- \" | null\" }}\n {%- endif -%}\n {%- endif -%}\n {%- elif param_spec.type == \"number\" -%}\n {{- \"number\" }}\n {%- elif param_spec.type == \"integer\" -%}\n {{- \"number\" }}\n {%- elif param_spec.type == \"boolean\" -%}\n {{- \"boolean\" }}\n\n {%- elif param_spec.type == \"object\" -%}\n {%- if param_spec.properties -%}\n {{- \"{\\n\" }}\n {%- for prop_name, prop_spec in param_spec.properties.items() -%}\n {{- prop_name -}}\n {%- if prop_name not in (param_spec.required or []) -%}\n {{- \"?\" }}\n {%- endif -%}\n {{- \": \" }}\n {{ render_typescript_type(prop_spec, param_spec.required or []) }}\n {%- if not loop.last -%}\n {{-\", \" }}\n {%- endif -%}\n {%- endfor -%}\n {{- \"}\" }}\n {%- else -%}\n {{- \"object\" }}\n {%- endif -%}\n {%- else -%}\n {{- \"any\" }}\n {%- endif -%}\n{%- endmacro -%}\n\n{%- macro render_tool_namespace(namespace_name, tools) -%}\n {{- \"## \" + namespace_name + \"\\n\\n\" }}\n {{- \"namespace \" + namespace_name + \" {\\n\\n\" }}\n {%- for tool in tools %}\n {%- set tool = tool.function %}\n {{- \"// \" + tool.description + \"\\n\" }}\n {{- \"type \"+ tool.name + \" = \" }}\n {%- if tool.parameters and tool.parameters.properties %}\n {{- \"(_: {\\n\" }}\n {%- for param_name, param_spec in tool.parameters.properties.items() %}\n {%- if param_spec.description %}\n {{- \"// \" + param_spec.description + \"\\n\" }}\n {%- endif %}\n {{- param_name }}\n {%- if param_name not in (tool.parameters.required or []) -%}\n {{- \"?\" }}\n {%- endif -%}\n {{- \": \" }}\n {{- render_typescript_type(param_spec, tool.parameters.required or []) }}\n {%- if param_spec.default is defined -%}\n {%- if param_spec.enum %}\n {{- \", // default: \" + param_spec.default }}\n {%- elif param_spec.oneOf %}\n {{- \"// default: \" + param_spec.default }}\n {%- else %}\n {{- \", // default: \" + param_spec.default|tojson }}\n {%- endif -%}\n {%- endif -%}\n {%- if not loop.last %}\n {{- \",\\n\" }}\n {%- else %}\n {{- \",\\n\" }}\n {%- endif -%}\n {%- endfor %}\n {{- \"}) => any;\\n\\n\" }}\n {%- else -%}\n {{- \"() => any;\\n\\n\" }}\n {%- endif -%}\n {%- endfor %}\n {{- \"} // namespace \" + namespace_name }}\n{%- endmacro -%}\n\n{%- macro render_builtin_tools(browser_tool, python_tool) -%}\n {%- if browser_tool %}\n {{- \"## browser\\n\\n\" }}\n {{- \"// Tool for browsing.\\n\" }}\n {{- \"// The `cursor` appears in brackets before each browsing display: `[{cursor}]`.\\n\" }}\n {{- \"// Cite information from the tool using the following format:\\n\" }}\n {{- \"// `【{cursor}†L{line_start}(-L{line_end})?】`, for example: `【6†L9-L11】` or `【8†L3】`.\\n\" }}\n {{- \"// Do not quote more than 10 words directly from the tool output.\\n\" }}\n {{- \"// sources=web (default: web)\\n\" }}\n {{- \"namespace browser {\\n\\n\" }}\n {{- \"// Searches for information related to `query` and displays `topn` results.\\n\" }}\n {{- \"type search = (_: {\\n\" }}\n {{- \"query: string,\\n\" }}\n {{- \"topn?: number, // default: 10\\n\" }}\n {{- \"source?: string,\\n\" }}\n {{- \"}) => any;\\n\\n\" }}\n {{- \"// Opens the link `id` from the page indicated by `cursor` starting at line number `loc`, showing `num_lines` lines.\\n\" }}\n {{- \"// Valid link ids are displayed with the formatting: `【{id}†.*】`.\\n\" }}\n {{- \"// If `cursor` is not provided, the most recent page is implied.\\n\" }}\n {{- \"// If `id` is a string, it is treated as a fully qualified URL associated with `source`.\\n\" }}\n {{- \"// If `loc` is not provided, the viewport will be positioned at the beginning of the document or centered on the most relevant passage, if available.\\n\" }}\n {{- \"// Use this function without `id` to scroll to a new location of an opened page.\\n\" }}\n {{- \"type open = (_: {\\n\" }}\n {{- \"id?: number | string, // default: -1\\n\" }}\n {{- \"cursor?: number, // default: -1\\n\" }}\n {{- \"loc?: number, // default: -1\\n\" }}\n {{- \"num_lines?: number, // default: -1\\n\" }}\n {{- \"view_source?: boolean, // default: false\\n\" }}\n {{- \"source?: string,\\n\" }}\n {{- \"}) => any;\\n\\n\" }}\n {{- \"// Finds exact matches of `pattern` in the current page, or the page given by `cursor`.\\n\" }}\n {{- \"type find = (_: {\\n\" }}\n {{- \"pattern: string,\\n\" }}\n {{- \"cursor?: number, // default: -1\\n\" }}\n {{- \"}) => any;\\n\\n\" }}\n {{- \"} // namespace browser\\n\\n\" }}\n {%- endif -%}\n\n {%- if python_tool %}\n {{- \"## python\\n\\n\" }}\n {{- \"Use this tool to execute Python code in your chain of thought. The code will not be shown to the user. This tool should be used for internal reasoning, but not for code that is intended to be visible to the user (e.g. when creating plots, tables, or files).\\n\\n\" }}\n {{- \"When you send a message containing Python code to python, it will be executed in a stateful Jupyter notebook environment. python will respond with the output of the execution or time out after 120.0 seconds. The drive at '/mnt/data' can be used to save and persist user files. Internet access for this session is UNKNOWN. Depends on the cluster.\\n\\n\" }}\n {%- endif -%}\n{%- endmacro -%}\n\n{#- System Message Construction ============================================ #}\n{%- macro build_system_message() -%}\n {%- if model_identity is not defined %}\n {%- set model_identity = \"You are ChatGPT, a large language model trained by OpenAI.\" %}\n {%- endif %}\n {{- model_identity + \"\\n\" }}\n {{- \"Knowledge cutoff: 2024-06\\n\" }}\n {{- \"Current date: \" + strftime_now(\"%Y-%m-%d\") + \"\\n\\n\" }}\n {%- if reasoning_effort is not defined %}\n {%- set reasoning_effort = \"medium\" %}\n {%- endif %}\n {{- \"Reasoning: \" + reasoning_effort + \"\\n\\n\" }}\n {%- if builtin_tools %}\n {{- \"# Tools\\n\\n\" }}\n {%- set available_builtin_tools = namespace(browser=false, python=false) %}\n {%- for tool in builtin_tools %}\n {%- if tool == \"browser\" %}\n {%- set available_builtin_tools.browser = true %}\n {%- elif tool == \"python\" %}\n {%- set available_builtin_tools.python = true %}\n {%- endif %}\n {%- endfor %}\n {{- render_builtin_tools(available_builtin_tools.browser, available_builtin_tools.python) }}\n {%- endif -%}\n {{- \"# Valid channels: analysis, commentary, final. Channel must be included for every message.\" }}\n {%- if tools -%}\n {{- \"\\nCalls to these tools must go to the commentary channel: 'functions'.\" }}\n {%- endif -%}\n{%- endmacro -%}\n\n{#- Main Template Logic ================================================= #}\n{#- Set defaults #}\n\n{#- Render system message #}\n{{- \"<|start|>system<|message|>\" }}\n{{- build_system_message() }}\n{{- \"<|end|>\" }}\n\n{#- Extract developer message #}\n{%- if messages[0].role == \"developer\" or messages[0].role == \"system\" %}\n {%- set developer_message = messages[0].content %}\n {%- set loop_messages = messages[1:] %}\n{%- else %}\n {%- set developer_message = \"\" %}\n {%- set loop_messages = messages %}\n{%- endif %}\n\n{#- Render developer message #}\n{%- if developer_message or tools %}\n {{- \"<|start|>developer<|message|>\" }}\n {%- if developer_message %}\n {{- \"# Instructions\\n\\n\" }}\n {{- developer_message }}\n {{- \"\\n\\n\" }}\n {%- endif %}\n {%- if tools -%}\n {{- \"# Tools\\n\\n\" }}\n {{- render_tool_namespace(\"functions\", tools) }}\n {%- endif -%}\n {{- \"<|end|>\" }}\n{%- endif %}\n\n{#- Render messages #}\n{%- set last_tool_call = namespace(name=none) %}\n{%- for message in loop_messages -%}\n {#- At this point only assistant/user/tool messages should remain #}\n {%- if message.role == 'assistant' -%}\n {#- Checks to ensure the messages are being passed in the format we expect #}\n {%- if \"content\" in message %}\n {%- if \"<|channel|>analysis<|message|>\" in message.content or \"<|channel|>final<|message|>\" in message.content %}\n {{- raise_exception(\"You have passed a message containing <|channel|> tags in the content field. Instead of doing this, you should pass analysis messages (the string between '<|message|>' and '<|end|>') in the 'thinking' field, and final messages (the string between '<|message|>' and '<|end|>') in the 'content' field.\") }}\n {%- endif %}\n {%- endif %}\n {%- if \"thinking\" in message %}\n {%- if \"<|channel|>analysis<|message|>\" in message.thinking or \"<|channel|>final<|message|>\" in message.thinking %}\n {{- raise_exception(\"You have passed a message containing <|channel|> tags in the thinking field. Instead of doing this, you should pass analysis messages (the string between '<|message|>' and '<|end|>') in the 'thinking' field, and final messages (the string between '<|message|>' and '<|end|>') in the 'content' field.\") }}\n {%- endif %}\n {%- endif %}\n {%- if \"tool_calls\" in message %}\n {#- We need very careful handling here - we want to drop the tool call analysis message if the model #}\n {#- has output a later <|final|> message, but otherwise we want to retain it. This is the only case #}\n {#- when we render CoT/analysis messages in inference. #}\n {%- set future_final_message = namespace(found=false) %}\n {%- for future_message in loop_messages[loop.index:] %}\n {%- if future_message.role == 'assistant' and \"tool_calls\" not in future_message %}\n {%- set future_final_message.found = true %}\n {%- endif %}\n {%- endfor %}\n {#- We assume max 1 tool call per message, and so we infer the tool call name #}\n {#- in \"tool\" messages from the most recent assistant tool call name #}\n {%- set tool_call = message.tool_calls[0] %}\n {%- if tool_call.function %}\n {%- set tool_call = tool_call.function %}\n {%- endif %}\n {%- if message.content and message.thinking %}\n {{- raise_exception(\"Cannot pass both content and thinking in an assistant message with tool calls! Put the analysis message in one or the other, but not both.\") }}\n {%- elif message.content and not future_final_message.found %}\n {{- \"<|start|>assistant<|channel|>analysis<|message|>\" + message.content + \"<|end|>\" }}\n {%- elif message.thinking and not future_final_message.found %}\n {{- \"<|start|>assistant<|channel|>analysis<|message|>\" + message.thinking + \"<|end|>\" }}\n {%- endif %}\n {{- \"<|start|>assistant to=\" }}\n {{- \"functions.\" + tool_call.name + \"<|channel|>commentary \" }}\n {{- (tool_call.content_type if tool_call.content_type is defined else \"json\") + \"<|message|>\" }}\n {{- tool_call.arguments|tojson }}\n {{- \"<|call|>\" }}\n {%- set last_tool_call.name = tool_call.name %}\n {%- elif loop.last and not add_generation_prompt %}\n {#- Only render the CoT if the final turn is an assistant turn and add_generation_prompt is false #}\n {#- This is a situation that should only occur in training, never in inference. #}\n {%- if \"thinking\" in message %}\n {{- \"<|start|>assistant<|channel|>analysis<|message|>\" + message.thinking + \"<|end|>\" }}\n {%- endif %}\n {#- <|return|> indicates the end of generation, but <|end|> does not #}\n {#- <|return|> should never be an input to the model, but we include it as the final token #}\n {#- when training, so the model learns to emit it. #}\n {{- \"<|start|>assistant<|channel|>final<|message|>\" + message.content + \"<|return|>\" }}\n {%- else %}\n {#- CoT is dropped during all previous turns, so we never render it for inference #}\n {{- \"<|start|>assistant<|channel|>final<|message|>\" + message.content + \"<|end|>\" }}\n {%- set last_tool_call.name = none %}\n {%- endif %}\n {%- elif message.role == 'tool' -%}\n {%- if last_tool_call.name is none %}\n {{- raise_exception(\"Message has tool role, but there was no previous assistant message with a tool call!\") }}\n {%- endif %}\n {{- \"<|start|>functions.\" + last_tool_call.name }}\n {{- \" to=assistant<|channel|>commentary<|message|>\" + message.content|tojson + \"<|end|>\" }}\n {%- elif message.role == 'user' -%}\n {{- \"<|start|>user<|message|>\" + message.content + \"<|end|>\" }}\n {%- endif -%}\n{%- endfor -%}\n\n{#- Generation prompt #}\n{%- if add_generation_prompt -%}\n<|start|>assistant\n{%- endif -%}",
"templatePath": "chat_template.jinja",
"templateUrl": "https://huggingface.co/openai/gpt-oss-120b/blob/b5c939de8f754692c1647ca79fbf85e8c1e70f8a/chat_template.jinja",
"templateToolLines": [
105,
165
],
"templateHelperSource": null,
"templateHelperPath": null,
"templateHelperUrl": null,
"bosToken": "<|startoftext|>",
"eosToken": "<|return|>",
"padToken": "<|endoftext|>",
"unkToken": "",
"specialTokens": {
"<|startoftext|>": 199998,
"<|endoftext|>": 199999,
"<|reserved_200000|>": 200000,
"<|reserved_200001|>": 200001,
"<|return|>": 200002,
"<|constrain|>": 200003,
"<|reserved_200004|>": 200004,
"<|channel|>": 200005,
"<|start|>": 200006,
"<|end|>": 200007,
"<|message|>": 200008,
"<|reserved_200009|>": 200009,
"<|reserved_200010|>": 200010,
"<|reserved_200011|>": 200011,
"<|call|>": 200012,
"<|reserved_200013|>": 200013,
"<|reserved_200014|>": 200014,
"<|reserved_200015|>": 200015,
"<|reserved_200016|>": 200016,
"<|reserved_200017|>": 200017,
"<|endofprompt|>": 200018
},
"stopTokenCall": "<|call|>",
"stopTokenText": "<|return|>",
"dedicatedStopToken": true,
"stopKind": "dedicated",
"eosNote": "gpt-oss-120b's generation_config lists <|return|> (200002), <|endoftext|> (199999), and <|call|> (200012): <|call|> is a dedicated tool-call stop token, distinct from <|return|> for final user answers.",
"cap": "gpt-oss-120b renders tools inside <code><|start|>developer</code> using a Jinja TypeScript macro (<code>namespace functions</code>). It converts <code>integer</code> to <code>number</code>, drops numeric bounds like <code>minimum</code>/<code>maximum</code>, and collapses arrays of nested objects like <code>contacts</code> to <code>any[]</code>.",
"outCap": "Shown in the Hub/vLLM header order (<code>to=functions.{name}<|channel|>commentary <|constrain|>json</code>), streaming JSON arguments and halting on dedicated <code><|call|></code>; SGLang's detector expects <code><|channel|>commentary</code> before <code>to=functions.{name}</code>.",
"walkSteps": {
"s2": "The Harmony Jinja macro translates each tool into TypeScript inside namespace functions, turning integer into number, dropping minimum/maximum/additionalProperties, and collapsing nested object arrays (customer.contacts) to any[].",
"s3": "The system and developer blocks wrap the declarations with Harmony channel definitions (analysis, commentary, final) and identity metadata.",
"s4": "The rendered prompt ends with <|start|>assistant, leaving the model to emit its own <|channel|>analysis opener.",
"s5": "After analysis<|end|>, the model routes <|start|>assistant to=functions.{name}<|channel|>commentary <|constrain|>json<|message|>{json}.",
"s6": "vLLM's harmony.py accepts both recipient-first (shown here, matching Hub Jinja) and channel-first headers; SGLang's gpt_oss_detector.py uses its own HarmonyParser and expects <|channel|>commentary before to=functions.x<|constrain|>json.",
"s7": "Generation stops on dedicated <|call|> (200012), distinct from <|return|> (200002) for final answers; the serving layer still maps engine 'stop' to API finish_reason='tool_calls' after parsing."
},
"lane": [
"<|channel|>analysis<|message|> … <|end|> reasoning",
"<|start|>assistant to=functions.… routes to tool",
"<|channel|>commentary <|constrain|>json<|message|> header",
"JSON argument object payload",
"<|call|> dedicated call stop; sampler reports stop"
],
"laneText": [
"<|channel|>analysis<|message|> … <|end|> reasoning",
"<|start|>assistant<|channel|>final<|message|> answer text",
"<|return|> ends turn; sampler reports stop"
],
"excerpts": {
"vllm": [
{
"repo": "vllm",
"path": "vllm/parser/harmony.py",
"start": 427,
"end": 454,
"hl": [
427,
433,
434,
438,
439,
440,
441
],
"sha": "ef687f6179b752c028767e610addbda67ed36d03",
"url": "https://github.com/vllm-project/vllm/blob/ef687f6179b752c028767e610addbda67ed36d03/vllm/parser/harmony.py#L427-L454",
"note": "vLLM's harmony.py supports both header orders: recipient-first and channel-first.",
"code": "_JSON_CONSTRAINS = [\" json\", \" <|constrain|>json\"]\n# Harmomy's stop tokens are <|return|>, <|call|>, <|endoftext|>\n# They are represented as \"\" since xgrammar disallows stop tokens while\n# under constraints, leading to bad or infinite generations.\n_END_TAG = [\"<|end|>\", \"\"]\n_FINAL_BEGIN = \"<|channel|>final{constrain}<|message|>\"\n_TOOL_CALL_CHANNELS = [\n \"<|channel|>commentary\",\n \"<|channel|>analysis\",\n \"<|channel|>final\",\n]\n_FUNCTION_CALL_BEGINS = [\n \" to=functions.{name}{channel}{constrain}<|message|>\",\n \"{channel} to=functions.{name}{constrain}<|message|>\",\n]\n_ANY_CONTENT = AnyTextFormat()\n\n\ndef _assemble_tag(\n allow_analysis: bool, allow_commentary: bool, content: Format\n) -> StructuralTag:\n tags = []\n if allow_analysis:\n analysis_tag = OptionalFormat(\n content=SequenceFormat(\n elements=[\n TagFormat(\n begin=\"<|channel|>analysis<|message|>\","
}
],
"sglang": [
{
"repo": "sglang",
"path": "python/sglang/srt/function_call/gpt_oss_detector.py",
"start": 19,
"end": 45,
"hl": [
24,
29,
30,
31,
35
],
"sha": "1918da6349f9be1c62315503e1a7458a3957bc5f",
"url": "https://github.com/sgl-project/sglang/blob/1918da6349f9be1c62315503e1a7458a3957bc5f/python/sglang/srt/function_call/gpt_oss_detector.py#L19-L45",
"note": "SGLang's GptOssDetector uses its own HarmonyParser and expects <|start|>assistant<|channel|>commentary before to=…<|constrain|>json.",
"code": "class GptOssDetector(BaseFormatDetector):\n \"\"\"\n Detector for T4-style function calls using HarmonyParser.\n\n Handles tool calls in the format:\n <|channel|>commentary to={namespace.function}<|constrain|>json<|message|>{args}<|call|>\n \"\"\"\n\n def __init__(self):\n super().__init__()\n self.harmony_parser = HarmonyParser()\n self.bot_token = \"<|start|>assistant<|channel|>commentary\"\n self.eot_token = \"<|call|>\"\n\n # Pattern to extract function name and JSON from tool_call event content\n self.tool_extract_pattern = re.compile(\n r\"to=([a-zA-Z_][a-zA-Z0-9_.-]*)\\s*<\\|constrain\\|>json<\\|message\\|>(.*?)(?:<\\|call\\|>|$)\",\n re.DOTALL,\n )\n\n def has_tool_call(self, text: str) -> bool:\n \"\"\"Check if text contains TypeScript-style function call markers.\"\"\"\n return self.bot_token in text\n\n def detect_and_parse(self, text: str, tools: List[Tool]) -> StreamingParseResult:\n \"\"\"Parse TypeScript-style function calls from complete text.\"\"\"\n if not self.has_tool_call(text):"
}
]
}
},
{
"key": "gemma4",
"id": "google/gemma-4-31B-it",
"label": "gemma-4-31B-it",
"sub": "Custom DSL",
"sha": "842da3794eaa0b77d5f08bae87a17459d91ff475",
"created": "2026-03-11",
"likes": 4448,
"templateKind": "jinja",
"schemaEncoding": "declaration:fn{…} DSL",
"callSyntax": "<|tool_call>call:fn{…}<tool_call|>",
"servingNote": "Gemma 4 avoids JSON quotes inside tool declarations and calls, quoting strings with special token <|\">| (id 52); vLLM (gemma4.py) and SGLang (gemma4_detector.py) parse this DSL directly.",
"chatTemplate": "{#\n Template: Google Gemma 4 Canonical Chat Template\n Author: Google Gemma Engineering Team\n Published: 2026-07-09\n Context: Fixed tool-calling loops, turn closures, and thinking content-ordering.\n#}\n{%- macro format_parameters(properties, required, filter_keys=false) -%}\n {%- set standard_keys = ['description', 'type', 'properties', 'required', 'nullable'] -%}\n {%- set ns = namespace(found_first=false) -%}\n {%- for key, value in properties | dictsort -%}\n {%- set add_comma = false -%}\n {%- if not filter_keys or key not in standard_keys -%}\n {%- if ns.found_first %},{% endif -%}\n {%- set ns.found_first = true -%}\n {{ key }}:{\n {%- if value['description'] -%}\n description:<|\"|>{{ value['description'] }}<|\"|>\n {%- set add_comma = true -%}\n {%- endif -%}\n {%- if value['type'] | upper == 'STRING' -%}\n {%- if value['enum'] -%}\n {%- if add_comma %},{%- else -%} {%- set add_comma = true -%} {% endif -%}\n enum:{{ format_argument(value['enum']) }}\n {%- endif -%}\n {%- elif value['type'] | upper == 'ARRAY' -%}\n {%- if value['items'] is mapping and value['items'] -%}\n {%- if add_comma %},{%- else -%} {%- set add_comma = true -%} {% endif -%}\n items:{\n {%- set ns_items = namespace(found_first=false) -%}\n {%- for item_key, item_value in value['items'] | dictsort -%}\n {%- if item_value is not none -%}\n {%- if ns_items.found_first %},{% endif -%}\n {%- set ns_items.found_first = true -%}\n {%- if item_key == 'properties' -%}\n properties:{\n {%- if item_value is mapping -%}\n {{- format_parameters(item_value, value['items']['required'] | default([])) -}}\n {%- endif -%}\n }\n {%- elif item_key == 'required' -%}\n required:[\n {%- for req_item in item_value -%}\n <|\"|>{{- req_item -}}<|\"|>\n {%- if not loop.last %},{% endif -%}\n {%- endfor -%}\n ]\n {%- elif item_key == 'type' -%}\n {%- if item_value is string -%}\n type:{{ format_argument(item_value | upper) }}\n {%- else -%}\n type:{{ format_argument(item_value | map('upper') | list) }}\n {%- endif -%}\n {%- else -%}\n {{ item_key }}:{{ format_argument(item_value) }}\n {%- endif -%}\n {%- endif -%}\n {%- endfor -%}\n }\n {%- endif -%}\n {%- endif -%}\n {%- if value['nullable'] %}\n {%- if add_comma %},{%- else -%} {%- set add_comma = true -%} {% endif -%}\n nullable:true\n {%- endif -%}\n {%- if value['type'] | upper == 'OBJECT' -%}\n {%- if value['properties'] is defined and value['properties'] is mapping -%}\n {%- if add_comma %},{%- else -%} {%- set add_comma = true -%} {% endif -%}\n properties:{\n {{- format_parameters(value['properties'], value['required'] | default([])) -}}\n }\n {%- elif value is mapping -%}\n {%- if add_comma %},{%- else -%} {%- set add_comma = true -%} {% endif -%}\n properties:{\n {{- format_parameters(value, value['required'] | default([]), filter_keys=true) -}}\n }\n {%- endif -%}\n {%- if value['required'] -%}\n {%- if add_comma %},{%- else -%} {%- set add_comma = true -%} {% endif -%}\n required:[\n {%- for item in value['required'] | default([]) -%}\n <|\"|>{{- item -}}<|\"|>\n {%- if not loop.last %},{% endif -%}\n {%- endfor -%}\n ]\n {%- endif -%}\n {%- endif -%}\n {%- if add_comma %},{%- else -%} {%- set add_comma = true -%} {% endif -%}\n type:<|\"|>{{ value['type'] | upper }}<|\"|>}\n {%- endif -%}\n {%- endfor -%}\n{%- endmacro -%}\n{%- macro format_function_declaration(tool_data) -%}\n declaration:{{- tool_data['function']['name'] -}}{description:<|\"|>{{- tool_data['function']['description'] -}}<|\"|>\n {%- set params = tool_data['function']['parameters'] -%}\n {%- if params -%}\n ,parameters:{\n {%- if params['properties'] -%}\n properties:{ {{- format_parameters(params['properties'], params['required']) -}} },\n {%- endif -%}\n {%- if params['required'] -%}\n required:[\n {%- for item in params['required'] -%}\n <|\"|>{{- item -}}<|\"|>\n {{- ',' if not loop.last -}}\n {%- endfor -%}\n ],\n {%- endif -%}\n {%- if params['type'] -%}\n type:<|\"|>{{- params['type'] | upper -}}<|\"|>}\n {%- endif -%}\n {%- endif -%}\n {%- if 'response' in tool_data['function'] -%}\n {%- set response_declaration = tool_data['function']['response'] -%}\n ,response:{\n {%- if response_declaration['description'] -%}\n description:<|\"|>{{- response_declaration['description'] -}}<|\"|>,\n {%- endif -%}\n {%- if response_declaration['type'] | upper == 'OBJECT' -%}\n type:<|\"|>{{- response_declaration['type'] | upper -}}<|\"|>}\n {%- endif -%}\n {%- endif -%}\n }\n{%- endmacro -%}\n{%- macro format_argument(argument, escape_keys=True) -%}\n {%- if argument is none -%}\n {{- 'null' -}}\n {%- elif argument is string -%}\n {{- '<|\"|>' + argument + '<|\"|>' -}}\n {%- elif argument is boolean -%}\n {{- 'true' if argument else 'false' -}}\n {%- elif argument is mapping -%}\n {{- '{' -}}\n {%- set ns = namespace(found_first=false) -%}\n {%- for key, value in argument | dictsort -%}\n {%- if ns.found_first %},{% endif -%}\n {%- set ns.found_first = true -%}\n {%- if escape_keys -%}\n {{- '<|\"|>' + key + '<|\"|>' -}}\n {%- else -%}\n {{- key -}}\n {%- endif -%}\n :{{- format_argument(value, escape_keys=escape_keys) -}}\n {%- endfor -%}\n {{- '}' -}}\n {%- elif argument is sequence -%}\n {{- '[' -}}\n {%- for item in argument -%}\n {{- format_argument(item, escape_keys=escape_keys) -}}\n {%- if not loop.last %},{% endif -%}\n {%- endfor -%}\n {{- ']' -}}\n {%- else -%}\n {{- argument -}}\n {%- endif -%}\n{%- endmacro -%}\n{%- macro strip_thinking(text) -%}\n {%- set ns = namespace(result='') -%}\n {%- for part in text.split('<channel|>') -%}\n {%- if '<|channel>' in part -%}\n {%- set ns.result = ns.result + part.split('<|channel>')[0] -%}\n {%- else -%}\n {%- set ns.result = ns.result + part -%}\n {%- endif -%}\n {%- endfor -%}\n {{- ns.result | trim -}}\n{%- endmacro -%}\n\n{%- macro format_tool_response_block(tool_name, response) -%}\n {{- '<|tool_response>' -}}\n {%- if response is mapping -%}\n {{- 'response:' + tool_name + '{' -}}\n {%- for key, value in response | dictsort -%}\n {{- key -}}:{{- format_argument(value, escape_keys=False) -}}\n {%- if not loop.last %},{% endif -%}\n {%- endfor -%}\n {{- '}' -}}\n {%- else -%}\n {{- 'response:' + tool_name + '{value:' + format_argument(response, escape_keys=False) + '}' -}}\n {%- endif -%}\n {{- '<tool_response|>' -}}\n{%- endmacro -%}\n\n{#- ===== SETUP ===== -#}\n{%- set ns = namespace(prev_message_type=None, prev_non_tool_role=None) -%}\n{%- set loop_messages = messages -%}\n{%- set enable_thinking = enable_thinking | default(false) -%}\n{%- set preserve_thinking = preserve_thinking | default(false) -%}\n{{- bos_token -}}\n{#- Handle System/Tool Definitions Block -#}\n{%- if enable_thinking or tools or (messages and messages[0]['role'] in ['system', 'developer']) -%}\n {{- '<|turn>system\\n' -}}\n {#- Inject Thinking token at the very top of the FIRST system turn -#}\n {%- if enable_thinking -%}\n {{- '<|think|>\\n' -}}\n {%- set ns.prev_message_type = 'think' -%}\n {%- endif -%}\n {%- if messages and messages[0]['role'] in ['system', 'developer'] -%}\n {%- if messages[0]['content'] is string -%}\n {{- messages[0]['content'] | trim -}}\n {%- elif messages[0]['content'] is sequence -%}\n {%- for item in messages[0]['content'] -%}\n {{- item['text'] | trim + ' '-}}\n {%- endfor -%}\n {%- endif -%}\n {%- set loop_messages = messages[1:] -%}\n {%- endif -%}\n {%- if tools -%}\n {%- for tool in tools %}\n {{- '<|tool>' -}}\n {{- format_function_declaration(tool) | trim -}}\n {{- '<tool|>' -}}\n {%- endfor %}\n {%- set ns.prev_message_type = 'tool' -%}\n {%- endif -%}\n {{- '<turn|>\\n' -}}\n{%- endif %}\n\n{#- Pre-scan: find last user message index for reasoning guard -#}\n{%- set ns_turn = namespace(last_user_idx=-1) -%}\n{%- for i in range(loop_messages | length) -%}\n {%- if loop_messages[i]['role'] == 'user' -%}\n {%- set ns_turn.last_user_idx = i -%}\n {%- endif -%}\n{%- endfor -%}\n\n{#- Loop through messages -#}\n{%- for message in loop_messages -%}\n {%- if message['role'] != 'tool' -%}\n {%- set ns.prev_message_type = None -%}\n {%- set role = 'model' if message['role'] == 'assistant' else message['role'] -%}\n {#- Detect continuation using tracked state — O(1) instead of O(n) backward scan -#}\n {%- set continue_same_model_turn = (role == 'model' and ns.prev_non_tool_role == 'assistant') -%}\n {%- if not continue_same_model_turn -%}\n {{- '<|turn>' + role + '\\n' }}\n\n {%- endif -%}\n\n {#- Render reasoning/reasoning_content as thinking channel -#}\n {%- set thinking_text = message.get('reasoning') or message.get('reasoning_content') -%}\n {%- set thinking_gate = (loop.index0 > ns_turn.last_user_idx) or (preserve_thinking and message.get('tool_calls')) -%}\n {%- if thinking_text and thinking_gate -%}\n {{- '<|channel>thought\\n' + thinking_text + '\\n<channel|>' -}}\n {%- endif -%}\n\n {%- if message.get('tool_calls') -%}\n {%- for tool_call in message.get('tool_calls') -%}\n {%- set function = tool_call['function'] -%}\n {{- '<|tool_call>call:' + function['name'] + '{' -}}\n {%- if function['arguments'] is mapping -%}\n {%- set ns_args = namespace(found_first=false) -%}\n {%- for key, value in function['arguments'] | dictsort -%}\n {%- if ns_args.found_first %},{% endif -%}\n {%- set ns_args.found_first = true -%}\n {{- key -}}:{{- format_argument(value, escape_keys=False) -}}\n {%- endfor -%}\n {%- elif function['arguments'] is none -%}\n {%- else -%}\n {{- raise_exception(\n \"chat_template: tool_calls[].function.arguments must be a \"\n \"JSON object (mapping), not a string. Deserialize arguments \"\n \"before passing to the template.\"\n ) -}}\n {%- endif -%}\n {{- '}<tool_call|>' -}}\n {%- endfor -%}\n {%- set ns.prev_message_type = 'tool_call' -%}\n {%- endif -%}\n\n {%- set ns_tr_out = namespace(flag=false) -%}\n {%- if message.get('tool_responses') -%}\n {#- Legacy: tool_responses embedded on the assistant message (Google/Gemma native) -#}\n {%- for tool_response in message.get('tool_responses') -%}\n {{- format_tool_response_block(tool_response['name'] | default('unknown', true), tool_response['response']) -}}\n {%- set ns_tr_out.flag = true -%}\n {%- set ns.prev_message_type = 'tool_response' -%}\n {%- endfor -%}\n {%- elif message.get('tool_calls') -%}\n {#- OpenAI Chat Completions: forward-scan consecutive role:tool messages -#}\n {%- set ns_tool_scan = namespace(stopped=false) -%}\n {%- for k in range(loop.index0 + 1, loop_messages | length) -%}\n {%- if ns_tool_scan.stopped -%}\n {%- elif loop_messages[k]['role'] != 'tool' -%}\n {%- set ns_tool_scan.stopped = true -%}\n {%- else -%}\n {%- set follow = loop_messages[k] -%}\n {#- Resolve tool_call_id to function name -#}\n {%- set ns_tname = namespace(name=follow.get('name') or 'unknown') -%}\n {%- for tc in message.get('tool_calls') -%}\n {%- if tc.get('id') == follow.get('tool_call_id') -%}\n {%- set ns_tname.name = tc['function']['name'] -%}\n {%- endif -%}\n {%- endfor -%}\n {#- Handle content as string or content-parts array -#}\n {%- set tool_body = follow.get('content') -%}\n {%- if tool_body is string -%}\n {{- format_tool_response_block(ns_tname.name, tool_body) -}}\n {%- elif tool_body is sequence and tool_body is not string -%}\n {%- set ns_txt = namespace(s='') -%}\n {%- for part in tool_body -%}\n {%- if part.get('type') == 'text' -%}\n {%- set ns_txt.s = ns_txt.s + (part.get('text') | default('')) -%}\n {%- endif -%}\n {%- endfor -%}\n {{- format_tool_response_block(ns_tname.name, ns_txt.s) -}}\n {%- for part in tool_body -%}\n {%- if part.get('type') in ['image', 'image_url'] -%}\n {{- '<|image|>' -}}\n {%- elif part.get('type') in ['audio', 'input_audio'] -%}\n {{- '<|audio|>' -}}\n {%- elif part.get('type') == 'video' -%}\n {{- '<|video|>' -}}\n {%- endif -%}\n {%- endfor -%}\n {%- else -%}\n {{- format_tool_response_block(ns_tname.name, tool_body) -}}\n {%- endif -%}\n {%- set ns_tr_out.flag = true -%}\n {%- set ns.prev_message_type = 'tool_response' -%}\n {%- endif -%}\n {%- endfor -%}\n {%- endif -%}\n\n {%- set captured_content -%}\n {%- if message.get('content') is string -%}\n {%- if role == 'model' -%}\n {{- strip_thinking(message['content']) -}}\n {%- else -%}\n {{- message['content'] | trim -}}\n {%- endif -%}\n {%- elif message.get('content') is sequence -%}\n {%- for item in message['content'] -%}\n {%- if item.get('type') == 'text' -%}\n {%- if role == 'model' -%}\n {{- strip_thinking(item['text']) -}}\n {%- else -%}\n {{- item['text'] | trim -}}\n {%- endif -%}\n {%- elif item.get('type') in ['image', 'image_url'] -%}\n {{- '<|image|>' -}}\n {%- elif item.get('type') in ['audio', 'input_audio'] -%}\n {{- '<|audio|>' -}}\n {%- elif item.get('type') == 'video' -%}\n {{- '<|video|>' -}}\n {%- endif -%}\n {%- endfor -%}\n {%- endif -%}\n {%- endset -%}\n\n {{- captured_content -}}\n {%- set has_content = captured_content | trim | length > 0 -%}\n\n {#- Forward-scan: find next non-tool message role for continuation detection -#}\n {%- set next_nt = namespace(role=None, found=false) -%}\n {%- for j in range(loop.index0 + 1, loop_messages | length) -%}\n {%- if not next_nt.found -%}\n {%- if loop_messages[j]['role'] != 'tool' -%}\n {%- set next_nt.role = loop_messages[j]['role'] -%}\n {%- set next_nt.found = true -%}\n {%- endif -%}\n {%- endif -%}\n {%- endfor -%}\n\n {%- set continues_into_next = (\n role == 'model'\n and next_nt.role == 'assistant'\n and (not message.get('tool_calls') or ns_tr_out.flag)\n ) -%}\n\n {%- if ns.prev_message_type == 'tool_call' and not ns_tr_out.flag -%}\n {{- '<|tool_response>' -}}\n {%- elif continues_into_next -%}\n {%- elif not (ns_tr_out.flag and not has_content and not next_nt.found) -%}\n {{- '<turn|>\\n' -}}\n {%- endif -%}\n\n {#- Track previous non-tool role for next iteration (avoids O(n) backward scan) -#}\n {%- set ns.prev_non_tool_role = message['role'] -%}\n {%- endif -%}\n{%- endfor -%}\n\n{%- if add_generation_prompt -%}\n {%- if ns.prev_message_type != 'tool_response' and ns.prev_message_type != 'tool_call' -%}\n {{- '<|turn>model\\n' -}}\n {%- if not enable_thinking -%}\n {{- '<|channel>thought\\n<channel|>' -}}\n {%- endif -%}\n {%- elif ns.prev_message_type == 'tool_response' and enable_thinking -%}\n {{- '<|channel>thought\\n' -}}\n {%- endif -%}\n{%- endif -%}\n",
"templatePath": "chat_template.jinja",
"templateUrl": "https://huggingface.co/google/gemma-4-31B-it/blob/842da3794eaa0b77d5f08bae87a17459d91ff475/chat_template.jinja",
"templateToolLines": [
85,
120
],
"templateHelperSource": null,
"templateHelperPath": null,
"templateHelperUrl": null,
"bosToken": "<bos>",
"eosToken": "<eos>",
"padToken": "<pad>",
"unkToken": "<unk>",
"specialTokens": {
"<pad>": 0,
"<eos>": 1,
"<bos>": 2,
"<unk>": 3,
"<mask>": 4,
"<|tool>": 46,
"<tool|>": 47,
"<|tool_call>": 48,
"<tool_call|>": 49,
"<|tool_response>": 50,
"<tool_response|>": 51,
"<|\"|>": 52,
"<|think|>": 98,
"<|channel>": 100,
"<channel|>": 101,
"<|turn>": 105,
"<turn|>": 106,
"<|image>": 255999,
"<|audio>": 256000,
"<|image|>": 258880,
"<|audio|>": 258881,
"<image|>": 258882,
"<audio|>": 258883,
"<|video|>": 258884
},
"stopTokenCall": "<|tool_response>",
"stopTokenText": "<turn|>",
"dedicatedStopToken": true,
"stopKind": "role-boundary",
"eosNote": "Gemma 4's generation_config lists EOS IDs [1, 106, 50] (<eos>, <turn|>, <|tool_response>). After <tool_call|> (49), Gemma hands off to the tool runtime on <|tool_response> (50), whereas a plain answer closes with <turn|> (106).",
"cap": "Gemma 4 rewrites JSON Schema into an unquoted-key DSL (<code>declaration:name{description:<|\"|>...<|\"|>,parameters:{...}}</code>) inside <code><|tool>...<tool|></code>. Types are uppercased (<code>STRING</code>, <code>INTEGER</code>) and keywords like <code>minimum</code>, <code>maximum</code>, and <code>default</code> are dropped.",
"outCap": "Gemma 4 emits <code><|tool_call>call:name{key:<|\"|>val<|\"|>,num:3}<tool_call|></code> using token 52 (<code><|\"|></code>) for strings, then hands off on <code><|tool_response></code> (id 50).",
"walkSteps": {
"s2": "chat_template.jinja compiles each tool into <|tool>declaration:name{…}<tool|>, quoting strings with <|\"|> (52), uppercasing types (STRING/INTEGER/OBJECT), and dropping numeric bounds and defaults.",
"s3": "Each tool sits directly inside <|turn>system with no verbose calling prose or multi-line examples.",
"s4": "The default non-thinking prompt ends with <|turn>model\\n<|channel>thought\\n<channel|>, already closing an empty thought block before generation begins.",
"s5": "The model emits <|tool_call>call:name{…}<tool_call|> with sorted unquoted keys and <|\"|> string delimiters.",
"s6": "vLLM's Gemma4 parser and SGLang's Gemma4Detector (skip_special_tokens=False) parse the DSL and <|\"|> strings into JSON arguments.",
"s7": "After <tool_call|>, Gemma hands off on <|tool_response> (50) — an EOS boundary distinct from <turn|> (106) on plain replies — and parsed calls map engine 'stop' to API finish_reason='tool_calls'."
},
"lane": [
"<|tool_call> opens DSL tool call",
"call:…{ names the target tool",
"Unquoted keys with <|\"|> string delimiters",
"} and <tool_call|> close tool call",
"<|tool_response> hands off to runtime; sampler reports stop"
],
"laneText": [
"Plain assistant answer text",
"<turn|> closes model turn; sampler reports stop"
],
"excerpts": {
"vllm": [
{
"repo": "vllm",
"path": "vllm/parser/gemma4.py",
"start": 39,
"end": 60,
"hl": [
39,
40,
41,
42,
43
],
"sha": "ef687f6179b752c028767e610addbda67ed36d03",
"url": "https://github.com/vllm-project/vllm/blob/ef687f6179b752c028767e610addbda67ed36d03/vllm/parser/gemma4.py#L39-L60",
"note": "vLLM's Gemma4 parser defines <|channel>, <|tool_call>, <tool_call|>, and the <|\"|> string delimiter.",
"code": "CHANNEL_START = \"<|channel>\"\nCHANNEL_END = \"<channel|>\"\nTOOL_CALL_START = \"<|tool_call>\"\nTOOL_CALL_END = \"<tool_call|>\"\nSTRING_DELIM = '<|\"|>'\n_DELIM_LEN = len(STRING_DELIM)\n\nlogger = init_logger(__name__)\n\n\n# ---------------------------------------------------------------------------\n# Gemma4 argument parser\n# ---------------------------------------------------------------------------\n\n_PARTIAL_DELIM_SUFFIXES = tuple(\n STRING_DELIM[:k] for k in range(len(STRING_DELIM), 0, -1)\n)\n\n\ndef _strip_partial_delim(value: str) -> str:\n \"\"\"Strip a trailing partial `STRING_DELIM` prefix from *value*.\n"
}
],
"sglang": [
{
"repo": "sglang",
"path": "python/sglang/srt/function_call/gemma4_detector.py",
"start": 15,
"end": 42,
"hl": [
16,
17,
18,
28,
34,
37
],
"sha": "1918da6349f9be1c62315503e1a7458a3957bc5f",
"url": "https://github.com/sgl-project/sglang/blob/1918da6349f9be1c62315503e1a7458a3957bc5f/python/sglang/srt/function_call/gemma4_detector.py#L15-L42",
"note": "SGLang's Gemma4Detector parses Gemma4's custom key:value syntax and converts booleans, numbers, and <|\"|> strings.",
"code": "# Gemma4 special tokens for tool calls\nTOOL_CALL_START = \"<|tool_call>\"\nTOOL_CALL_END = \"<tool_call|>\"\nSTRING_DELIM = '<|\"|>'\n\n\ndef _parse_gemma4_value(value_str: str) -> object:\n \"\"\"Parse a single Gemma4 value (after key:) into a Python object.\"\"\"\n value_str = value_str.strip()\n if not value_str:\n return value_str\n\n # Boolean\n if value_str == \"true\":\n return True\n if value_str == \"false\":\n return False\n\n # Number (int or float)\n try:\n if \".\" in value_str:\n return float(value_str)\n return int(value_str)\n except ValueError:\n pass\n\n # Bare string (no <|\"|> delimiters)\n return value_str"
}
]
}
},
{
"key": "mistral4",
"id": "mistralai/Mistral-Large-4-1T-A52B",
"label": "Mistral-Large-4",
"sub": "Bracket tokens",
"sha": "af26e7869af601441d5cdf75a1272469ddc3d059",
"created": "2026-09-30",
"likes": 1679,
"templateKind": "jinja",
"schemaEncoding": "Compact JSON in [AVAILABLE_TOOLS]",
"callSyntax": "[TOOL_CALLS]fn[ARGS]{…}",
"servingNote": "vLLM supports both mistral-common (vllm/renderers/mistral.py) and HF chat_template.jinja; Mistral Large 4 uses [TOOL_CALLS]name[ARGS]{json} instead of Mistral v3's JSON array.",
"chatTemplate": "{#- Default system message if no system prompt is passed. #}\n{%- set default_system_message = '' %}\n\n{#- Begin of sequence token. #}\n{{- bos_token }}\n\n\n{#- Handle system prompt if it exists. #}\n{%- set loop_messages = messages %}\n{%- if messages[0]['role'] != 'system' and default_system_message != '' %}\n {{- '[SYSTEM_PROMPT]' ~ default_system_message ~ '[/SYSTEM_PROMPT]' }}\n{%- endif %}\n\n\n{#- Tools and model settings definition #}\n{%- set available_tools = '' %}\n{%- set has_tools = false %}\n{%- if tools is defined and tools is not none and tools|length > 0 %}\n {%- set has_tools = true %}\n {%- set available_tools = '[AVAILABLE_TOOLS]' ~ (tools| tojson) ~ '[/AVAILABLE_TOOLS]' %}\n{%- endif %}\n{%- set json_schema = none %}\n{%- if response_format is defined and response_format is not none %}\n {%- set response_format_type = response_format.get('type', 'text') %}\n {%- set response_json_schema = response_format.get('json_schema') %}\n {%- if response_format_type not in ['text', 'json_object', 'json_schema'] %}\n {{- raise_exception('Response format type must be one of text, json_object or json_schema, got ' ~ response_format_type ~ '.') }}\n {%- elif response_format_type == 'json_schema' %}\n {%- if response_json_schema is none or response_json_schema.get('schema') is none %}\n {{- raise_exception('Response format `json_schema` must define the schema') }}\n {%- else %}\n {%- set json_schema = response_json_schema['schema'] %}\n {%- endif %}\n {%- elif response_format_type == 'json_object' %}\n {%- set json_schema = {'anyOf': [{'type': 'object'}, {'type': 'array'}]} %}\n {%- endif %}\n{%- endif %}\n{%- if reasoning_effort is not defined or reasoning_effort is none %}\n {%- set reasoning_effort = 'high' %}\n{%- endif %}\n{%- if reasoning_effort not in ['low', 'medium', 'high'] %}\n {{- raise_exception('reasoning_effort must be one of \"low\", \"medium\", \"high\"') }}\n{%- endif %}\n{%- set model_settings_parts = [] %}\n{%- if json_schema is not none %}\n {%- set model_settings_parts = model_settings_parts + ['\"json_schema\": ' ~ (json_schema|tojson)] %}\n{%- endif %}\n{%- set model_settings_parts = model_settings_parts + ['\"reasoning_effort\": \"' ~ reasoning_effort ~ '\"'] %}\n{%- set model_settings = '' %}\n{%- if model_settings_parts %}\n {%- set model_settings = '[MODEL_SETTINGS]{' ~ model_settings_parts|join(', ') ~ '}[/MODEL_SETTINGS]' %}\n{%- endif %}\n\n{#- Macros #}\n{%- macro render_content(content, context_name, supported_types_desc, support_thinking, support_images) -%}\n {%- if content is string -%}\n {{- content -}}\n {%- elif content -%}\n {%- for block in content -%}\n {%- if block['type'] == 'text' -%}\n {{- block['text'] -}}\n {%- elif support_thinking and block['type'] == 'thinking' -%}\n {{- '[THINK]' ~ block['thinking'] -}}\n {%- if block.get('closed', true) -%}{{- '[/THINK]' -}}{%- endif -%}\n {%- elif support_images and block['type'] in ['image', 'image_url'] -%}\n {{- '[IMG]' -}}\n {%- else -%}\n {{- raise_exception('Only ' ~ supported_types_desc ~ ' chunks are supported in ' ~ context_name ~ '.') -}}\n {%- endif -%}\n {%- endfor -%}\n {%- else -%}\n {{- raise_exception(context_name ~ ' must have non-empty content.') -}}\n {%- endif -%}\n{%- endmacro -%}\n\n{#- Aggregate consecutive messages with the same role except system and tool. #}\n{#- A sentinel message is appended so the last group gets flushed inside the loop. #}\n{%- set ns_agg = namespace(messages=[], current_group=[], current_role=none) %}\n{%- for message in loop_messages + [{'role': '__sentinel__'}] %}\n {%- if message['role'] != ns_agg.current_role or message['role'] == 'system' or message['role'] == 'tool' %}\n {%- if ns_agg.current_role == 'tool' %}\n {%- set ns_agg.messages = ns_agg.messages + ns_agg.current_group %}\n {%- elif ns_agg.current_role is not none %}\n {%- set ns_c = namespace(text_parts=[], chunks=[], has_non_text=false, tool_calls=[]) %}\n {%- for msg in ns_agg.current_group %}\n {#- Convert reasoning / reasoning_content to a leading thinking chunk. #}\n {%- set reasoning = msg.get('reasoning_content', msg.get('reasoning', none)) %}\n {%- if reasoning is not none and reasoning != '' %}\n {%- if msg['content'] is not none and msg['content'] is not string %}\n {%- for block in msg['content'] %}\n {%- if block['type'] == 'thinking' %}\n {{- raise_exception('Message cannot have both thinking chunks in content and a top-level `reasoning` or `reasoning_content` field.') }}\n {%- endif %}\n {%- endfor %}\n {%- endif %}\n {%- set think_chunk = {'type': 'thinking', 'thinking': reasoning} %}\n {%- if msg['content'] is string and msg['content'] != '' %}\n {%- set new_content = [think_chunk, {'type': 'text', 'text': msg['content']}] %}\n {%- elif msg['content'] is not none and msg['content'] is not string and msg['content'] | length > 0 %}\n {%- set new_content = [think_chunk] + msg['content'] | list %}\n {%- else %}\n {%- set new_content = [think_chunk] %}\n {%- endif %}\n {%- if msg['tool_calls'] is defined and msg['tool_calls'] is not none %}\n {%- set msg = {'role': msg['role'], 'content': new_content, 'tool_calls': msg['tool_calls']} %}\n {%- else %}\n {%- set msg = {'role': msg['role'], 'content': new_content} %}\n {%- endif %}\n {%- endif %}\n {%- if msg['content'] is string %}\n {%- set ns_c.text_parts = ns_c.text_parts + [msg['content']] %}\n {%- elif msg['content'] is not none %}\n {%- set ns_msg = namespace(msg_text_parts=[]) %}\n {%- for block in msg['content'] %}\n {%- if block['type'] == 'text' %}\n {%- set ns_msg.msg_text_parts = ns_msg.msg_text_parts + [block['text']] %}\n {%- else %}\n {%- if ns_msg.msg_text_parts | length > 0 %}\n {%- set ns_c.text_parts = ns_c.text_parts + [ns_msg.msg_text_parts | join('')] %}\n {%- set ns_msg.msg_text_parts = [] %}\n {%- endif %}\n {%- if ns_c.text_parts | length > 0 %}\n {%- set ns_c.chunks = ns_c.chunks + [{'type': 'text', 'text': ns_c.text_parts | join('\\n\\n')}] %}\n {%- set ns_c.text_parts = [] %}\n {%- endif %}\n {%- set ns_c.chunks = ns_c.chunks + [block] %}\n {%- set ns_c.has_non_text = true %}\n {%- endif %}\n {%- endfor %}\n {%- if ns_msg.msg_text_parts | length > 0 %}\n {%- set ns_c.text_parts = ns_c.text_parts + [ns_msg.msg_text_parts | join('')] %}\n {%- endif %}\n {%- endif %}\n {%- if msg['tool_calls'] is defined and msg['tool_calls'] is not none %}\n {%- set ns_c.tool_calls = ns_c.tool_calls + msg['tool_calls'] | list %}\n {%- endif %}\n {%- endfor %}\n {%- if ns_c.has_non_text %}\n {%- if ns_c.text_parts | length > 0 %}\n {%- set ns_c.chunks = ns_c.chunks + [{'type': 'text', 'text': ns_c.text_parts | join('\\n\\n')}] %}\n {%- endif %}\n {%- set merged_content = ns_c.chunks %}\n {%- else %}\n {%- set merged_content = ns_c.text_parts | join('\\n\\n') %}\n {%- endif %}\n {%- if ns_c.tool_calls | length > 0 %}\n {%- set ns_agg.messages = ns_agg.messages + [{'role': ns_agg.current_role, 'content': merged_content, 'tool_calls': ns_c.tool_calls}] %}\n {%- else %}\n {%- set ns_agg.messages = ns_agg.messages + [{'role': ns_agg.current_role, 'content': merged_content}] %}\n {%- endif %}\n {%- endif %}\n {%- if message['role'] != '__sentinel__' %}\n {%- set ns_agg.current_group = [message] %}\n {%- set ns_agg.current_role = message['role'] %}\n {%- endif %}\n {%- else %}\n {%- set ns_agg.current_group = ns_agg.current_group + [message] %}\n {%- endif %}\n{%- endfor %}\n{%- set loop_messages = ns_agg.messages %}\n\n{#- Validates message ordering. #}\n{%- set ns = namespace(available_tools_and_settings_emitted=false) %}\n{%- if loop_messages | length > 0 and loop_messages[0]['role'] not in ['user', 'system'] %}\n {{- raise_exception('Conversation must start with a user or system message, got ' ~ loop_messages[0]['role'] ~ '.') }}\n{%- endif %}\n{%- set ns_order = namespace(previous_role=none) %}\n{%- for message in loop_messages %}\n {%- set current_role = message['role'] %}\n {%- if ns_order.previous_role is not none %}\n {%- if ns_order.previous_role == 'system' %}\n {%- if current_role not in ['user', 'assistant', 'system'] %}\n {{- raise_exception('Unexpected role \\'' ~ current_role ~ '\\' after role \\'' ~ ns_order.previous_role ~ '\\'') }}\n {%- endif %}\n {%- elif ns_order.previous_role == 'user' %}\n {%- if current_role not in ['assistant', 'system', 'user'] %}\n {{- raise_exception('Unexpected role \\'' ~ current_role ~ '\\' after role \\'' ~ ns_order.previous_role ~ '\\'') }}\n {%- endif %}\n {%- elif ns_order.previous_role == 'assistant' %}\n {%- if current_role not in ['assistant', 'user', 'tool'] %}\n {{- raise_exception('Unexpected role \\'' ~ current_role ~ '\\' after role \\'' ~ ns_order.previous_role ~ '\\'') }}\n {%- endif %}\n {%- elif ns_order.previous_role == 'tool' %}\n {%- if current_role not in ['assistant', 'tool', 'user'] %}\n {{- raise_exception('Unexpected role \\'' ~ current_role ~ '\\' after role \\'' ~ ns_order.previous_role ~ '\\'') }}\n {%- endif %}\n {%- endif %}\n {%- endif %}\n {%- set ns_order.previous_role = current_role %}\n{%- endfor %}\n\n{#- Handle conversation messages. #}\n{%- for message in loop_messages %}\n {#- User messages supports text, image and image_url content. #}\n {%- if message['role'] == 'user' %}\n {%- if not ns.available_tools_and_settings_emitted %}\n {{- available_tools }}\n {{- model_settings }}\n {%- set ns.available_tools_and_settings_emitted = true %}\n {%- endif %}\n {%- if message['content'] is not string and message['content'] %}\n {#- When content has exactly one image and one text block, put image first. #}\n {%- if message['content'] | length == 2 and message['content'][0]['type'] == 'text' and message['content'][1]['type'] in ['image', 'image_url'] %}\n {%- set blocks = [message['content'][1], message['content'][0]] %}\n {%- else %}\n {%- set blocks = message['content'] %}\n {%- endif %}\n {%- set user_content = blocks %}\n {%- else %}\n {%- set user_content = message['content'] %}\n {%- endif %}\n {{- '[INST]' -}}\n {{- render_content(content=user_content, context_name='user message content', supported_types_desc='text, image and image_url', support_thinking=false, support_images=true) -}}\n {{- '[/INST]' }}\n\n {#- Assistant messages supports text and thinking content. #}\n {%- elif message['role'] == 'assistant' %}\n {%- if (message['content'] is none or message['content'] == '' or message['content']|length == 0) and (message['tool_calls'] is not defined or message['tool_calls'] is none or message['tool_calls']|length == 0) %}\n {{- raise_exception('Assistant message must have a string or a list of chunks in content or a list of tool calls.') }}\n {%- endif %}\n\n {%- if message['content'] %}\n {{- render_content(content=message['content'], context_name='assistant message contents', supported_types_desc='text and thinking', support_thinking=true, support_images=false) -}}\n {%- endif %}\n\n {%- if message['tool_calls'] is defined and message['tool_calls'] is not none and message['tool_calls']|length > 0 %}\n {%- for tool in message['tool_calls'] %}\n {{- '[TOOL_CALLS]' }}\n {%- set name = tool['function']['name'] %}\n {%- set arguments = tool['function']['arguments'] %}\n {%- if arguments is not string %}\n {%- set arguments = arguments|tojson|safe %}\n {%- elif arguments == '' %}\n {%- set arguments = '{}' %}\n {%- endif %}\n {{- name ~ '[ARGS]' ~ arguments }}\n {%- endfor %}\n {%- endif %}\n\n {{- eos_token }}\n\n {#- Tool messages (multimodal). #}\n {%- elif message['role'] == 'tool' %}\n {{- '[TOOL_RESULTS]' -}}\n {{- render_content(content=message['content'], context_name='tool message contents', supported_types_desc='text and image', support_thinking=false, support_images=true) -}}\n {{- '[/TOOL_RESULTS]' }}\n\n {#- System messages. #}\n {%- elif message['role'] == 'system' %}\n {{- '[SYSTEM_PROMPT]' -}}\n {{- render_content(content=message['content'], context_name='system message contents', supported_types_desc='text', support_thinking=false, support_images=false) -}}\n {{- '[/SYSTEM_PROMPT]' -}}\n\n {#- Raise exception for unsupported roles. #}\n {%- else %}\n {{- raise_exception('Only user, assistant, system and tool roles are supported, got ' ~ message['role'] ~ '.') }}\n {%- endif %}\n{%- endfor %}\n",
"templatePath": "chat_template.jinja",
"templateUrl": "https://huggingface.co/mistralai/Mistral-Large-4-1T-A52B/blob/af26e7869af601441d5cdf75a1272469ddc3d059/chat_template.jinja",
"templateToolLines": [
18,
26
],
"templateHelperSource": null,
"templateHelperPath": null,
"templateHelperUrl": null,
"bosToken": "<s>",
"eosToken": "</s>",
"padToken": "<pad>",
"unkToken": "<unk>",
"specialTokens": {
"<unk>": 0,
"<s>": 1,
"</s>": 2,
"[INST]": 3,
"[/INST]": 4,
"[AVAILABLE_TOOLS]": 5,
"[/AVAILABLE_TOOLS]": 6,
"[TOOL_RESULTS]": 7,
"[/TOOL_RESULTS]": 8,
"[TOOL_CALLS]": 9,
"[IMG]": 10,
"<pad>": 11,
"[IMG_BREAK]": 12,
"[IMG_END]": 13,
"[PREFIX]": 14,
"[MIDDLE]": 15,
"[SUFFIX]": 16,
"[SYSTEM_PROMPT]": 17,
"[/SYSTEM_PROMPT]": 18,
"[TOOL_CONTENT]": 19,
"[AUDIO]": 24,
"[BEGIN_AUDIO]": 25,
"[ARGS]": 32,
"[CALL_ID]": 33,
"[THINK]": 34,
"[/THINK]": 35,
"[MODEL_SETTINGS]": 36,
"[/MODEL_SETTINGS]": 37
},
"stopTokenCall": "</s>",
"stopTokenText": "</s>",
"dedicatedStopToken": false,
"stopKind": "shared",
"eosNote": "Mistral Large 4's generation_config sets EOS to </s> (id 2), shared by both [TOOL_CALLS] turns and normal text replies.",
"cap": "Mistral Large 4 serializes the OpenAI tool array as compact JSON via <code>tools | tojson</code> inside <code>[AVAILABLE_TOOLS]...[/AVAILABLE_TOOLS]</code> (tokens 5 and 6) with zero extra system prose. Every schema field and constraint arrives intact.",
"outCap": "Mistral Large 4 emits <code>[TOOL_CALLS]</code> (id 9), the bare function name, <code>[ARGS]</code> (id 36), and a compact JSON object before stopping on shared <code></s></code>.",
"walkSteps": {
"s2": "chat_template.jinja serializes the OpenAI tools array as compact JSON via tools | tojson inside [AVAILABLE_TOOLS]…[/AVAILABLE_TOOLS], preserving every nested object and constraint.",
"s3": "The template adds zero calling instructions or examples around [AVAILABLE_TOOLS].",
"s4": "There is no assistant prefix: the prompt stops directly after [/INST], and the model emits [THINK] or [TOOL_CALLS] itself.",
"s5": "After [THINK]…[/THINK], the model emits special token [TOOL_CALLS], the bare tool name, [ARGS], and a compact JSON object.",
"s6": "vLLM's Mistral parser and SGLang's MistralDetector (keeping special tokens) match [TOOL_CALLS] and [ARGS] to extract the tool name and JSON arguments.",
"s7": "Generation stops on shared </s> (id 2); on an ordinary completed auto-tool turn with parsed calls, the serving layer rewrites engine 'stop' to API finish_reason='tool_calls'."
},
"lane": [
"[THINK] … [/THINK] reasoning block",
"[TOOL_CALLS] opens tool-call section",
"Bare function name follows [TOOL_CALLS]",
"[ARGS] separates tool name from payload",
"Compact JSON argument object",
"</s> ends turn; sampler reports stop"
],
"laneText": [
"[THINK] … [/THINK] reasoning block",
"Plain assistant answer text",
"</s> ends turn; sampler reports stop"
],
"excerpts": {
"vllm": [
{
"repo": "vllm",
"path": "vllm/parser/mistral.py",
"start": 56,
"end": 70,
"hl": [
61,
62
],
"sha": "ef687f6179b752c028767e610addbda67ed36d03",
"url": "https://github.com/vllm-project/vllm/blob/ef687f6179b752c028767e610addbda67ed36d03/vllm/parser/mistral.py#L56-L70",
"note": "vLLM's Mistral parser reads [TOOL_CALLS] and [ARGS] special token boundaries directly.",
"code": "logger = init_logger(__name__)\n\n_ALPHANUMERIC = ascii_letters + digits\n\n# Special token strings as emitted/decoded by MistralTokenizer.\n_TOOL_CALLS = SpecialTokens.tool_calls.value\n_ARGS = SpecialTokens.args.value\n_THINK_START_SPECIAL = SpecialTokens.begin_think.value\n_THINK_END_SPECIAL = SpecialTokens.end_think.value\n\n# Plain-text reasoning markers used by v11 tokenizers.\n_THINK_START_TEXT = \"<think>\"\n_THINK_END_TEXT = \"</think>\"\n\n_OPEN_BRACE = \"{\""
}
],
"sglang": [
{
"repo": "sglang",
"path": "python/sglang/srt/function_call/mistral_detector.py",
"start": 34,
"end": 58,
"hl": [
38,
40,
46
],
"sha": "1918da6349f9be1c62315503e1a7458a3957bc5f",
"url": "https://github.com/sgl-project/sglang/blob/1918da6349f9be1c62315503e1a7458a3957bc5f/python/sglang/srt/function_call/mistral_detector.py#L34-L58",
"note": "SGLang's MistralDetector checks for the common [TOOL_CALLS prefix before dispatching to array or compact parsing.",
"code": " def __init__(self):\n \"\"\"Initialize tokens and streaming state.\"\"\"\n super().__init__()\n # Canonical Mistral prefix for JSON-array tool calls.\n self.bot_token = \"[TOOL_CALLS] [\"\n # Common marker shared by both JSON-array and compact formats.\n self._tool_calls_marker = \"[TOOL_CALLS\"\n self.eot_token = \"]\"\n self.tool_call_separator = \", \"\n\n def has_tool_call(self, text: str) -> bool:\n \"\"\"Return True if the text contains either supported tool-call marker.\"\"\"\n return self._tool_calls_marker in text\n\n def detect_and_parse(self, text: str, tools: List[Tool]) -> StreamingParseResult:\n \"\"\"\n One-time parsing: Detects and parses tool calls in the provided text.\n\n :param text: The complete text to parse.\n :param tools: List of available tools.\n :return: ParseResult indicating success or failure, consumed text, leftover text, and parsed calls.\n \"\"\"\n marker_idx = text.find(self._tool_calls_marker)\n if marker_idx == -1:\n return StreamingParseResult(normal_text=text, calls=[])"
}
]
}
},
{
"key": "minimax31",
"id": "MiniMaxAI/MiniMax-M3.1-Flash",
"label": "MiniMax-M3.1-Flash",
"sub": "Recursive namespaced XML",
"sha": "ce7f4df87d2e05262f5775f373dac4772f134041",
"created": "2026-10-17",
"likes": 613,
"templateKind": "jinja",
"schemaEncoding": "JSON per <tool> in <tools>",
"callSyntax": "]<]minimax[>[<invoke …>",
"servingNote": "MiniMax-M3.1 prefixes structural call XML tags with the special token ]<]minimax[>[ (id 200059); both vLLM (minimax_m3.py) and SGLang (minimax_m3.py) parse recursive namespaced elements.",
"chatTemplate": "{# ---------- special token variables ---------- #}\n{%- set ns_token = ']<]minimax[>[' -%}\n{%- set bod_token = ']~!b[' -%}\n{%- set bos_token = ']~b]' -%}\n{%- set eos_token = '[e~[' -%}\n{%- set toolcall_begin_token = ns_token ~ '<tool_call>' -%}\n{%- set toolcall_end_token = ns_token ~ '</tool_call>' -%}\n{%- set think_begin_token = '<mm:think>' -%}\n{%- set think_end_token = '</mm:think>' -%}\n{%- set image_token = ']<]image[>[' -%}\n{%- set video_token = ']<]video[>[' -%}\n{#- Recursive XML renderer for tool_call arguments ======================== -#}\n{#- None values are intentionally skipped in mapping iteration so that\n `<key>null</key>` (which would round-trip to the literal string \"null\")\n never appears in the rendered tool_call. The convention is: omit the\n field entirely. The top-level `_args` loop applies the same rule.\n The `val is none` branch below is a safety net only — upstream cleaning\n (drop_none_in_tool_arguments) should ensure no None ever reaches here. -#}\n{%- macro to_xml(val, ns) -%}\n{%- if val is mapping -%}\n{%- for k, v in val.items() if v is not none -%}\n{{ ns }}<{{ k }}>{{ to_xml(v, ns) }}{{ ns }}</{{ k }}>\n{%- endfor -%}\n{%- elif val is iterable and val is not string -%}\n{%- for item in val -%}\n{{ ns }}<item>{{ to_xml(item, ns) }}{{ ns }}</item>\n{%- endfor -%}\n{%- elif val is none -%}\n{#- Should be unreachable when upstream cleaning is applied. -#}\n{%- elif val is boolean -%}\n{{ val | tojson }}\n{%- else -%}\n{{ val }}\n{%- endif -%}\n{%- endmacro -%}\n{#- Tool Rendering Functions ============================================== -#}\n{%- macro render_tool_namespace(namespace_name, tool_list) -%}\n{%- for tool in tool_list -%}\n<tool>{{ tool.function | tojson(ensure_ascii=False) }}</tool>\n{% endfor -%}\n{%- endmacro -%}\n{%- macro visible_text(content) -%}\n {%- if content is string -%}\n {{ content }}\n {%- elif content is iterable and content is not mapping -%}\n {%- for item in content -%}\n {%- if item is mapping and item.type == 'text' -%}\n {{- item.text }}\n {%- elif item is mapping and item.type == 'image' -%}\n {{- image_token }}\n {%- elif item is mapping and item.type == 'video' -%}\n {{- video_token }}\n {%- elif item is string -%}\n {{- item }}\n {%- endif -%}\n {%- endfor -%}\n {%- elif content is none -%}\n {{- '' }}\n {%- else -%}\n {{- content }}\n {%- endif -%}\n{%- endmacro -%}\n{#- System Message Construction ============================================ -#}\n{%- macro build_system_message(system_message) -%}\n {%- if system_message and system_message.content -%}\n {{- visible_text(system_message.content) }}\n {#- Handle current_date -#}\n {%- if system_message.current_date -%}\n {{- '\\n' ~ 'Current date: ' + system_message.current_date }}\n {%- endif -%}\n {#- Handle current_location -#}\n {%- if system_message.current_location -%}\n {{- '\\n' ~ 'Current location: ' + system_message.current_location }}\n {%- endif -%}\n {%- else -%}\n {{- 'Your model version is MiniMax-M3.1, developed by MiniMax. Knowledge cutoff: January 2026. Founded in early 2022, MiniMax is a global AI foundation model company committed to advancing the frontiers of AI towards AGI.' }}\n {%- endif -%}\n\n {#- Thinking mode instructions -#}\n {{- '\\n\\n<thinking_instructions>\\n' }}\n {{- 'You have a thinking capability that allows you to reason step by step before responding. When thinking is enabled, wrap your reasoning in ' ~ think_begin_token ~ think_end_token ~ ' tags before your response. When thinking is disabled, begin your response directly after the ' ~ think_end_token ~ ' prefix. When thinking is adaptive, decide on your own whether to think for the current turn.\\n' }}\n {{- 'Current thinking mode: adaptive. You are encouraged to think for complex decision-making, multi-step reasoning, or when analyzing function/tool results.\\n' }}\n {{- '</thinking_instructions>' }}\n {{- '\\n\\n<model_id>8bb8149fe</model_id>' }}\n {%- if reasoning_effort is defined and reasoning_effort is not none -%}\n {{- '\\n\\n<effort>' ~ reasoning_effort ~ '</effort>' }}\n {%- elif effort is defined and effort is not none -%}\n {{- '\\n\\n<effort>' ~ effort ~ '</effort>' }}\n {%- endif -%}\n{%- endmacro -%}\n{%- macro build_developer_message(developer_message) -%}\n {%- if developer_message and developer_message.content -%}\n {{- visible_text(developer_message.content) }}\n {%- else -%}\n {%- if model_identity is not defined -%}\n {%- set model_identity = \"You are a helpful assistant.\" -%}\n {%- endif -%}\n {{- model_identity }}\n {%- endif -%}\n{%- endmacro -%}\n{#- Main Template Logic ================================================= -#}\n{#- Role mapping: root -> system sp (high priority), system/developer -> developer sp (low priority) -#}\n{%- set system_message = none -%}\n{%- set developer_message = none -%}\n{%- set conversation_messages = messages -%}\n{%- if messages and messages[0].role == \"root\" -%}\n {%- set system_message = messages[0] -%}\n {%- set conversation_messages = messages[1:] -%}\n {%- if conversation_messages and conversation_messages[0].role in [\"system\", \"developer\"] -%}\n {%- set developer_message = conversation_messages[0] -%}\n {%- set conversation_messages = conversation_messages[1:] -%}\n {%- endif -%}\n{%- elif messages and messages[0].role in [\"system\", \"developer\"] -%}\n {%- set developer_message = messages[0] -%}\n {%- set conversation_messages = messages[1:] -%}\n{%- endif -%}\n{#- Render system sp (higher priority, root role only) -#}\n{{- bod_token ~ bos_token ~ 'system' ~ '\\n' }}\n{{- build_system_message(system_message) }}\n{{- eos_token ~ '\\n' }}\n\n{#- Render developer sp (lower priority: system/developer role + tools) -#}\n{{- bos_token ~ 'developer' ~ '\\n' }}\n{{- build_developer_message(developer_message) }}\n{%- if tools -%}\n {{- '\\n\\n' ~ '# Tools' ~ '\\n' ~ 'You may call one or more tools to assist with the user query.\\nHere are the tools available in JSONSchema format:' ~ '\\n' }}\n {{- '\\n' ~ '<tools>' ~ '\\n' }}\n {{- render_tool_namespace(\"functions\", tools) }}\n {{- '</tools>' ~ '\\n\\n' }}\n {{- 'To call tools, wrap all invocations in a single ' ~ toolcall_begin_token ~ toolcall_end_token ~ ' block. Parameter values containing nested objects or arrays are recursively expanded into XML elements. Example:\\n' }}\n {{- '\\n' ~ toolcall_begin_token ~ '\\n' }}\n {{- ns_token + '<invoke name=\"tool-name-1\">' }}\n {{- ns_token + '<param-1>value-1' + ns_token + '</param-1>' }}\n {{- ns_token + '<param-2>' }}\n {{- ns_token + '<item>' }}\n {{- ns_token + '<key-a>val-a' + ns_token + '</key-a>' }}\n {{- ns_token + '<key-b>val-b' + ns_token + '</key-b>' }}\n {{- ns_token + '</item>' }}\n {{- ns_token + '</param-2>' }}\n {{- ns_token + '</invoke>\\n' }}\n {{- ns_token + '<invoke name=\"tool-name-2\">' }}\n {{- ns_token + '<param-1>value-1' + ns_token + '</param-1>' }}\n {{- ns_token + '</invoke>\\n' }}\n {{- toolcall_end_token }}\n{%- endif -%}\n{{- eos_token ~ '\\n' }}\n\n{#- Render messages -#}\n{%- set last_tool_call = namespace(name=none) -%}\n{%- for message in conversation_messages -%}\n {%- if message.role == 'assistant' -%}\n {{- bos_token ~ 'ai' ~ '\\n' }}\n\n {%- set reasoning_content = '' %}\n {%- set content = visible_text(message.content) %}\n {%- if message.reasoning_content is string %}\n {%- set reasoning_content = message.reasoning_content %}\n {%- else %}\n {%- if think_end_token in content %}\n {%- set reasoning_content = content.split(think_end_token)[0].strip('\\n').split(think_begin_token)[-1].strip('\\n') %}\n {%- set content = content.split(think_end_token)[-1].strip('\\n') %}\n {%- endif %}\n {%- endif %}\n\n {%- if reasoning_content -%}\n {#- Render thinking for every assistant turn (all-turn visible) -#}\n {{- think_begin_token ~ reasoning_content ~ think_end_token }}\n {%- else -%}\n {#- No thinking rendered → prefix with think_end_token -#}\n {{- think_end_token }}\n {%- endif -%}\n\n {%- if content -%}\n {{- content }}\n {%- endif -%}\n {%- if message.tool_calls -%}\n {{- toolcall_begin_token ~ '\\n' }}\n\n {%- for tool_call in message.tool_calls -%}\n {%- if tool_call.function -%}\n {%- set tool_call = tool_call.function -%}\n {%- endif -%}\n{{- ns_token + '<invoke name=\"' + tool_call.name + '\">' }}\n{%- set _args = tool_call.arguments -%}\n{%- for k, v in _args.items() if v is not none %}\n{{- ns_token + '<' + k + '>' -}}\n{{- to_xml(v, ns_token) -}}\n{{- ns_token + '</' + k + '>' }}\n{%- endfor -%}\n{{- ns_token + '</invoke>' ~ '\\n' }}\n {%- endfor -%}\n\n {{- toolcall_end_token }}\n {%- if message.tool_calls[-1].function -%}\n {%- set last_tool_call.name = message.tool_calls[-1].function.name -%}\n {%- else -%}\n {%- set last_tool_call.name = message.tool_calls[-1].name -%}\n {%- endif -%}\n {%- else -%}\n {%- set last_tool_call.name = none -%}\n {%- endif -%}\n {{- eos_token ~ '\\n' }}\n\n {%- elif message.role == 'tool' -%}\n {%- if last_tool_call.name is none -%}\n {{- raise_exception(\"Message has tool role, but there was no previous assistant message with a tool call!\") }}\n {%- endif -%}\n {%- if loop.first or (conversation_messages[loop.index0 - 1].role != 'tool') -%}\n {{- bos_token ~ 'tool' }}\n {%- endif -%}\n {{- '\\n<response>' }}\n {%- if message.content is string -%}\n {{- message.content }}\n {%- else -%}\n {%- for tr in message.content -%}\n {%- if tr is mapping and tr.type is defined and tr.type == 'image' -%}\n {{- image_token }}\n {%- elif tr is mapping and tr.type is defined and tr.type == 'video' -%}\n {{- video_token }}\n {%- else -%}\n {{- tr.output if tr.output is defined else (tr.text if tr.type == 'text' and tr.text is defined else tr) }}\n {%- endif -%}\n {%- endfor -%}\n {%- endif -%}\n {{- '</response>' }}\n {%- if loop.last or (conversation_messages[loop.index0 + 1].role != 'tool') -%}\n {{- eos_token ~ '\\n' -}}\n {%- endif -%}\n\n {%- elif message.role in ['system', 'developer'] -%}\n {#- Mid-conversation system/developer messages keep their position and\n map to the lower-priority M3 developer role. -#}\n {{- bos_token ~ 'developer' ~ '\\n' }}\n {{- build_developer_message(message) }}\n {{- eos_token ~ '\\n' }}\n\n {%- elif message.role == 'user' -%}\n {{- bos_token ~ 'user' ~ '\\n' }}\n {{- visible_text(message.content) }}\n {{- eos_token ~ '\\n' }}\n {%- endif -%}\n{%- endfor -%}\n\n{#- Generation prompt -#}\n{%- if add_generation_prompt -%}\n{{- bos_token ~ 'ai' ~ '\\n' }}\n{#- adaptive: no prefix, let model decide -#}\n{%- endif -%}\n",
"templatePath": "chat_template.jinja",
"templateUrl": "https://huggingface.co/MiniMaxAI/MiniMax-M3.1-Flash/blob/ce7f4df87d2e05262f5775f373dac4772f134041/chat_template.jinja",
"templateToolLines": [
125,
145
],
"templateHelperSource": null,
"templateHelperPath": null,
"templateHelperUrl": null,
"bosToken": "]~b]",
"eosToken": "[e~[",
"padToken": "]!p~[",
"unkToken": "[e~[",
"specialTokens": {
"]!p~[": 200000,
"<fim_prefix>": 200001,
"<fim_middle>": 200002,
"<fim_suffix>": 200003,
"<fim_pad>": 200004,
"<reponame>": 200005,
"<filename>": 200006,
"<gh_stars>": 200007,
"<issue_start>": 200008,
"<issue_comment>": 200009,
"<issue_closed>": 200010,
"<jupyter_start>": 200011,
"<jupyter_text>": 200012,
"<jupyter_code>": 200013,
"<jupyter_output>": 200014,
"<empty_output>": 200015,
"<commit_before>": 200016,
"<commit_msg>": 200017,
"<commit_after>": 200018,
"]~b]": 200019,
"[e~[": 200020,
"]!d~[": 200021,
"<function_call>": 200022,
"<code_interpreter>": 200023,
"]<]speech[>[": 200024,
"]<]image[>[": 200025,
"]<]video[>[": 200026,
"]<]start of speech[>[": 200027,
"]<]end of speech[>[": 200028,
"]<]start of image[>[": 200029,
"]<]end of image[>[": 200030,
"]<]start of video[>[": 200031,
"]<]end of video[>[": 200032,
"]<]vision pad[>[": 200033,
"]~!b[": 200034,
"<jupyter_error>": 200035,
"<add_file>": 200036,
"<delete_file>": 200037,
"<rename_file>": 200038,
"<edit_file>": 200039,
"<commit_message>": 200040,
"<empty_source_file>": 200041,
"<repo_struct>": 200042,
"<code_context>": 200043,
"<file_content>": 200044,
"<source_files>": 200045,
"<pr_start>": 200046,
"<review_comment>": 200047,
"<filepath>": 200048,
"<file_sep>": 200049,
"<think>": 200050,
"</think>": 200051,
"<tool_call>": 200052,
"</tool_call>": 200053,
"]<]frame[>[": 200054,
"]<]start of frame[>[": 200055,
"]<]end of frame[>[": 200056,
"<|content_altered_placeholder|>": 200057,
"]<]minimax[>[": 200058,
"<mm:think>": 200059,
"</mm:think>": 200060
},
"stopTokenCall": "[e~[",
"stopTokenText": "[e~[",
"dedicatedStopToken": false,
"stopKind": "shared",
"eosNote": "MiniMax-M3.1's generation_config sets EOS to [e~[ (id 200020), shared across tool calls and plain replies; ]<]minimax[>[<tool_call> marks tool invocations.",
"cap": "MiniMax-M3.1 serializes each tool's <code>function</code> dict as JSON inside <code><tools><tool>...</tool></tools></code> in the system message (framed by <code>]~b]system</code> and <code>[e~[</code>). All nested properties and constraints survive intact.",
"outCap": "MiniMax-M3.1 prefixes structural XML call tags with special token <code>]<]minimax[>[</code> (id 200059), nesting child elements for objects and <code><item></code> elements for arrays.",
"walkSteps": {
"s2": "chat_template.jinja serializes each tool's function dict as JSON inside <tools><tool>…</tool></tools> under ]~b]system, preserving every nested object and constraint.",
"s3": "The system prompt surrounds <tools> with calling instructions explaining the ]<]minimax[>[ namespaced XML syntax.",
"s4": "The rendered prompt ends with ]~b]ai\\n, opening the assistant turn.",
"s5": "After <mm:think>…</mm:think>, the model prefixes <tool_call>, <invoke name=\"…\">, and recursive parameter/<item> tags with special token ]<]minimax[>[ (200059).",
"s6": "vLLM's MinimaxM3 parser and SGLang's MinimaxM3Detector (skip_special_tokens=False) recursively parse namespaced elements and coerce values against the schema.",
"s7": "Generation stops on shared [e~[ (id 200020); on an ordinary completed auto-tool turn with parsed calls, the serving layer rewrites engine 'stop' to API finish_reason='tool_calls'."
},
"lane": [
"<mm:think> … </mm:think> reasoning block",
"]<]minimax[>[<tool_call> opens tool block",
"]<]minimax[>[<invoke name=\"…\"> names the tool",
"Recursive ]<]minimax[>[<param> / <item> XML values",
"]<]minimax[>[</invoke> and </tool_call> close block",
"[e~[ ends turn; sampler reports stop"
],
"laneText": [
"<mm:think> … </mm:think> reasoning block",
"Plain assistant answer text",
"[e~[ ends turn; sampler reports stop"
],
"excerpts": {
"vllm": [
{
"repo": "vllm",
"path": "vllm/parser/minimax_m3.py",
"start": 50,
"end": 75,
"hl": [
50,
51,
52,
53,
56,
69
],
"sha": "ef687f6179b752c028767e610addbda67ed36d03",
"url": "https://github.com/vllm-project/vllm/blob/ef687f6179b752c028767e610addbda67ed36d03/vllm/parser/minimax_m3.py#L50-L75",
"note": "vLLM's MiniMax M3 parser anchors structural tags on NAMESPACE = ']<]minimax[>[' and defines recursive _parse_element.",
"code": "NAMESPACE = \"]<]minimax[>[\"\nTOOL_CALL_START = f\"{NAMESPACE}<tool_call>\"\nTOOL_CALL_END = f\"{NAMESPACE}</tool_call>\"\nINVOKE_PREFIX_DQ = f'{NAMESPACE}<invoke name=\"'\nINVOKE_PREFIX_SQ = f\"{NAMESPACE}<invoke name='\"\nINVOKE_PREFIX_UNQUOTED = f\"{NAMESPACE}<invoke name=\"\nINVOKE_END = f\"{NAMESPACE}</invoke>\"\nNAME_END_DQ = '\">'\nNAME_END_SQ = \"'>\"\nNAME_END_UNQUOTED = \">\"\nELEMENT_START = f\"{NAMESPACE}<\"\nELEMENT_END_START = f\"{NAMESPACE}</\"\nMIXED_TEXT_FIELD = \"$text\"\nMAX_ELEMENT_DEPTH = 128\n\n# An element value: its text, or its ``(name, value)`` children in order.\n_Element = str | list[tuple[str, \"_Element\"]]\n\n\ndef _parse_element(text: str, pos: int, depth: int) -> tuple[str, _Element, int] | None:\n \"\"\"Parse the element starting at `pos`; `None` if malformed.\"\"\"\n if depth > MAX_ELEMENT_DEPTH:\n return None\n name_start = pos + len(ELEMENT_START)\n name_end = text.find(\">\", name_start)\n if name_end <= name_start:"
}
],
"sglang": [
{
"repo": "sglang",
"path": "python/sglang/srt/function_call/minimax_m3.py",
"start": 18,
"end": 42,
"hl": [
18,
31,
32,
34,
35
],
"sha": "1918da6349f9be1c62315503e1a7458a3957bc5f",
"url": "https://github.com/sgl-project/sglang/blob/1918da6349f9be1c62315503e1a7458a3957bc5f/python/sglang/srt/function_call/minimax_m3.py#L18-L42",
"note": "SGLang's MinimaxM3Detector defines namespaced ]<]minimax[>[ tool-call and invoke markers.",
"code": "MINIMAX_NS_TOKEN = \"]<]minimax[>[\"\nSTRING_TYPES = {\"string\", \"str\"}\nINTEGER_TYPES = {\"integer\", \"int\"}\nNUMBER_TYPES = {\"number\", \"float\"}\nBOOLEAN_TYPES = {\"boolean\", \"bool\"}\nSCALAR_TYPES = STRING_TYPES | INTEGER_TYPES | NUMBER_TYPES | BOOLEAN_TYPES | {\"null\"}\nCONTAINER_TYPES = {\"object\", \"array\"}\n# Exact-case only; \"none\"/\"nil\" are valid string enum values, never null-coerced.\nNULL_STRINGS = {\"null\", \"Null\", \"NULL\"}\nUNTYPED_LITERALS = {\"true\": True, \"false\": False, \"null\": None}\n\n\nclass MinimaxM3Detector(BaseFormatDetector):\n TOOL_CALL_START = MINIMAX_NS_TOKEN + \"<tool_call>\"\n TOOL_CALL_END = MINIMAX_NS_TOKEN + \"</tool_call>\"\n\n INVOKE_PREFIX = MINIMAX_NS_TOKEN + '<invoke name=\"'\n INVOKE_SUFFIX = MINIMAX_NS_TOKEN + \"</invoke>\"\n PARAM_START_PREFIX = MINIMAX_NS_TOKEN + \"<\"\n TAG_SPACING_CHARS = \" \\t\\r\\n\"\n TAG_SPACING_RE = re.compile(re.escape(MINIMAX_NS_TOKEN) + r\"[ \\t\\r\\n]+(?=<)\")\n\n def __init__(self):\n super().__init__()\n self._in_tool_call = False"
}
]
}
},
{
"key": "glimmer",
"id": "meta-models/Muse-Glimmer-30B",
"label": "Muse-Glimmer-30B",
"sub": "ATEM XML",
"sha": "1297fd7dfeac4598948a5d15886968435c81c2b7",
"created": "2026-08-09",
"likes": 2169,
"templateKind": "jinja",
"schemaEncoding": "JSON under // Function schemas",
"callSyntax": "<atem:function_calls>",
"servingNote": "Muse-Glimmer routes messages with Harmony-style to=<recipient><|message|> headers and ATEM XML payloads; vLLM (muse.py) and SGLang (muse_glimmer_detector.py) parse recipient routing + <atem:invoke> blocks.",
"chatTemplate": "{#\n Template: Muse Glimmer ATEM Chat Template\n Renders the ATEM tool-calling protocol: reasoning channel (to=self), tool\n channels (to=<tool>), and the user channel, plus tool definitions and the\n valid-recipient list in the system block.\n\n Whitespace note: every tag uses the {%- -%} / {{- -}} stripping markers, so\n the indentation below is purely for readability and contributes nothing to\n the rendered output.\n#}\n{%- macro render_content(content) -%}\n {%- if content is string -%}\n {{- content -}}\n {%- elif content is not none -%}\n {%- for part in content -%}\n {%- if part['type'] == 'image' -%}\n {{- '<|patch|>' -}}\n {%- elif part['type'] == 'video' -%}\n {{- '<|video|>' -}}\n {%- elif part['type'] == 'text' -%}\n {{- part['text'] -}}\n {%- endif -%}\n {%- endfor -%}\n {%- endif -%}\n{%- endmacro -%}\n{%- macro render_atem(tc) -%}\n {%- set args = tc.function.arguments -%}\n {%- if args is not mapping -%}\n {{- raise_exception('Muse Glimmer ATEM chat template requires tool_call.function.arguments to be a dict (mapping); a JSON string cannot be parsed in the HF jinja sandbox.') -}}\n {%- endif -%}\n {{- '<atem:function_calls>\\n<atem:invoke name=\"' + tc.function.name + '\">\\n' -}}\n {%- for k, v in args.items() -%}\n {{- '<atem:parameter name=\"' + k + '\">' -}}\n {%- if v is boolean -%}\n {%- if v -%}\n true\n {%- else -%}\n false\n {%- endif -%}\n {%- elif v is none -%}\n null\n {%- elif v is mapping or (v is iterable and v is not string) -%}\n {{- v | tojson -}}\n {%- else -%}\n {{- v -}}\n {%- endif -%}\n {{- '</atem:parameter>\\n' -}}\n {%- endfor -%}\n {{- '</atem:invoke>\\n</atem:function_calls>' -}}\n{%- endmacro -%}\n{%- macro render_tool_defs(tools) -%}\n {{- 'In this environment you have access to a set of tools you can use to answer the user\\'s question.\\n\\n' -}}\n {{- 'You can invoke a function by writing a \"<atem:function_calls>\" block like the following:\\n' -}}\n {{- '<atem:function_calls>\\n<atem:invoke name=\"$FUNCTION_NAME\">\\n<atem:parameter name=\"$PARAMETER_NAME\">$PARAMETER_VALUE</atem:parameter>\\n...\\n</atem:invoke>\\n</atem:function_calls>\\n\\n' -}}\n {{- 'String and scalar parameters should be specified as is, while lists and objects should use JSON format. Note that spaces for string values are not stripped. The output is not expected to be valid XML and is parsed with regular expressions.\\n' -}}\n {{- 'Here are the functions available in JSONSchema format:\\n' -}}\n {{- '// Tool metadata\\n' -}}\n {%- set nsns = namespace(seen=[]) -%}\n {%- for tool in tools -%}\n {%- set fn = tool.function if tool.function is defined else tool -%}\n {%- set tns = fn.name.split('.')[0] -%}\n {%- if tns not in nsns.seen -%}\n {%- set nsns.seen = nsns.seen + [tns] -%}\n {%- endif -%}\n {%- endfor -%}\n {%- set nd = tool_namespace_descriptions if tool_namespace_descriptions is defined else {} -%}\n {%- for tns in nsns.seen -%}\n {{- '{\"name\": ' + (tns | tojson) + ', \"description\": ' + ((nd[tns] if tns in nd else '') | tojson) + '}\\n' -}}\n {%- endfor -%}\n {{- '// Function schemas' -}}\n {%- for tool in tools -%}\n {%- set fn = tool.function if tool.function is defined else tool -%}\n {{- '\\n{\"name\": ' + (fn.name | tojson) + ', \"description\": ' + (fn.description | tojson) + ', \"parameters\": ' + (fn.parameters | tojson) + '}' -}}\n {%- endfor -%}\n {{- '\\n\\nHere\\'s an example of how to call a function in the tool set:\\n' -}}\n {{- '(If the tool namespace is not specified, invoke the function directly as `example_function_name` rather than `example_tool_name.example_function_name`)\\n\\n' -}}\n {{- 'to=example_tool_name.example_function_name\\n\\n' -}}\n {{- '<atem:function_calls>\\n<atem:invoke name=\"example_tool_name.example_function_name\">\\n' -}}\n {{- '<atem:parameter name=\"example_parameter_1\">value_1</atem:parameter>\\n' -}}\n {{- '<atem:parameter name=\"example_parameter_2\">This is the value for the second parameter\\nthat can span\\n\"multiple\" lines\\n</atem:parameter>\\n' -}}\n {{- '</atem:invoke>\\n</atem:function_calls>' -}}\n{%- endmacro -%}\n{%- macro render_reasoning() -%}\n {%- set rs = reasoning_strength if reasoning_strength is defined and reasoning_strength else 'high' -%}\n {{- 'Reasoning strength: ' + rs + '.' -}}\n{%- endmacro -%}\n{%- macro render_response_format() -%}\n {#- The engine enforces response_format by sampling; the model never sees it. State it so the\n model writes the answer the grammar expects. -#}\n {%- if response_format is defined and response_format -%}\n {%- if response_format.type == 'json_schema' -%}\n {{- '\\n\\nIn your final response to the user\\'s latest message the output must adhere to the following json schema: ' + (response_format.json_schema.schema | tojson) -}}\n {%- endif -%}\n {%- endif -%}\n{%- endmacro -%}\n{%- macro render_system_meta(tools) -%}\n {%- set rns = namespace(recipients=['\"self\"'], nslist=[]) -%}\n {%- if tools -%}\n {%- for tool in tools -%}\n {%- set fn = tool.function if tool.function is defined else tool -%}\n {%- set tns = fn.name.split('.')[0] -%}\n {%- if tns not in rns.nslist -%}\n {%- set rns.nslist = rns.nslist + [tns] -%}\n {%- endif -%}\n {%- endfor -%}\n {%- for tns in rns.nslist -%}\n {%- set rns.recipients = rns.recipients + ['\"' + tns + '.*\"'] -%}\n {%- endfor -%}\n {%- endif -%}\n {%- set rns.recipients = rns.recipients + ['\"user\"'] -%}\n {{- '# Valid recipients: ' + rns.recipients | join(', ') + '.' -}}\n{%- endmacro -%}\n{{- bos_token -}}\n{%- set ns = namespace(has_system=false) -%}\n{%- for m in messages -%}\n {%- if m['role'] == 'system' -%}\n {%- set ns.has_system = true -%}\n {%- endif -%}\n{%- endfor -%}\n{%- if not ns.has_system -%}\n {{- '<|start|>system<|message|>You are a helpful AI assistant.' -}}\n {%- set kc = knowledge_cutoff if knowledge_cutoff is defined and knowledge_cutoff else '2026-01-04' -%}\n {{- '\\nKnowledge cutoff: ' + kc + '.' -}}\n {%- if current_date is defined and current_date -%}\n {{- '\\nCurrent date: ' + current_date + '.' -}}\n {%- elif strftime_now is defined -%}\n {{- '\\nCurrent date: ' + strftime_now('%Y-%m-%d') + '.' -}}\n {%- endif -%}\n {{- '\\n\\n' -}}\n {{- render_reasoning() -}}\n {{- render_response_format() -}}\n {%- if tools -%}\n {{- '\\n\\n' -}}\n {{- render_tool_defs(tools) -}}\n {%- endif -%}\n {{- '\\n\\n' -}}\n {{- render_system_meta(tools) -}}\n {{- '<|eot|>' -}}\n{%- endif -%}\n{%- for message in messages -%}\n {%- set role = message['role'] -%}\n {%- set end_token = '<|eom|>' if (not loop.last and messages[loop.index0 + 1]['role'] == role) else '<|eot|>' -%}\n {%- if role == 'system' -%}\n {#- Callers sometimes write the directive into the system prompt themselves.\n Normalise \"Reasoning effort\" to \"Reasoning strength\" (jinja has no\n case-insensitive replace, hence the four realistic casings), then skip\n the kwarg-driven line below if the prompt already carries one. -#}\n {%- set sys_text = render_content(message['content'])\n | replace('Reasoning effort', 'Reasoning strength')\n | replace('Reasoning Effort', 'Reasoning Strength')\n | replace('reasoning effort', 'reasoning strength')\n | replace('REASONING EFFORT', 'REASONING STRENGTH') -%}\n {{- '<|start|>system<|message|>' -}}\n {{- sys_text -}}\n {%- if 'reasoning strength' not in (sys_text | lower) -%}\n {{- '\\n\\n' -}}\n {{- render_reasoning() -}}\n {%- endif -%}\n {{- render_response_format() -}}\n {%- if tools -%}\n {{- '\\n\\n' -}}\n {{- render_tool_defs(tools) -}}\n {%- endif -%}\n {{- '\\n\\n' -}}\n {{- render_system_meta(tools) -}}\n {{- '<|eot|>' -}}\n {%- elif role == 'user' -%}\n {{- '<|start|>user<|message|>' -}}\n {{- render_content(message['content']) -}}\n {{- '<|eot|>' -}}\n {%- elif role == 'tool' -%}\n {%- set tname = message.get('name') -%}\n {%- if not tname -%}\n {%- set tcid = message.get('tool_call_id') -%}\n {%- set rns = namespace(name=tcid if tcid else '') -%}\n {%- for m in messages -%}\n {%- if m.get('tool_calls') -%}\n {%- for tc in m['tool_calls'] -%}\n {%- if tcid is not none and tc.id is defined and tc.id == tcid -%}\n {%- set rns.name = tc.function.name -%}\n {%- endif -%}\n {%- endfor -%}\n {%- endif -%}\n {%- endfor -%}\n {%- set tname = rns.name -%}\n {%- endif -%}\n {{- '<|start|>tool ' + tname + '<|message|><tool_output name=\"' + tname + '\">\\n' -}}\n {{- render_content(message['content']) -}}\n {{- '\\n</tool_output><|eot|>' -}}\n {%- elif role == 'assistant' -%}\n {%- if message.get('reasoning_content') -%}\n {{- '<|start|>assistant to=self<|message|>' + message['reasoning_content'] + '<|eom|>' -}}\n {%- endif -%}\n {%- if message.get('tool_calls') -%}\n {%- for tc in message['tool_calls'] -%}\n {{- '<|start|>assistant to=' + tc.function.name + '<|message|>' -}}\n {{- render_atem(tc) -}}\n {%- if loop.last -%}\n {{- end_token -}}\n {%- else -%}\n {{- '<|eom|>' -}}\n {%- endif -%}\n {%- endfor -%}\n {%- else -%}\n {%- set recipient = message.get('recipient') or 'user' -%}\n {%- set end_turn = message.get('end_turn') -%}\n {%- if end_turn is none -%}\n {%- set end_turn = not (recipient and recipient != 'user') -%}\n {%- endif -%}\n {{- '<|start|>assistant' -}}\n {%- if recipient -%}\n {{- ' to=' + recipient -}}\n {%- endif -%}\n {{- '<|message|>' -}}\n {{- render_content(message['content']) -}}\n {{- ('<|eot|>' if end_turn else '<|eom|>') -}}\n {%- endif -%}\n {%- endif -%}\n{%- endfor -%}\n{%- if add_generation_prompt -%}\n {{- '<|start|>assistant' -}}\n{%- endif -%}\n",
"templatePath": "chat_template.jinja",
"templateUrl": "https://huggingface.co/meta-models/Muse-Glimmer-30B/blob/1297fd7dfeac4598948a5d15886968435c81c2b7/chat_template.jinja",
"templateToolLines": [
55,
115
],
"templateHelperSource": null,
"templateHelperPath": null,
"templateHelperUrl": null,
"bosToken": "<|begin_of_text|>",
"eosToken": "<|end_of_text|>",
"padToken": "<|finetune_right_pad|>",
"unkToken": "",
"specialTokens": {
"<|begin_of_text|>": 200000,
"<|end_of_text|>": 200001,
"<|eom|>": 200007,
"<|eot|>": 200008,
"<|finetune_right_pad|>": 200018,
"<|start|>": 200022,
"<|message|>": 200023,
"<|image_start|>": 200080,
"<|image_end|>": 200081,
"<|vid_start|>": 200082,
"<|vid_end|>": 200083,
"<|vid_frame_separator|>": 200087,
"<|image|>": 200090,
"<|video|>": 200091,
"<|patch|>": 200092
},
"stopTokenCall": "<|eot|>",
"stopTokenText": "<|eot|>",
"dedicatedStopToken": false,
"stopKind": "shared",
"eosNote": "Muse-Glimmer's generation_config lists EOS IDs [200001, 200008] (<|end_of_text|>, <|eot|>). Internal to=self reasoning and intermediate parallel calls end in <|eom|> (200007), while the final call before a tool result and final text replies share <|eot|> (200008).",
"cap": "Muse-Glimmer emits a system prompt under <code><|start|>system<|message|></code> listing each tool's JSON schema under <code>// Tool metadata</code> alongside ATEM XML calling instructions. Nested schemas and constraints are serialized as JSON intact.",
"outCap": "Muse-Glimmer routes <code>to={name}<|message|></code> into <code><atem:function_calls><atem:invoke name=\"...\"><atem:parameter name=\"...\"></code> and closes on shared <code><|eot|></code>.",
"walkSteps": {
"s2": "chat_template.jinja serializes each tool's JSON schema under // Tool metadata in <|start|>system<|message|>, preserving nested objects, arrays, enums, and numeric bounds.",
"s3": "Below the schemas, the system prompt appends ATEM XML calling rules and an example invocation.",
"s4": "The rendered prompt ends with <|start|>assistant, leaving the model to emit its own to=self or to=<tool> recipient header.",
"s5": "After to=self<|message|>…<|eom|>, the model routes <|start|>assistant to={name}<|message|><atem:function_calls><atem:invoke name=\"…\"><atem:parameter name=\"…\">.",
"s6": "vLLM's Muse parser and SGLang's MuseGlimmerDetector (keeping special tokens) match to=<recipient> headers and extract <atem:invoke>/<atem:parameter> blocks.",
"s7": "Internal to=self blocks end in <|eom|> (200007), while the final tool call and plain to=user replies share <|eot|> (200008); parsed calls rewrite engine 'stop' to API finish_reason='tool_calls'."
},
"lane": [
"to=self<|message|> … <|eom|> internal reasoning",
"<|start|>assistant to=…<|message|> routes to tool",
"<atem:function_calls><atem:invoke name=\"…\"> opens call",
"<atem:parameter name=\"…\"> argument tags",
"</atem:invoke></atem:function_calls> closes block",
"<|eot|> ends turn; sampler reports stop"
],
"laneText": [
"to=self<|message|> … <|eom|> internal reasoning",
"<|start|>assistant to=user<|message|> answer text",
"<|eot|> ends turn; sampler reports stop"
],
"excerpts": {
"vllm": [
{
"repo": "vllm",
"path": "vllm/parser/muse.py",
"start": 47,
"end": 65,
"hl": [
47,
48,
49,
50,
52,
54
],
"sha": "ef687f6179b752c028767e610addbda67ed36d03",
"url": "https://github.com/vllm-project/vllm/blob/ef687f6179b752c028767e610addbda67ed36d03/vllm/parser/muse.py#L47-L65",
"note": "vLLM's Muse parser defines <|eom|>/<|eot|> boundaries, recipient regex, and <atem:invoke> pattern.",
"code": "START = \"<|start|>\"\nMESSAGE = \"<|message|>\"\nEOM = \"<|eom|>\"\nEOT = \"<|eot|>\"\n\n_RECIPIENT_RE = re.compile(r\"to=([A-Za-z0-9_.\\-]+)\\s*$\")\n_HEADER_TAIL_RE = re.compile(r\"(?:t|to|to=[A-Za-z0-9_.\\-]{0,256})$\")\n_INVOKE_RE = re.compile(\n r'<atem:invoke\\b[^<>]*?\\bname=\"([^\"]+)\"[^<>]*>(.*?)</atem:invoke>', re.DOTALL\n)\n_PARAMETER_RE = re.compile(\n r'<atem:parameter\\b[^<>]*?\\bname=\"([^\"]+)\"[^<>]*?>(.*?)</atem:parameter>',\n re.DOTALL,\n)\n_INVOKE_END = \"</atem:invoke>\"\n_BODY_STATES = frozenset({ParserState.CONTENT, ParserState.REASONING})\n_MAX_HEADER_TOKENS = 64\n\n"
}
],
"sglang": [
{
"repo": "sglang",
"path": "python/sglang/srt/function_call/muse_glimmer_format.py",
"start": 6,
"end": 23,
"hl": [
7,
8,
9,
13,
14,
15
],
"sha": "1918da6349f9be1c62315503e1a7458a3957bc5f",
"url": "https://github.com/sgl-project/sglang/blob/1918da6349f9be1c62315503e1a7458a3957bc5f/python/sglang/srt/function_call/muse_glimmer_format.py#L6-L23",
"note": "SGLang's muse_glimmer_format defines <|message|>, <|eom|>, <|eot|>, and <atem:function_calls> format constants.",
"code": "# Channel framing.\nMESSAGE = \"<|message|>\"\nEOM = \"<|eom|>\"\nEOT = \"<|eot|>\"\nSTART = \"<|start|>\"\n\n# ATEM payload markers.\nFUNCTION_CALLS_OPEN = \"<atem:function_calls>\"\nFUNCTION_CALLS_CLOSE = \"</atem:function_calls>\"\nINVOKE_OPEN = \"<atem:invoke\"\nINVOKE_CLOSE = \"</atem:invoke>\"\n\nRECIPIENT_RE = re.compile(r\"to=([^\\s<]+)\")\n\n# Longest marker that could straddle a chunk boundary while streaming.\nMAX_CHANNEL_MARKER = max(len(m) for m in (MESSAGE, EOM, EOT, START))\nMAX_MARKER = max(MAX_CHANNEL_MARKER, len(FUNCTION_CALLS_OPEN))\n"
}
]
}
},
{
"key": "beam",
"id": "reflection/Beam-1.0-501B-A23B",
"label": "Beam-1.0-501B",
"sub": "Harmony + XML hybrid",
"sha": "12950ae640b48cbbe9b5bb7735bf197507d6383f",
"created": "2026-10-07",
"likes": 328,
"templateKind": "jinja",
"schemaEncoding": "TS signatures (Harmony)",
"callSyntax": "<|constrain|>xml <rfl:parameter>",
"servingNote": "Beam combines Harmony channel framing (<|start|>, <|channel|>, <|call|>, <|return|>) with <rfl:parameter> XML arguments; vLLM (beam.py) and SGLang (BeamDetector) compile response-template structural tags for supported schemas.",
"chatTemplate": "{#-\n harmony_xml: Harmony wire format with XML tool-call bodies.\n\n Channels are `analysis` and `final`; there is no commentary channel. Tools\n are declared as flat TypeScript under `# Tools` and called with\n `<|constrain|>xml` and `rfl:parameter` bodies.\n\n Kwargs:\n - model_identity: defaults to \"You are Beam, an AI assistant trained by\n Reflection.\"\n - reasoning_effort: emits `Reasoning effort: N` after the identity line;\n defaults to 512 (`max`) when unset or null. Accepts an int, or the labels\n `minimal`/`low`/`medium`/`high`/`xhigh`/`max` mapped to\n 8/32/64/128/256/512. Other strings raise. `minimal` is 8, the smallest\n effort training sampled: a smaller budget is not respected.\n - builtin_tools: names from `tools=` to render in the system `# Tools` block,\n with their own definitions. Only name `search` and `browse`, and only with\n the definitions Beam was trained with. Every other tool, including a\n `search` or `browse` with a different definition, belongs in the developer\n block, where `tools=` renders it by default.\n Exception: a `bash` tool whose only parameter is an unconstrained `command`\n string is always declared in the system block with the trained definition,\n without this kwarg; its own descriptions are not rendered. A `bash` with\n any other call shape follows the rule above.\n - allow_missing_thinking: defaults to true. When false, a generation prompt\n raises when any assistant turn has empty or no reasoning, since dropping it\n degrades the model's output. Setting it to false is highly recommended for\n serving.\n\n OpenAI roles \"system\" and \"developer\" are equivalent and map to the developer\n `# Instructions` block. Consecutive ones at the start of `messages` join into\n that one block, a blank line apart; empty content is omitted. A system or\n developer message after the first message of another role is not rendered.\n The Reflection system block is injected before the developer block.\n\n Tool wire:\n - Calls: `to={name}` + analysis + `<|constrain|>xml` + rfl: body\n - Results: `{recipient} to=assistant` on analysis\n - Parallel calls: `<|end|>` between calls, `<|call|>` on the last\n - `function.arguments` must be a dict (parse JSON strings before apply)\n-#}\n\n{%- macro ts_type_name(type_val) -%}\n {%- if type_val == \"integer\" -%}\n {{- \"number\" -}}\n {%- elif type_val in [\"string\", \"number\", \"boolean\"] -%}\n {{- type_val -}}\n {%- else -%}\n {{- \"any\" -}}\n {%- endif -%}\n{%- endmacro -%}\n\n{#- Property defaults render enum strings bare. Generic `oneOf` variants pass\n false because the reference renderer quotes them in that path. #}\n{%- macro render_default(schema, bare_enum_string=true) -%}\n {%- set is_enum = schema.get(\"enum\") is sequence and schema.get(\"enum\") is not string and schema.get(\"enum\") -%}\n {%- if schema.default is string and (not is_enum or not bare_enum_string) -%}\n {{- '\"' + schema.default + '\"' -}}\n {%- elif schema.default is string -%}\n {{- schema.default -}}\n {%- else -%}\n {{- schema.default | tojson(separators=(\",\", \":\")) -}}\n {%- endif -%}\n{%- endmacro -%}\n\n{#- The reference renderer checks the complete rendered text for `null`, so\n this intentionally does the same rather than inspecting schema members. #}\n{%- macro render_nullable_type(schema, indent) -%}\n {%- set rendered = json_schema_to_typescript(schema, indent) -%}\n {{- rendered -}}\n {%- if schema is mapping and schema.get(\"nullable\") and \"null\" not in rendered -%}\n {{- \" | null\" -}}\n {%- endif -%}\n{%- endmacro -%}\n\n{#- Render a JSON-schema node as a TypeScript type.\n\n `indent` is the leading spaces for properties inside an object; nested\n objects bump it by 4. Use `schema[\"items\"]` (not `schema.items`), since\n attribute access would hit dict.items. #}\n{%- macro json_schema_to_typescript(schema, indent=0) -%}\n {%- if schema is mapping and schema.get(\"oneOf\") is sequence and schema.get(\"oneOf\") is not string -%}\n {%- for variant in schema.oneOf -%}\n {{- \"\\n\" + (\" \" * indent) + \" | \" -}}\n {{- render_nullable_type(variant, indent + 3) -}}\n {%- if variant is mapping and variant.get(\"description\") is string -%}\n {{- \" // \" + variant.description -}}\n {%- if \"default\" in variant -%}\n {{- \" default: \" + render_default(variant, false) -}}\n {%- endif -%}\n {%- elif variant is mapping and \"default\" in variant -%}\n {{- \" // default: \" + render_default(variant, false) -}}\n {%- endif -%}\n {%- endfor -%}\n {#- Only a string enum becomes a literal union. An integer or untyped enum\n falls through to its plain type, or to `any` when it has none. #}\n {%- elif schema is mapping and schema.get(\"enum\") is sequence and schema.get(\"enum\") is not string and schema.get(\"enum\") and schema.get(\"type\") == \"string\" -%}\n {%- set rendered_enum = namespace(any=false) -%}\n {%- for val in schema.enum -%}\n {%- if val is string -%}\n {%- if rendered_enum.any %} | {% endif -%}\n {{- val | tojson -}}\n {%- set rendered_enum.any = true -%}\n {%- endif -%}\n {%- endfor -%}\n {%- if not rendered_enum.any %}string{%- endif -%}\n {%- elif schema is mapping and schema.get(\"type\") == \"object\" -%}\n {%- if schema.get(\"description\") is string -%}\n {{- (\" \" * indent) + \"// \" + schema.description + \"\\n\" -}}\n {%- endif -%}\n {{- \"{\\n\" -}}\n {%- set required = schema.required if schema.get(\"required\") else [] -%}\n {%- if schema.get(\"properties\") -%}\n {#- Properties render in insertion order, so a schema controls the\n order its parameters appear in. #}\n {%- for prop_name, prop_spec in schema.properties.items() -%}\n {%- if prop_spec is mapping and prop_spec.get(\"title\") is string -%}\n {{- (\" \" * indent) + \"// \" + prop_spec.title + \"\\n\" -}}\n {{- (\" \" * indent) + \"//\\n\" -}}\n {%- endif -%}\n {%- if prop_spec is mapping and \"oneOf\" not in prop_spec and prop_spec.get(\"description\") is string -%}\n {{- (\" \" * indent) + \"// \" + prop_spec.description + \"\\n\" -}}\n {%- endif -%}\n {%- if prop_spec is mapping and prop_spec.get(\"examples\") is sequence and prop_spec.get(\"examples\") is not string and prop_spec.get(\"examples\") -%}\n {{- (\" \" * indent) + \"// Examples:\\n\" -}}\n {%- for example in prop_spec.examples -%}\n {%- if example is string -%}\n {{- (\" \" * indent) + '// - \"' + example + '\"\\n' -}}\n {%- endif -%}\n {%- endfor -%}\n {%- endif -%}\n {%- if prop_spec is mapping and prop_spec.get(\"oneOf\") is sequence and prop_spec.get(\"oneOf\") is not string -%}\n {%- set property_description = prop_spec.get(\"description\") if prop_spec.get(\"description\") is string else none -%}\n {%- set first_variant = prop_spec.oneOf[0] if prop_spec.oneOf else {} -%}\n {%- set first_description = first_variant.get(\"description\") if first_variant is mapping and first_variant.get(\"description\") is string else none -%}\n {%- set render_property_description = property_description and property_description != first_description -%}\n {%- if render_property_description -%}\n {{- (\" \" * indent) + \"// \" + property_description + \"\\n\" -}}\n {%- endif -%}\n {%- if \"default\" in prop_spec -%}\n {{- (\" \" * indent) + \"// default: \" + render_default(prop_spec) + \"\\n\" -}}\n {%- endif -%}\n {{- (\" \" * indent) + prop_name -}}\n {%- if prop_name not in required -%}?{%- endif -%}\n {{- \":\\n\" -}}\n {%- for variant in prop_spec.oneOf -%}\n {{- (\" \" * indent) + \" | \" -}}\n {{- render_nullable_type(variant, indent + 3) -}}\n {%- set render_variant_description = variant is mapping and variant.get(\"description\") is string and variant.description != property_description and not (loop.first and render_property_description) -%}\n {%- if render_variant_description -%}\n {{- \" // \" + variant.description -}}\n {%- if \"default\" in variant -%}\n {{- \" default: \" + render_default(variant) -}}\n {%- endif -%}\n {%- elif variant is mapping and \"default\" in variant -%}\n {{- \" // default: \" + render_default(variant) -}}\n {%- endif -%}\n {{- \"\\n\" -}}\n {%- endfor -%}\n {{- (\" \" * indent) + \",\\n\" -}}\n {%- else -%}\n {{- (\" \" * indent) + prop_name -}}\n {%- if prop_name not in required -%}?{%- endif -%}\n {{- \": \" -}}\n {{- render_nullable_type(prop_spec, indent + 4) -}}\n {{- \",\" -}}\n {%- if prop_spec is mapping and \"default\" in prop_spec -%}\n {{- \" // default: \" + render_default(prop_spec) -}}\n {%- endif -%}\n {{- \"\\n\" -}}\n {%- endif -%}\n {%- endfor -%}\n {%- endif -%}\n {{- (\" \" * indent) + \"}\" -}}\n {%- elif schema is mapping and schema.get(\"type\") == \"array\" -%}\n {%- if schema.get(\"items\") -%}\n {{- json_schema_to_typescript(schema[\"items\"], indent) + \"[]\" -}}\n {%- else -%}\n {{- \"Array<any>\" -}}\n {%- endif -%}\n {%- elif schema is mapping and schema.get(\"type\") is string -%}\n {{- ts_type_name(schema.type) -}}\n {%- elif schema is mapping and schema.get(\"type\") is sequence -%}\n {%- set rendered_types = namespace(any=false) -%}\n {%- for ty in schema.type -%}\n {%- if ty is string -%}\n {%- if rendered_types.any %} | {% endif -%}\n {%- if ty == \"integer\" %}number{%- else %}{{ ty }}{%- endif -%}\n {%- set rendered_types.any = true -%}\n {%- endif -%}\n {%- endfor -%}\n {%- if not rendered_types.any %}any{%- endif -%}\n {%- else -%}\n {{- \"any\" -}}\n {%- endif -%}\n{%- endmacro -%}\n\n{#- String-schema tools declare as `## name`; every other tool declares as\n `type name = (_: {...}) => any;`. Call sites emit XML either way. #}\n{%- macro render_tool_declaration(tool) -%}\n {%- set tool = tool.function if tool.function is defined else tool -%}\n {%- if tool.parameters is mapping and tool.parameters.get(\"type\") == \"string\" and (not tool.parameters.get(\"properties\")) -%}\n {{- \"## \" + tool.name + \"\\n\\n\" -}}\n {{- tool.description or \"\" -}}\n {%- else -%}\n {%- if tool.description -%}\n {%- for line in tool.description.split(\"\\n\") -%}\n {{- \"// \" + line + \"\\n\" -}}\n {%- endfor -%}\n {%- endif -%}\n {#- A tool with no parameters keeps the `(_: ...)` form and renders\n `(_: any)`. #}\n {{- \"type \" + tool.name + \" = (_: \" + json_schema_to_typescript(tool.parameters) + \") => any;\" -}}\n {%- endif -%}\n{%- endmacro -%}\n\n{%- macro render_tools_section(tools) -%}\n {{- \"# Tools\\n\\n\" -}}\n {%- for tool in tools -%}\n {{- render_tool_declaration(tool) -}}\n {%- if not loop.last -%}\n {{- \"\\n\\n\" -}}\n {%- endif -%}\n {%- endfor -%}\n{%- endmacro -%}\n\n{#- String values go out as-is; non-strings are JSON-encoded in their given\n order, at every depth. Jinja's `tojson` sorts keys by default, so mappings\n and sequences recurse through this macro instead of being handed to it. #}\n{%- macro render_json_value(value) -%}\n {%- if value is mapping -%}\n {{- \"{\" -}}\n {%- for k, v in value.items() -%}\n {{- k | tojson }}: {{ render_json_value(v) -}}\n {%- if not loop.last %}, {% endif -%}\n {%- endfor -%}\n {{- \"}\" -}}\n {%- elif value is sequence and value is not string -%}\n {{- \"[\" -}}\n {%- for item in value -%}\n {{- render_json_value(item) -}}\n {%- if not loop.last %}, {% endif -%}\n {%- endfor -%}\n {{- \"]\" -}}\n {%- else -%}\n {{- value | tojson -}}\n {%- endif -%}\n{%- endmacro -%}\n\n{%- macro render_parameter_value(value) -%}\n {%- if value is string -%}\n {{- value -}}\n {%- else -%}\n {{- render_json_value(value) -}}\n {%- endif -%}\n{%- endmacro -%}\n\n{%- macro render_tool_call_body(tool_call) -%}\n {%- set fn = tool_call.function if tool_call.function is defined else tool_call -%}\n {%- set args = fn.arguments if fn.arguments is defined else tool_call.arguments -%}\n {%- if args is mapping -%}\n {%- for param_name in args -%}\n {%- set value_text = render_parameter_value(args[param_name]) -%}\n {%- if \"</rfl:parameter>\" in value_text -%}\n {{- raise_exception(\"Tool-call parameter '\" + (param_name | string) + \"' contains the reserved delimiter </rfl:parameter>\") }}\n {%- endif -%}\n {%- if not loop.first %}{{- \"\\n\" }}{%- endif -%}\n {{- '<rfl:parameter name=\"' + param_name + '\">\\n' -}}\n {{- value_text -}}\n {{- '\\n</rfl:parameter>' -}}\n {%- endfor -%}\n {%- elif args is defined and args is not none -%}\n {{- raise_exception(\"function.arguments must be a dict; parse JSON strings before apply_chat_template\") }}\n {%- endif -%}\n{%- endmacro -%}\n\n{%- macro build_system_message(builtin_tool_definitions) -%}\n {%- if model_identity is not defined %}\n {%- set model_identity = \"You are Beam, an AI assistant trained by Reflection.\" %}\n {%- endif %}\n {{- model_identity -}}\n {#- Served default: effort 512 (`max`) when the kwarg is unset or null. #}\n {%- if reasoning_effort is not defined or reasoning_effort is none %}\n {%- set reasoning_effort = 512 %}\n {%- endif %}\n {%- if reasoning_effort is string %}\n {%- if reasoning_effort == \"minimal\" %}\n {%- set reasoning_effort = 8 %}\n {%- elif reasoning_effort == \"low\" %}\n {%- set reasoning_effort = 32 %}\n {%- elif reasoning_effort == \"medium\" %}\n {%- set reasoning_effort = 64 %}\n {%- elif reasoning_effort == \"high\" %}\n {%- set reasoning_effort = 128 %}\n {%- elif reasoning_effort == \"xhigh\" %}\n {%- set reasoning_effort = 256 %}\n {%- elif reasoning_effort == \"max\" %}\n {%- set reasoning_effort = 512 %}\n {%- else %}\n {{- raise_exception(\"reasoning_effort must be an int or one of: minimal, low, medium, high, xhigh, max\") }}\n {%- endif %}\n {%- endif %}\n {{- \"\\n\\nReasoning effort: \" + (reasoning_effort | string) }}\n {%- if builtin_tool_definitions -%}\n {{- \"\\n\\n\" -}}\n {{- render_tools_section(builtin_tool_definitions) -}}\n {%- endif -%}\n {{- \"\\n\\n# Valid channels: analysis, final. Channel must be included for every message.\" -}}\n{%- endmacro -%}\n\n{%- if not messages %}{{ raise_exception(\"messages cannot be empty\") }}{%- endif %}\n\n{#- `tools=` remains the serving engine's complete tool registry. The names in\n `builtin_tools` only select which definitions move into the system block. #}\n{%- set builtin_tool_names = builtin_tools | default([], true) -%}\n{#- Training declares `bash` in the system block with this definition, so a\n `bash` whose only parameter is an unconstrained `command` string is declared\n with it. Only descriptions and `additionalProperties` may differ, since they\n leave the accepted calls the same; any schema key that constrains the call\n keeps the supplied definition in the developer block. An omitted `required`\n is declared as required: every call the trained declaration invites is one\n the supplied schema accepts. #}\n{%- set trained_bash_tool = {\n \"name\": \"bash\",\n \"description\": \"Execute a bash command. The output contains the command's stdout and stderr.\\nCommands time out after 10 minutes. You can set a shorter timeout within the bash command.\",\n \"parameters\": {\n \"type\": \"object\",\n \"properties\": {\"command\": {\"type\": \"string\", \"description\": \"The command to execute\"}},\n \"required\": [\"command\"],\n },\n} -%}\n{%- set tool_groups = namespace(builtin=[], regular=[]) -%}\n{%- for tool in tools | default([], true) -%}\n {%- set tool_definition = tool.function if tool.function is defined else tool -%}\n {%- set tool_name = tool_definition.name -%}\n {%- set tool_parameters = tool_definition.parameters if tool_definition.parameters is mapping else {} -%}\n {%- set tool_properties = tool_parameters.properties if tool_parameters.properties is mapping else {} -%}\n {%- set bash_shape = namespace(plain=true) -%}\n {%- for key in tool_parameters -%}\n {%- if key not in [\"type\", \"properties\", \"required\", \"additionalProperties\", \"description\"] -%}\n {%- set bash_shape.plain = false -%}\n {%- endif -%}\n {%- endfor -%}\n {%- set command_schema = tool_properties.command if tool_properties.command is mapping else {} -%}\n {%- for key in command_schema -%}\n {%- if key not in [\"type\", \"description\"] -%}\n {%- set bash_shape.plain = false -%}\n {%- endif -%}\n {%- endfor -%}\n {%- set is_trained_bash = tool_name == \"bash\"\n and bash_shape.plain\n and tool_parameters.get(\"type\") == \"object\"\n and (tool_properties | list) == [\"command\"]\n and command_schema.get(\"type\") == \"string\"\n and tool_parameters.get(\"required\", [\"command\"]) == [\"command\"] -%}\n {%- if is_trained_bash -%}\n {%- set tool_groups.builtin = tool_groups.builtin + [trained_bash_tool] -%}\n {%- elif tool_name in builtin_tool_names -%}\n {%- set tool_groups.builtin = tool_groups.builtin + [tool] -%}\n {%- else -%}\n {%- set tool_groups.regular = tool_groups.regular + [tool] -%}\n {%- endif -%}\n{%- endfor -%}\n\n{{- \"<|start|>system<|message|>\" }}\n{{- build_system_message(tool_groups.builtin) }}\n{{- \"<|end|>\" }}\n\n{#- The leading run of system/developer messages joins, a blank line apart,\n into the one `# Instructions` block. Empty content counts as absent, so a\n run with no content emits no `# Instructions`. #}\n{%- set leading_instructions = namespace(count=0, parts=[]) %}\n{%- for message in messages %}\n {%- if loop.index0 == leading_instructions.count and message.role in [\"system\", \"developer\"] %}\n {%- set leading_instructions.count = leading_instructions.count + 1 %}\n {%- if message.content %}\n {%- set leading_instructions.parts = leading_instructions.parts + [message.content] %}\n {%- endif %}\n {%- endif %}\n{%- endfor %}\n{%- set developer_message = leading_instructions.parts | join(\"\\n\\n\") %}\n{%- set loop_messages = messages[leading_instructions.count:] %}\n\n{%- if add_generation_prompt and allow_missing_thinking is defined and allow_missing_thinking == false %}\n {%- for message in loop_messages %}\n {%- if message.role == 'assistant' and not (message.thinking or message.reasoning_content or message.reasoning) %}\n {{- raise_exception(\"The assistant turn at messages[\" + ((loop.index0 + leading_instructions.count) | string) + \"] is missing its reasoning. Dropping reasoning from earlier turns degrades this model's output. Send it back in 'reasoning_content', or set allow_missing_thinking=true to skip this check.\") }}\n {%- endif %}\n {%- endfor %}\n{%- endif %}\n\n{%- set has_tools = tool_groups.regular %}\n\n{%- if developer_message or has_tools %}\n {{- \"<|start|>developer<|message|>\" }}\n {%- if developer_message %}\n {{- \"# Instructions\\n\\n\" }}\n {{- developer_message }}\n {%- if has_tools %}\n {{- \"\\n\\n\" }}\n {%- endif %}\n {%- endif %}\n {%- if has_tools %}\n {{- render_tools_section(tool_groups.regular) }}\n {%- endif %}\n {{- \"<|end|>\" }}\n{%- endif %}\n\n{%- set tool_call_registry = namespace(entries=[]) %}\n\n{%- for message in loop_messages -%}\n {%- if message.role == 'assistant' -%}\n {%- if message.content %}\n {%- if \"<|channel|>analysis<|message|>\" in message.content or \"<|channel|>final<|message|>\" in message.content %}\n {{- raise_exception(\"Pass plain text in API fields, not Harmony wire tags. Use 'thinking' for analysis and 'content' for final.\") }}\n {%- endif %}\n {%- endif %}\n {%- set thinking_text = message.thinking or message.reasoning_content or message.reasoning %}\n {%- if thinking_text %}\n {%- if \"<|channel|>analysis<|message|>\" in thinking_text or \"<|channel|>final<|message|>\" in thinking_text %}\n {{- raise_exception(\"Pass plain text in 'thinking'/'reasoning_content'/'reasoning' without Harmony wire tags.\") }}\n {%- endif %}\n {%- endif %}\n {{- \"<|start|>assistant\" }}\n {%- generation %}\n {{- \"<|channel|>analysis<|message|>\" + (thinking_text or \"\") + \"<|end|>\" }}\n {%- if message.tool_calls %}\n {%- for tool_call in message.tool_calls %}\n {%- set fn = tool_call.function if tool_call.function is defined else tool_call %}\n {%- set tool_name = fn.name if fn.name is defined else tool_call.name %}\n {%- set call_id = tool_call.id if tool_call.id is defined else (fn.id if fn.id is defined else none) %}\n {%- if call_id and tool_name %}\n {%- set tool_call_registry.entries = tool_call_registry.entries + [{\"id\": call_id, \"name\": tool_name}] %}\n {%- endif %}\n {{- \"<|start|>assistant to=\" + tool_name + \"<|channel|>analysis <|constrain|>xml<|message|>\" }}\n {{- render_tool_call_body(tool_call) }}\n {%- if loop.last %}\n {{- \"<|call|>\" }}\n {%- else %}\n {{- \"<|end|>\" }}\n {%- endif %}\n {%- endfor %}\n {%- else %}\n {{- \"<|start|>assistant<|channel|>final<|message|>\" + (message.content or \"\") + \"<|return|>\" }}\n {%- endif %}\n {%- endgeneration %}\n {%- elif message.role == 'tool' -%}\n {%- set resolved_tool = namespace(name=none) %}\n {%- if message.name is defined and message.name %}\n {%- set resolved_tool.name = message.name %}\n {%- elif message.tool_call_id is defined %}\n {%- for entry in tool_call_registry.entries %}\n {%- if entry.id == message.tool_call_id %}\n {%- set resolved_tool.name = entry.name %}\n {%- endif %}\n {%- endfor %}\n {%- endif %}\n {%- if resolved_tool.name is none %}\n {{- raise_exception(\"Tool message needs 'name' or a matching prior tool_call 'id' / 'tool_call_id'.\") }}\n {%- endif %}\n {{- \"<|start|>\" + resolved_tool.name + \" to=assistant<|channel|>analysis<|message|>\" + (message.content or \"\") + \"<|end|>\" }}\n {%- elif message.role == 'user' -%}\n {{- \"<|start|>user<|message|>\" + (message.content or \"\") + \"<|end|>\" }}\n {%- endif -%}\n{%- endfor -%}\n\n{%- if add_generation_prompt -%}\n<|start|>assistant\n{%- endif -%}\n",
"templatePath": "chat_template.jinja",
"templateUrl": "https://huggingface.co/reflection/Beam-1.0-501B-A23B/blob/12950ae640b48cbbe9b5bb7735bf197507d6383f/chat_template.jinja",
"templateToolLines": [
215,
290
],
"templateHelperSource": null,
"templateHelperPath": null,
"templateHelperUrl": null,
"bosToken": "",
"eosToken": "<|return|>",
"padToken": "<|endoftext|>",
"unkToken": "",
"specialTokens": {
"<|endoftext|>": 151643,
"<|im_start|>": 151644,
"<|im_end|>": 151645,
"<|object_ref_start|>": 151646,
"<|object_ref_end|>": 151647,
"<|box_start|>": 151648,
"<|box_end|>": 151649,
"<|quad_start|>": 151650,
"<|quad_end|>": 151651,
"<|vision_start|>": 151652,
"<|vision_end|>": 151653,
"<|vision_pad|>": 151654,
"<|image_pad|>": 151655,
"<|video_pad|>": 151656,
"<tool_call>": 151657,
"</tool_call>": 151658,
"<|fim_prefix|>": 151659,
"<|fim_middle|>": 151660,
"<|fim_suffix|>": 151661,
"<|fim_pad|>": 151662,
"<|repo_name|>": 151663,
"<|file_sep|>": 151664,
"<tool_response>": 151665,
"</tool_response>": 151666,
"<think>": 151667,
"</think>": 151668,
"<|start|>": 151669,
"<|end|>": 151670,
"<|message|>": 151671,
"<|channel|>": 151672,
"<|constrain|>": 151673,
"<|return|>": 151674,
"<|call|>": 151675,
"<|value_unk|>": 151676,
"<|value_zero_0|>": 151677,
"<|value_one_0|>": 151678,
"<rfl:parameter name=\"": 151679,
"\n</rfl:parameter>": 151680
},
"stopTokenCall": "<|call|>",
"stopTokenText": "<|return|>",
"dedicatedStopToken": true,
"stopKind": "dedicated",
"eosNote": "Beam-1.0's generation_config lists EOS IDs [151674, 151675]: dedicated <|call|> (151675) stops the final tool call (intermediate parallel calls use <|end|>), while <|return|> (151674) finishes plain answers.",
"cap": "Beam-1.0 renders tools inside <code><|start|>developer</code> using a Harmony-derived TypeScript macro (<code>type name = (_: { ... }) => any;</code>). It converts <code>integer</code> to <code>number</code> and preserves nested object schemas and enums, while omitting numeric bounds like <code>minimum</code>/<code>maximum</code>.",
"outCap": "Beam-1.0 routes <code>to={name}<|channel|>analysis <|constrain|>xml<|message|></code>, writes <code><rfl:parameter name=\"...\"></code> blocks, and halts on dedicated <code><|call|></code>.",
"walkSteps": {
"s2": "chat_template.jinja compiles tools into TypeScript function signatures under <|start|>developer<|message|>, turning integer into number and dropping minimum/maximum while keeping nested objects and enums.",
"s3": "The system and developer headers frame the signatures with Harmony channel rules and XML parameter conventions.",
"s4": "The rendered prompt ends with <|start|>assistant, leaving the model to open <|channel|>analysis itself.",
"s5": "After analysis<|end|>, the model routes <|start|>assistant to={name}<|channel|>analysis <|constrain|>xml<|message|> and writes <rfl:parameter name=\"…\"> blocks.",
"s6": "vLLM's BeamParser and SGLang's BeamDetector build xgrammar response-template structural tags (when supported) and parse <rfl:parameter> blocks.",
"s7": "Generation stops on dedicated <|call|> (151675), separate from <|return|> (151674) for plain replies; parsed calls map engine 'stop' to API finish_reason='tool_calls'."
},
"lane": [
"<|channel|>analysis<|message|> … <|end|> reasoning",
"<|start|>assistant to=… routes to tool",
"<|channel|>analysis <|constrain|>xml<|message|> header",
"<rfl:parameter name=\"…\"> XML argument blocks",
"<|call|> dedicated call stop; sampler reports stop"
],
"laneText": [
"<|channel|>analysis<|message|> … <|end|> reasoning",
"<|start|>assistant<|channel|>final<|message|> answer text",
"<|return|> ends turn; sampler reports stop"
],
"excerpts": {
"vllm": [
{
"repo": "vllm",
"path": "vllm/parser/beam.py",
"start": 122,
"end": 146,
"hl": [
126,
127,
129,
136
],
"sha": "ef687f6179b752c028767e610addbda67ed36d03",
"url": "https://github.com/vllm-project/vllm/blob/ef687f6179b752c028767e610addbda67ed36d03/vllm/parser/beam.py#L122-L146",
"note": "vLLM's BeamParser compiles Beam's response_template into an xgrammar structural tag when supported.",
"code": " def _constrain_request(\n self,\n request: ChatCompletionRequest | ResponsesRequest,\n ) -> ChatCompletionRequest | ResponsesRequest:\n message_start = _starts_message(self.response_template, self._prefix)\n tag = self._template_tag(request, message_start=message_start)\n if tag is not None:\n grammar = StructuredOutputsParams(structural_tag=json.dumps(tag))\n if isinstance(request, ChatCompletionRequest):\n request.structured_outputs = grammar\n request.response_format = None\n else:\n request._parser_structured_outputs = grammar\n # From the message start, the tag also covers the reasoning.\n request._grammar_from_parser = message_start\n return request\n\n def _template_tag(\n self,\n request: ChatCompletionRequest | ResponsesRequest,\n *,\n message_start: bool,\n ) -> dict[str, Any] | None:\n \"\"\"The template grammar for `request`, or `None` to leave its output\n to the request's own constraint, if any.\"\"\""
}
],
"sglang": [
{
"repo": "sglang",
"path": "python/sglang/srt/function_call/beam_detector.py",
"start": 14,
"end": 34,
"hl": [
15,
16,
18,
24
],
"sha": "1918da6349f9be1c62315503e1a7458a3957bc5f",
"url": "https://github.com/sgl-project/sglang/blob/1918da6349f9be1c62315503e1a7458a3957bc5f/python/sglang/srt/function_call/beam_detector.py#L14-L34",
"note": "SGLang's BeamDetector configures ResponseTemplateToolDetector with strict_arguments=True for supported tool schemas.",
"code": "class BeamDetector(ResponseTemplateToolDetector):\n response_template = BEAM_RESPONSE_TEMPLATE\n constrains_every_turn = True\n # Unheld, Beam's arguments drift from their schemas.\n strict_arguments = True\n\n def supports_structural_tag(self) -> bool:\n # Forced calls then keep the native format, which this detector parses\n # instead of the JSON array used without a template-derived tag.\n tools = [tool.model_dump() for tool in self._tools or ()]\n return supports_tool_call_structural_tag(self._tool_field, tools)\n\n def get_structural_tag(\n self,\n tools: list[Tool] | None = None,\n tool_choice: Any = \"auto\",\n thinking_mode: bool = False,\n parallel_tool_calls: bool = True,\n message_start: bool = False,\n ):\n tool_dicts = [tool.model_dump() for tool in tools or ()]"
}
]
}
}
]
};
// Auto-generated by v2-work/build_data.py — do not hand-edit.
export const REPORT_DATA = {
"meta": {
"generatedAt": "2026-11-22",
"repos": {
"transformers": {
"sha": "4cac50ff5414dd0b591e6d5fc1c5ca3f32a20a16",
"shortSha": "4cac50f",
"url": "https://github.com/huggingface/transformers/tree/4cac50ff5414dd0b591e6d5fc1c5ca3f32a20a16"
},
"vllm": {
"sha": "ef687f6179b752c028767e610addbda67ed36d03",
"shortSha": "ef687f6",
"url": "https://github.com/vllm-project/vllm/tree/ef687f6179b752c028767e610addbda67ed36d03"
},
"sglang": {
"sha": "1918da6349f9be1c62315503e1a7458a3957bc5f",
"shortSha": "1918da6",
"url": "https://github.com/sgl-project/sglang/tree/1918da6349f9be1c62315503e1a7458a3957bc5f"
},
"llama_cpp": {
"sha": "35c9b1f39ebe5a7bb83986d64415a079218be78d",
"shortSha": "35c9b1f",
"url": "https://github.com/ggml-org/llama.cpp/tree/35c9b1f39ebe5a7bb83986d64415a079218be78d"
}
}
},
"presets": {
"search": {
"id": "search",
"label": "search_models",
"sub": "flat",
"userPrompt": "Find small speech-recognition models, at most 3.",
"tools": [
{
"type": "function",
"function": {
"name": "search_models",
"description": "Search the Hugging Face Hub for models.",
"parameters": {
"type": "object",
"properties": {
"query": {
"type": "string",
"description": "Free-text search, e.g. 'whisper small'."
},
"task": {
"type": "string",
"enum": [
"text-generation",
"automatic-speech-recognition",
"image-text-to-text"
],
"description": "Pipeline tag to filter by."
},
"limit": {
"type": "integer",
"minimum": 1,
"maximum": 50,
"description": "How many results to return."
}
},
"required": [
"query"
]
}
}
}
],
"sampleArgs": {
"query": "whisper small",
"task": "automatic-speech-recognition",
"limit": 3
},
"sampleToolResult": {
"count": 2,
"models": [
"openai/whisper-small",
"distil-whisper/distil-small.en"
]
},
"textReply": "You can filter Hugging Face models by automatic-speech-recognition on huggingface.co/models, or let me run search_models if you want live matches.",
"tip": "Rename <code>limit</code> to <code>max_results</code>, add <code>\"default\": 10</code>, or change its type to <code>\"string\"</code> and watch both the prompt and parsed call update."
},
"ticket": {
"id": "ticket",
"label": "create_ticket",
"sub": "nested",
"userPrompt": "Open a high-priority ticket for cust_42 (email ops@acme.dev) tagged billing.",
"tools": [
{
"type": "function",
"function": {
"name": "create_ticket",
"description": "Create a support ticket with nested customer contact details.",
"parameters": {
"type": "object",
"properties": {
"priority": {
"type": "string",