File size: 6,887 Bytes
53d5fc6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
"""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
  <tool_call>
  {"name": "get_weather", "arguments": {"city": "Kraków"}}
  </tool_call><|im_end|>
  <|im_start|>tool
  <tool_response>
  {"temp_c": 3}
  </tool_response><|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<tools>\n")
TOOLS_FOOTER = ("</tools>\n\nTo call a function, reply with one or more blocks:\n<tool_call>\n"
                "{\"name\": \"<function name>\", \"arguments\": {<arguments as JSON>}}\n</tool_call>\n"
                "Function results come back in a tool message inside <tool_response></tool_response>. "
                "Use them to answer the user.")
CALL_RE = re.compile(r"<tool_call>\s*(\{.*?\})\s*</tool_call>", 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("<tool_call>\n" + json.dumps({"name": c["name"], "arguments": args}, ensure_ascii=False) + "\n</tool_call>")
        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 = "<tool_response>\n" + (m.get("content") or "") + "\n</tool_response>"
                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 "<tool_call>" in text and not calls and not errs:
        errs.append("unterminated_tool_call")
    return calls, errs