"""Muse Glimmer prompt format. A direct port of ``chat_template.jinja`` from meta-models/Muse-Glimmer-30B. ``tools/test_glimmer_fmt.py`` renders the same conversations through ``transformers.AutoTokenizer.apply_chat_template`` and asserts byte equality, so this file is not a paraphrase of the template — it is checked against it. Why a port rather than calling transformers: the pool generators need to emit millions of tokens of markup deterministically and without loading a 28 MB tokenizer per worker, and the calibration text must stay reproducible even if a future transformers release changes its jinja sandbox. Note the tool-call tags are namespaced ``atem:``. Emitting bare ```` would put the calibration on token sequences the model never sees. """ from __future__ import annotations import json from typing import Any, Iterable, Sequence # --- special tokens, ids from tokenizer.json ------------------------------ BOS = "<|begin_of_text|>" # 200000 EOS = "<|end_of_text|>" # 200001 EOM = "<|eom|>" # 200007 end of message, turn continues EOT = "<|eot|>" # 200008 end of turn START = "<|start|>" # 200022 MESSAGE = "<|message|>" # 200023 PATCH = "<|patch|>" # 200092 one image patch VIDEO = "<|video|>" # 200091 SPECIAL_IDS = { BOS: 200000, EOS: 200001, EOM: 200007, EOT: 200008, START: 200022, MESSAGE: 200023, VIDEO: 200091, PATCH: 200092, } REASONING_STRENGTHS = ("low", "medium", "high", "xhigh") DEFAULT_REASONING = "high" DEFAULT_KNOWLEDGE_CUTOFF = "2026-01-04" DEFAULT_SYSTEM = "You are a helpful AI assistant." def _tojson(v: Any) -> str: """Match the jinja ``tojson`` filter as transformers configures it.""" return json.dumps(v, ensure_ascii=False) def render_content(content: Any) -> str: if isinstance(content, str): return content if content is None: return "" out = [] for part in content: t = part.get("type") if t == "image": out.append(PATCH) elif t == "video": out.append(VIDEO) elif t == "text": out.append(part["text"]) return "".join(out) def _param_value(v: Any) -> str: if isinstance(v, bool): return "true" if v else "false" if v is None: return "null" if isinstance(v, dict) or (isinstance(v, (list, tuple, set)) and not isinstance(v, str)): return _tojson(v) return str(v) def render_atem(name: str, arguments: dict) -> str: """The ATEM tool-call block. ``arguments`` must be a mapping; the template raises on a JSON string, so we do too.""" if not isinstance(arguments, dict): raise TypeError("tool call arguments must be a dict, not a JSON string") parts = [f'\n\n'] for k, v in arguments.items(): parts.append(f'{_param_value(v)}\n') parts.append("\n") return "".join(parts) def _namespaces(tools: Sequence[dict]) -> list[str]: seen: list[str] = [] for tool in tools: fn = tool.get("function", tool) ns = fn["name"].split(".")[0] if ns not in seen: seen.append(ns) return seen def render_tool_defs(tools: Sequence[dict], namespace_descriptions: dict | None = None) -> str: nd = namespace_descriptions or {} out = [ "In this environment you have access to a set of tools you can use to answer the user's question.\n\n", 'You can invoke a function by writing a "" block like the following:\n', '\n\n' '$PARAMETER_VALUE\n' "...\n\n\n\n", "String and scalar parameters should be specified as is, while lists and objects " "should use JSON format. Note that spaces for string values are not stripped. " "The output is not expected to be valid XML and is parsed with regular expressions.\n", "Here are the functions available in JSONSchema format:\n", "// Tool metadata\n", ] for ns in _namespaces(tools): out.append(f'{{"name": {_tojson(ns)}, "description": {_tojson(nd.get(ns, ""))}}}\n') out.append("// Function schemas") for tool in tools: fn = tool.get("function", tool) out.append( f'\n{{"name": {_tojson(fn["name"])}, "description": {_tojson(fn["description"])}, ' f'"parameters": {_tojson(fn["parameters"])}}}') out.append( "\n\nHere's an example of how to call a function in the tool set:\n" "(If the tool namespace is not specified, invoke the function directly as " "`example_function_name` rather than `example_tool_name.example_function_name`)\n\n" "to=example_tool_name.example_function_name\n\n" '\n\n' 'value_1\n' 'This is the value for the second parameter\n' 'that can span\n"multiple" lines\n\n' "\n") return "".join(out) def render_system_meta(tools: Sequence[dict] | None) -> str: recipients = ['"self"'] if tools: recipients += [f'"{ns}.*"' for ns in _namespaces(tools)] recipients.append('"user"') return "# Valid recipients: " + ", ".join(recipients) + "." def _system_block(body: str, tools: Sequence[dict] | None, reasoning: str, namespace_descriptions: dict | None) -> str: out = [START, "system", MESSAGE, body, "\n\n", f"Reasoning strength: {reasoning}."] if tools: out += ["\n\n", render_tool_defs(tools, namespace_descriptions)] out += ["\n\n", render_system_meta(tools), EOT] return "".join(out) def render(messages: Sequence[dict], tools: Sequence[dict] | None = None, reasoning_strength: str = DEFAULT_REASONING, knowledge_cutoff: str = DEFAULT_KNOWLEDGE_CUTOFF, current_date: str | None = None, namespace_descriptions: dict | None = None, add_generation_prompt: bool = False, add_bos: bool = True) -> str: """Render a conversation exactly as chat_template.jinja would. ``current_date`` is required rather than defaulted to today's date: the template would call ``strftime_now`` and make the corpus unreproducible. """ rs = reasoning_strength or DEFAULT_REASONING out: list[str] = [BOS] if add_bos else [] if not any(m["role"] == "system" for m in messages): body = [DEFAULT_SYSTEM, f"\nKnowledge cutoff: {knowledge_cutoff}."] if current_date: body.append(f"\nCurrent date: {current_date}.") out.append(_system_block("".join(body), tools, rs, namespace_descriptions)) n = len(messages) for i, message in enumerate(messages): role = message["role"] end_token = EOM if (i + 1 < n and messages[i + 1]["role"] == role) else EOT if role == "system": out.append(_system_block(render_content(message["content"]), tools, rs, namespace_descriptions)) elif role == "user": out += [START, "user", MESSAGE, render_content(message["content"]), EOT] elif role == "tool": tname = message.get("name") or "" if not tname: tcid = message.get("tool_call_id") tname = tcid or "" for m in messages: for tc in m.get("tool_calls") or []: if tcid is not None and tc.get("id") == tcid: tname = tc["function"]["name"] out += [START, f"tool {tname}", MESSAGE, f'\n', render_content(message["content"]), "\n", EOT] elif role == "assistant": if message.get("reasoning_content"): out += [START, "assistant to=self", MESSAGE, message["reasoning_content"], EOM] calls = message.get("tool_calls") if calls: for j, tc in enumerate(calls): fn = tc["function"] out += [START, f'assistant to={fn["name"]}', MESSAGE, render_atem(fn["name"], fn["arguments"]), end_token if j == len(calls) - 1 else EOM] else: recipient = message.get("recipient") or "user" end_turn = message.get("end_turn") if end_turn is None: end_turn = not (recipient and recipient != "user") out += [START, "assistant"] if recipient: out.append(f" to={recipient}") out += [MESSAGE, render_content(message["content"]), EOT if end_turn else EOM] else: raise ValueError(f"unknown role {role!r}") if add_generation_prompt: out += [START, "assistant"] return "".join(out)