File size: 7,967 Bytes
f210f00
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Turns saved tau2 conversations into fine-tuning examples for Qwen 3.5 (thinking kept).

One example = the conversation up to one customer message, plus the agent's whole answer to it (its reasoning, tool
calls, tool results and final reply). Only the agent's own turns in that answer are trained on. Reasoning is kept for
those turns and left out of earlier ones, which is exactly how the model's chat template lays a conversation out.

build:  vc_sft.py build <out.jsonl> <results.json> [<results.json> ...]      (run with the tau2 environment's python)
check:  vc_sft.py check <examples.jsonl> <tokenizer dir or model name>         (needs transformers)
"""
import collections
import json
import random
import sys

WRITES = {"book_reservation", "cancel_reservation", "update_reservation_flights", "update_reservation_passengers",
          "update_reservation_baggages", "send_certificate"}
FALLBACK = "One moment please while I look into this for you."
HINT_WORDS = ("resolution step", "resolution_step", "<resolution", "steps provided", "provided steps")
ASSISTANT, END = "<|im_start|>assistant\n", "<|im_end|>\n"


def family_of(task):
    try:
        return json.loads(task["description"]["notes"])["family"]
    except Exception:
        return "official"


def to_chat(m):
    """One saved tau2 message as a chat-template message, with the model's own reasoning when it was recorded."""
    if m["role"] == "user":
        return {"role": "user", "content": m.get("content") or ""}
    if m["role"] == "tool":
        return {"role": "tool", "content": m.get("content") or ""}
    out = {"role": "assistant", "content": m.get("content") or ""}
    if m.get("tool_calls"):
        out["tool_calls"] = [{"type": "function", "function": {"name": c["name"], "arguments": c["arguments"]}} for c in m["tool_calls"]]
    choice = (((m.get("raw_data") or {}).get("choices") or [{}])[0].get("message") or {})
    thinking = choice.get("reasoning_content") or choice.get("reasoning")
    if thinking:
        out["reasoning_content"] = thinking.strip()
    return out


def build(paths, max_chains=3, family_cap=70, seed=5):
    from tau2.agent.llm_agent import AGENT_INSTRUCTION, SYSTEM_PROMPT
    from tau2.registry import registry

    env = registry.get_env_constructor("airline")()
    system = {"role": "system", "content": SYSTEM_PROMPT.format(domain_policy=env.get_policy(), agent_instruction=AGENT_INSTRUCTION)}
    tools = [t.openai_schema for t in env.get_tools()]
    rng = random.Random(seed)
    convs, skipped = [], collections.Counter()
    for path in paths:
        d = json.load(open(path))
        fam = {t["id"]: family_of(t) for t in d["tasks"]}
        for s in d["simulations"]:
            if abs(((s.get("reward_info") or {}).get("reward") or 0.0) - 1.0) > 1e-6:
                skipped["did not pass"] += 1
                continue
            msgs = [to_chat(m) for m in s.get("messages") or []]
            text = " ".join((m.get("content") or "") + " " + (m.get("reasoning_content") or "") for m in msgs if m["role"] == "assistant")
            if FALLBACK in text:
                skipped["used the holding sentence"] += 1
                continue
            if any(w in text.lower() for w in HINT_WORDS):
                skipped["mentions hints"] += 1
                continue
            convs.append((fam.get(s["task_id"], "official"), s["task_id"], s.get("trial"), msgs))
    rng.shuffle(convs)
    kept, per_family = [], collections.Counter()
    for fam, tid, trial, msgs in convs:
        key, cap = (fam, family_cap) if fam != "official" else ("official task %s" % tid, 6)   # benchmark tasks: six runs each at most
        if per_family[key] >= cap:
            skipped["over the family cap"] += 1
            continue
        per_family[key] += 1
        kept.append((fam, tid, trial, msgs))
    examples = []
    for fam, tid, trial, msgs in kept:
        users = [i for i, m in enumerate(msgs) if m["role"] == "user"]
        chains = []
        for n, i in enumerate(users):
            end = users[n + 1] if n + 1 < len(users) else len(msgs)
            if end - i > 1:                                   # the agent said or did something after this customer message
                acts = [c["function"]["name"] for m in msgs[i + 1:end] for c in m.get("tool_calls", [])]
                score = 2 * any(a in WRITES for a in acts) + rng.random()      # answers that change the database first
                chains.append((score, i, end))
        if not chains:
            continue
        last = max(chains, key=lambda c: c[1])
        picked = {last[1:]} | {c[1:] for c in sorted(chains, reverse=True)[:max_chains]}
        for i, end in sorted(picked)[-max_chains:] if len(picked) > max_chains else sorted(picked):
            history = [{k: v for k, v in m.items() if k != "reasoning_content"} for m in msgs[:i + 1]]
            examples.append({"id": "%s/%s/%d" % (tid, trial, i), "family": fam, "chain_start": i + 2,   # +1 for the system message
                             "messages": [system] + history + msgs[i + 1:end], "tools": tools})
    return examples, per_family, skipped


def render(example, tokenizer, max_tokens=16384):
    """Token ids and labels for one example: labels are -100 everywhere except the agent's turns in the answer."""
    msgs, start = example["messages"], example["chain_start"]
    full = tokenizer.apply_chat_template(msgs, tools=example["tools"], tokenize=False, add_generation_prompt=False)
    prefix = tokenizer.apply_chat_template(msgs[:start], tools=example["tools"], tokenize=False, add_generation_prompt=False)
    assert full.startswith(prefix), "the template laid the history out differently once the answer was added"
    spans, pos = [], len(prefix)
    while True:
        a = full.find(ASSISTANT, pos)
        if a < 0:
            break
        b = full.index(END, a) + len(END)
        spans.append((a + len(ASSISTANT), b))
        pos = b
    assert spans and len(spans) == sum(m["role"] == "assistant" for m in msgs[start:]), "agent turns not found in the rendered text"
    enc = tokenizer(full, add_special_tokens=False, return_offsets_mapping=True)
    ids, labels = enc["input_ids"], []
    for tok, (s, e) in zip(ids, enc["offset_mapping"]):
        labels.append(tok if any(s >= a and e <= b for a, b in spans) and e > s else -100)
    if len(ids) > max_tokens:
        return None
    return {"input_ids": ids, "labels": labels, "text": full, "spans": spans}


if __name__ == "__main__":
    mode = sys.argv[1]
    if mode == "build":
        out, paths = sys.argv[2], sys.argv[3:]
        examples, per_family, skipped = build(paths)
        with open(out, "w") as f:
            for e in examples:
                f.write(json.dumps(e) + "\n")
        print("conversations kept by family:", dict(sorted(per_family.items())))
        print("skipped:", dict(skipped))
        print("EXAMPLES:", len(examples), "from", sum(per_family.values()), "conversations ->", out)
    else:
        from transformers import AutoTokenizer
        tok = AutoTokenizer.from_pretrained(sys.argv[3])
        rows = [json.loads(l) for l in open(sys.argv[2])]
        lens, trained, dropped = [], [], 0
        for e in rows:
            r = render(e, tok)
            if r is None:
                dropped += 1
                continue
            lens.append(len(r["input_ids"]))
            trained.append(sum(x != -100 for x in r["labels"]))
        lens.sort()
        print("examples %d | too long %d | tokens median %d, p90 %d, max %d | trained-on tokens per example median %d | total tokens %.1fM" % (
            len(lens), dropped, lens[len(lens) // 2], lens[int(len(lens) * 0.9)], lens[-1], sorted(trained)[len(trained) // 2], sum(lens) / 1e6))
        r = render(rows[0], tok)
        shown = "".join(r["text"][a:b] for a, b in r["spans"])
        print("--- what the model is trained to write in the first example ---\n" + shown[:900])