"""Slayer1B chat + tool-calling format (ChatML with Hermes-style tool blocks) and exact assistant-only label masks. The Slayer1B tokenizer (32,768 BPE) already contains <|endoftext|> (id 0, used as BOS/EOS by the native loader), <|im_start|> and <|im_end|>. The base model was never trained on them, so SFT teaches the protocol: <|endoftext|><|im_start|>system {system prompt}\n\n{TOOLS_BLOCK}<|im_end|> <|im_start|>user {text}<|im_end|> <|im_start|>assistant {"name": "get_weather", "arguments": {"city": "Kraków"}} <|im_end|> <|im_start|>tool {"temp_c": 3} <|im_end|> <|im_start|>assistant W Krakowie jest teraz 3°C.<|im_end|> Labels: only assistant content + its closing <|im_end|> are targets; role headers, system, user, tool turns and the newline after <|im_end|> are -100. Segments are tokenised separately at special-token boundaries, which is exactly how inference sees them (the prompt ends with "<|im_start|>assistant\\n", the model continues). Reasoning is never rendered (final answers only). """ from __future__ import annotations import json import re TOOLS_HEADER = ("# Tools\n\nYou can call functions to help with the user's request. Available functions:\n\n") TOOLS_FOOTER = ("\n\nTo call a function, reply with one or more blocks:\n\n" "{\"name\": \"\", \"arguments\": {}}\n\n" "Function results come back in a tool message inside . " "Use them to answer the user.") CALL_RE = re.compile(r"\s*(\{.*?\})\s*", re.S) class Fmt: def __init__(self, tokenizer): self.tok = tokenizer self.bos = tokenizer.token_to_id("<|endoftext|>") self.ims = tokenizer.token_to_id("<|im_start|>") self.ime = tokenizer.token_to_id("<|im_end|>") assert None not in (self.bos, self.ims, self.ime), "tokenizer lacks ChatML specials" self.nl = self.enc("\n") def enc(self, s: str) -> list[int]: return self.tok.encode(s, add_special_tokens=False).ids if s else [] # ------------------------------------------------------------------ text pieces @staticmethod def tools_block(tools: list[dict]) -> str: lines = [] for t in tools: params = t.get("parameters") if isinstance(params, str): try: params = json.loads(params) except json.JSONDecodeError: params = None lines.append(json.dumps({"name": t["name"], "description": t.get("description") or "", "parameters": params or {"type": "object", "properties": {}}}, ensure_ascii=False)) return TOOLS_HEADER + "\n".join(lines) + "\n" + TOOLS_FOOTER @staticmethod def call_text(calls: list[dict]) -> str: out = [] for c in calls: args = c["arguments"] if isinstance(args, str): args = json.loads(args) if args.strip() else {} out.append("\n" + json.dumps({"name": c["name"], "arguments": args}, ensure_ascii=False) + "\n") return "\n".join(out) def turns(self, messages: list[dict], tools: list[dict]) -> list[tuple[str, str, bool]]: """(role, text, trainable) turns. Consecutive tool messages merge into one tool turn.""" out = [] sys_txt = "\n\n".join((m["content"] or "").strip() for m in messages if m["role"] in ("system", "developer") and (m["content"] or "").strip()) if tools: sys_txt = (sys_txt + "\n\n" if sys_txt else "") + self.tools_block(tools) if sys_txt: out.append(("system", sys_txt, False)) for m in messages: r = m["role"] if r in ("system", "developer"): continue if r == "assistant": parts = [] if (m.get("content") or "").strip(): parts.append(m["content"].strip()) if m.get("tool_calls"): parts.append(self.call_text(m["tool_calls"])) out.append(("assistant", "\n".join(parts), bool(m.get("trainable", True)))) elif r == "tool": block = "\n" + (m.get("content") or "") + "\n" if out and out[-1][0] == "tool": out[-1] = ("tool", out[-1][1] + "\n" + block, False) else: out.append(("tool", block, False)) else: out.append(("user", m.get("content") or "", False)) return out # ------------------------------------------------------------------ tokens def render(self, messages: list[dict], tools: list[dict] | None = None, *, add_generation_prompt: bool = False): """Return (input_ids, labels). With add_generation_prompt the sequence ends with '<|im_start|>assistant\\n'.""" ids, labels = [self.bos], [-100] for role, text, train in self.turns(messages, tools or []): head = [self.ims] + self.enc(role + "\n") body = self.enc(text) + [self.ime] ids += head labels += [-100] * len(head) ids += body labels += body if (train and role == "assistant") else [-100] * len(body) ids += self.nl labels += [-100] * len(self.nl) if add_generation_prompt: head = [self.ims] + self.enc("assistant\n") ids += head labels += [-100] * len(head) return ids, labels def prompt_ids(self, messages, tools=None) -> list[int]: return self.render(messages, tools, add_generation_prompt=True)[0] def parse_calls(text: str) -> tuple[list[dict], list[str]]: """Extract tool calls from generated assistant text. Returns (calls, errors).""" calls, errs = [], [] for m in CALL_RE.finditer(text): try: obj = json.loads(m.group(1)) except json.JSONDecodeError as e: errs.append(f"invalid_json:{e.msg}") continue if not isinstance(obj, dict) or "name" not in obj: errs.append("missing_name") continue args = obj.get("arguments", {}) if isinstance(args, str): try: args = json.loads(args) except json.JSONDecodeError: errs.append("arguments_not_json") continue if not isinstance(args, dict): errs.append("arguments_not_object") continue calls.append({"name": obj["name"], "arguments": args}) if "" in text and not calls and not errs: errs.append("unterminated_tool_call") return calls, errs