// 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 limit to max_results, add \"default\": 10, or change its type to \"string\" 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 gpt-oss-120b with Kimi-K2.6 or Qwen3.8-27B: Harmony's TypeScript macro collapses contacts to any[], dropping kind and value."
}
},
"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 ",
"callSyntax": "",
"servingNote": "vLLM and SGLang render prompts via transformers apply_chat_template(tools=...) and parse 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\" }}\n {%- for tool in tools %}\n {{- \"\\n\" }}\n {{- tool | tojson }}\n {%- endfor %}\n {{- \"\\n\" }}\n {{- '\\n\\nIf you choose to call a function ONLY reply in the following format with NO suffix:\\n\\n\\n\\n\\nvalue_1\\n\\n\\nThis is the value for the second parameter\\nthat can span\\nmultiple lines\\n\\n\\n\\n\\n\\nReminder:\\n- Function calls MUST follow the specified format: an inner block must be nested within 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' }}\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('') and content.endswith('')) %}\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 {{- '\\n' + reasoning_content + '\\n\\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\\n\\n' }}\n {%- else %}\n {{- '\\n\\n' }}\n {%- endif %}\n {%- else %}\n {{- '\\n\\n\\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 {{- '\\n' }}\n {%- set args_value = args_value | string if args_value is string else args_value | tojson | safe %}\n {{- args_value }}\n {{- '\\n\\n' }}\n {%- endfor %}\n {%- endif %}\n {{- '\\n' }}\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\\n' }}\n {{- content }}\n {{- '\\n' }}\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 {{- '\\n\\n\\n\\n' }}\n {%- else %}\n {{- '\\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,
"": 248058,
"": 248059,
"<|fim_prefix|>": 248060,
"<|fim_middle|>": 248061,
"<|fim_suffix|>": 248062,
"<|fim_pad|>": 248063,
"<|repo_name|>": 248064,
"<|file_sep|>": 248065,
"": 248066,
"": 248067,
"": 248068,
"": 248069,
"<|audio_start|>": 248070,
"<|audio_end|>": 248071,
"": 248072,
"": 248073,
"": 248074,
"": 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 .",
"cap": "Qwen3.8 serializes each tool dict as a JSON line via tool | tojson inside <tools> tags in the system message. Every nested field, enum, and numeric bound survives intact, surrounded by explicit XML calling instructions.",
"outCap": "After closing </think>, Qwen3.8 emits XML <function=name> and <parameter=key> tags, then stops on the shared <|im_end|> token.",
"walkSteps": {
"s2": "Qwen3.8's Jinja template serializes each tool dict as a JSON line via tool | tojson inside ..., keeping every nested object, enum, and numeric bound intact.",
"s3": "Around , the system block adds explicit prose and a full XML example showing , , and tags.",
"s4": "The rendered prompt ends with <|im_start|>assistant\\n\\n, putting the model directly inside its reasoning block.",
"s5": "After , the model emits special token , plain-text and XML tags, and closes with .",
"s6": "vLLM's Qwen3 parser and SGLang's Qwen3CoderDetector (with skip_special_tokens=False) match , (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 ",
" opens tool-call block",
" names the target tool",
" tags carry each argument value",
" and close the block",
"<|im_end|> ends turn; sampler reports stop"
],
"laneText": [
"Reasoning text closes with ",
"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 , \"\nTHINK_END = \"\"\nTOOL_CALL_START = \"\"\nTOOL_CALL_END = \"\"\nCHATML_TURN_BOUNDARIES = frozenset((\"<|im_start|>\", \"<|im_end|>\"))\nFUNC_PREFIX = \"\"\nPARAM_START = \"\"\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 , \"\n self.tool_call_end_token: str = \"\"\n self.tool_call_prefix: str = \"\"\n self.parameter_prefix: str = \"\"\n\n # Regex for non-streaming fallback\n self.tool_call_regex = re.compile(r\"(.*?)\", re.DOTALL)\n self.tool_call_function_regex = re.compile(\n r\"||(?=)|$)\",\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 {{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 {{render_content(message)}}\n {%- else -%}\n {%- set rc = message.get('reasoning', message.get('reasoning_content', '')) -%}\n {{rc}}{{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 \n {%- else -%}\n \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\",\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,
"": 163606,
"": 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": "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). That helper rewrites JSON Schema into a TypeScript namespace functions block with // doc comments, converts integer to number, and moves minimum/maximum into comments.",
"outCap": "Kimi-K2.6 uses dedicated special tokens for the section, call wrapper, and argument boundary around plain-text functions.name:0 and JSON arguments, then stops on shared <|im_end|>.",
"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|>, opening the assistant's thinking channel.",
"s5": "After , the model emits <|tool_calls_section_begin|><|tool_call_begin|>functions.: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 ",
"<|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 ",
"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 = \"\"\nTHINK_END = \"\"\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.+:\\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 ```` 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 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,
"": 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 encoding_k3.py to emit XTML control tokens (<|open|>, <|sep|>, <|close|>). Tools are deep-key-sorted and serialized as compact JSON inside a type=\"tool-declare\" system message.",
"outCap": "Every assistant turn emits <|open|>think, <|open|>response, and optionally <|open|>tools with typed <|open|>argument key=... type=... 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\""
}
],
"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 ",
"callSyntax": "fn…",
"servingNote": "vLLM (glm47_moe) and SGLang (glm47_moe_detector) parse namekv with schema-driven type coercion.",
"chatTemplate": "[gMASK]\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 {{- '\\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 {{- '' -}}\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 XML tags:\n\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\n\nFor each function call, output the function name and arguments within the following XML format:\n{function-name}{arg-key-1}{arg-value-1}{arg-key-2}{arg-value-2}...{%- 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{{- '' + text + '' -}}\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 '' in content %}\n {%- set reasoning_content = content.split('')[0].split('')[-1] %}\n {%- set content = content.split('')[-1] %}\n{%- endif %}\n{%- if (not clear_thinking or loop.index0 > ns.last_user_index) and reasoning_content is defined -%}\n{{ '' + reasoning_content + ''}}\n{%- else -%}\n{{ '' }}\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{{- '' ~ tc.name -}}\n{% set _args = tc.arguments %}{% for k, v in _args.items() %}{{ k }}{{ v | tojson(ensure_ascii=False) if v is not string else v }}{% endfor %}{% 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|>{{- '' -}}\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,
"": 154824,
"": 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,
"": 154841,
"": 154842,
"": 154843,
"": 154844,
"": 154845,
"": 154846,
"": 154847,
"": 154848,
"": 154849,
"": 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 tojson inside <tools>...</tools> under <|system|>. All JSON Schema keywords survive intact, and the system prompt prescribes exact <arg_key>/<arg_value> syntax.",
"outCap": "GLM-5.3-Flash writes the function name directly after <tool_call>, pairs each argument in <arg_key>/<arg_value> tags, and hands off at the <|observation|> role boundary.",
"walkSteps": {
"s2": "The Jinja template serializes each tool dict via tojson inside ... under [gMASK]<|system|>, preserving nested schemas, enums, defaults, and bounds.",
"s3": "Surrounding system prose explains the {name}{k}{v} format.",
"s4": "The rendered prompt ends with <|assistant|>, starting directly inside the assistant reasoning block.",
"s5": "After , the model emits special tokens , / pairs, and .",
"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 ",
" opens tool-call block",
"Bare function name follows ",
"…… pairs",
" closes tool-call block",
"<|observation|> role boundary ends turn; sampler reports stop"
],
"laneText": [
"Reasoning text closes with ",
"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 , , and terminals.",
"code": "THINK_START = \"\"\nTHINK_END = \"\"\nTOOL_CALL_START = \"\"\nTOOL_CALL_END = \"\"\nARG_KEY_START = \"\"\nARG_KEY_END = \"\"\nARG_VALUE_START = \"\"\nARG_VALUE_END = \"\"\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\"(?P.*?)\\s*\"\n r\"(?P.*?)\",\n re.DOTALL,\n)\n_PARTIAL_ARG_RE = re.compile(\n r\"(?P.*?)\\s*\"\n r\"(?P.*)$\",\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 / 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 (custom macro)",
"callSyntax": "",
"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 = ''.format(HYTK) %}\n{%- set think_end_token = ''.format(HYTK) %}\n{%- set toolcalls_begin_token = ''.format(HYTK) %}\n{%- set toolcalls_end_token = ''.format(HYTK) %}\n{%- set toolcall_begin_token = ''.format(HYTK) %}\n{%- set toolcall_end_token = ''.format(HYTK) %}\n{%- set argkey_begin_token = ''.format(HYTK) %}\n{%- set argkey_end_token = ''.format(HYTK) %}\n{%- set argvalue_begin_token = ''.format(HYTK) %}\n{%- set argvalue_end_token = ''.format(HYTK) %}\n{%- set toolresponse_begin_token = ''.format(HYTK) %}\n{%- set toolresponse_end_token = ''.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 XML tags:' -}}\n {{- '\\n\\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\\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 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 {{- '\\n' -}}\n {%- set tools_ns.open = true -%}\n {%- elif not is_search_output and tools_ns.open -%}\n {{- '' -}}\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 {{- '' -}}\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,
"": 120029,
"": 120030,
"": 120033,
"": 120034,
"": 120035,
"": 120036,
"": 120037,
"": 120038,
"<|reasoning_mode:opensource|>": 120039,
"": 120040,
"": 120041,
"": 120042,
"": 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; signals tool invocation.",
"cap": "Hy4-flash uses a custom Jinja macro (tool_to_json) to serialize each function as JSON inside <tools> under <|hy_start:opensource|>system, excluding internal keys like defer_loading and strict. Structural chat and tool tags carry a :opensource suffix.",
"outCap": "Hy4-flash wraps calls in <tool_calls:opensource>, pairs arguments with <arg_key:opensource> / <arg_value:opensource> special tokens, and stops on shared <|hy_end:opensource|> (120025).",
"walkSteps": {
"s2": "chat_template.jinja serializes each tool into via its custom tool_to_json macro, preserving nested properties, enums, and numeric bounds.",
"s3": "The system prompt wraps with calling instructions specifying the :opensource-suffixed tool and argument tags.",
"s4": "The rendered prompt ends with <|hy_start:opensource|>assistant<|hy_middle:opensource|>, opening the namespaced reasoning block.",
"s5": "After , the model emits name with / 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 ",
" opens call",
"Bare function name follows ",
" / pairs",
" closes call",
"<|hy_end:opensource|> ends turn; sampler reports stop"
],
"laneText": [
"Reasoning text closes with ",
"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 ```` 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 .",
"code": "# a shared suffix to each (e.g. ````); 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\" + \"|\".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 ), you MUST output your complete reasoning inside ... BEFORE any tool calls or final response.\\n\\nOtherwise, output directly after with tool calls or final response.\\n\\n### Available Tool Schemas\\n\\n\" -}}\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 + [\"\" ~ tc ~ \"\"] -%}\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 \"\") ~ \"\" -}}\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|>\" ~ (\"\" if thinking else \"\") -}}{%- 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|>\" ~ (\"\" if thinking and (not effective_drop or idx >= state.last_user) else \"\") -}}\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,
"": 128821,
"": 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,
"": 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 ## Tools / ### Available Tool Schemas inside <|System|>. Its Jinja template uses Python's .format() to inject the |DSML| marker prefix into every example tag.",
"outCap": "DeepSeek-V4.1 emits spaced DSML tags (<|DSML| calls>, <|DSML| invoke>, <|DSML| parameter name=... string=\"true|false\">) and stops on shared <|end▁of▁sentence|>.",
"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|>, placing the model inside its thinking block.",
"s5": "After , 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 ",
"<|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 ",
"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 <|message_system|>tool_declare<|content_xml|>—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 <|content_invoke_tool_json|>, writes {\"name\":\"...\",\"args\":{...}} with sorted argument keys, closes with <|end_message|>, and halts on shared <|content_model_end_sampling|>.",
"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 <|start|>developer using a Jinja TypeScript macro (namespace functions). It converts integer to number, drops numeric bounds like minimum/maximum, and collapses arrays of nested objects like contacts to any[].",
"outCap": "Shown in the Hub/vLLM header order (to=functions.{name}<|channel|>commentary <|constrain|>json), streaming JSON arguments and halting on dedicated <|call|>; SGLang's detector expects <|channel|>commentary before to=functions.{name}.",
"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{…}",
"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('') -%}\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 {{- '' -}}\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 {{- '' -}}\n {%- endfor %}\n {%- set ns.prev_message_type = 'tool' -%}\n {%- endif -%}\n {{- '\\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' -}}\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 {{- '}' -}}\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 {{- '\\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' -}}\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": "",
"eosToken": "",
"padToken": "",
"unkToken": "",
"specialTokens": {
"": 0,
"": 1,
"": 2,
"": 3,
"": 4,
"<|tool>": 46,
"": 47,
"<|tool_call>": 48,
"": 49,
"<|tool_response>": 50,
"": 51,
"<|\"|>": 52,
"<|think|>": 98,
"<|channel>": 100,
"": 101,
"<|turn>": 105,
"": 106,
"<|image>": 255999,
"<|audio>": 256000,
"<|image|>": 258880,
"<|audio|>": 258881,
"": 258882,
"