File size: 7,799 Bytes
f730521
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
155
156
"""Write two-speaker phone dialogues as text with an open LLM behind any
OpenAI-compatible endpoint (the runbook serves an Apache-2.0 model with vLLM on GPU 1).

Each line of the output is one dialogue with its cast (voices, speeds, split) and turns.
Markers the later steps rely on:
  [pause]              inside a caller turn: the caller stops mid-sentence, then goes on
  "interrupts": true   on a caller turn: spoken over the agent's previous turn
  "self_correction"    on a caller turn: kept for the statistics

  python -m data.gen_dialogues --base-url http://localhost:8001/v1 --model Qwen/Qwen3-32B \
      --num-dialogues 3000 --out data/out/dialogues.jsonl
"""
import argparse
import asyncio
import json
import random
import re
from pathlib import Path

import aiohttp

from data.scenarios import STYLES, TEST_VOICES, TRAIN_VOICES, split_scenarios

PROMPT = """Write one phone conversation between a CALLER and an AGENT (a helpful voice assistant).

Scenario: {domain}: the caller wants to {task}.
Caller style: {style}.
Length: {n_turns} turns. The {first} speaks first. Speakers strictly alternate.

Rules:
- Natural spoken English, the way people really talk on the phone. Mix short and long turns.
- No stage directions, no emojis, no markdown. No names of real people or real companies.
- Spell out every number and symbol in words ("twenty five dollars", never "$25").
- In {k_pause} caller turns, put the marker [pause] where the caller stops in the middle of a sentence to think and then continues the same sentence. The words before [pause] must not sound finished.
- In {k_corr} caller turns, the caller corrects themselves mid-sentence ("on Tuesday, no, sorry, Wednesday"). Set "self_correction": true on those turns.
- In {k_int} caller turns, the caller cuts in while the agent is still talking. Set "interrupts": true on those turns. The agent turn right before it must be long (at least thirty words), the caller's words must make sense as an interruption, and the agent's next turn responds to it.
- Agent turns that explain something run twenty to sixty words.

Return only JSON:
{{"turns": [{{"spk": "caller", "text": "...", "interrupts": false, "self_correction": false}}, {{"spk": "agent", "text": "..."}}]}}"""


def make_cast(i, n_total, seed):
    """Everything about dialogue i that is decided before the LLM writes it."""
    rng = random.Random(f"{seed}-{i}")
    train_s, test_s = split_scenarios(seed)
    split = "test" if i < round(n_total * 0.1) else "train"
    domain, task = rng.choice(test_s if split == "test" else train_s)
    caller, agent = rng.sample(TEST_VOICES if split == "test" else TRAIN_VOICES, 2)
    return {
        "id": f"{split}_{i:06d}", "split": split, "domain": domain, "task": task, "style": rng.choice(STYLES),
        "caller_voice": caller, "agent_voice": agent,
        "caller_speed": round(rng.uniform(0.9, 1.15), 2), "agent_speed": round(rng.uniform(0.95, 1.1), 2),
        "n_turns": rng.randint(8, 18), "first": rng.choice(["AGENT", "AGENT", "CALLER"]),
        "k_pause": rng.randint(1, 3), "k_corr": rng.randint(0, 1), "k_int": rng.randint(0, 2),
    }


def clean(raw):
    """Parse and validate the model's JSON. Returns the turn list, or None to retry."""
    raw = re.sub(r"<think>.*?</think>", "", raw, flags=re.S)
    m = re.search(r"\{.*\}", raw, flags=re.S)
    if not m:
        return None
    try:
        turns = json.loads(m.group(0))["turns"]
    except (ValueError, KeyError, TypeError):
        return None
    out = []
    for t in turns if isinstance(turns, list) else []:
        if not isinstance(t, dict) or t.get("spk") not in ("caller", "agent") or not isinstance(t.get("text"), str):
            return None
        text = re.sub(r"\((.*?)\)|\[(?!pause\])[^\]]*\]|[*_#`]", " ", t["text"])
        text = re.sub(r"\s+", " ", text).strip()
        if not text or re.search(r"\d", text) or len(text) > 900:
            return None
        if out and out[-1]["spk"] == t["spk"]:
            return None                                        # speakers must alternate
        if t["spk"] == "agent":
            text = text.replace("[pause]", " ").strip()
        else:
            parts = [p.strip() for p in text.split("[pause]")]
            if any(len(p.split()) < 2 for p in parts):          # a fragment too short to voice: drop the markers
                text = " ".join(p for p in parts if p)
        out.append({
            "spk": t["spk"], "text": text,
            "interrupts": bool(t.get("interrupts")) and t["spk"] == "caller" and bool(out),
            "self_correction": bool(t.get("self_correction")) and t["spk"] == "caller",
        })
    return out if len(out) >= 6 else None


async def one(session, args, cast, sem, extra):
    body = {
        "model": args.model, "temperature": 0.9, "max_tokens": 3000, "response_format": {"type": "json_object"},
        "messages": [
            {"role": "system", "content": "You write realistic two-speaker phone conversations and return strict JSON."},
            {"role": "user", "content": PROMPT.format(**cast)},
        ], **extra,
    }
    async with sem:
        for _ in range(4):
            try:
                async with session.post(args.base_url.rstrip("/") + "/chat/completions", json=body) as r:
                    r.raise_for_status()
                    raw = (await r.json())["choices"][0]["message"]["content"] or ""
            except (aiohttp.ClientError, asyncio.TimeoutError, KeyError, ValueError) as e:
                print(f"{cast['id']}: request failed: {e!r}")
                continue
            turns = clean(raw)
            if turns:
                return {**cast, "turns": turns}
    return None


async def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--base-url", required=True)
    ap.add_argument("--model", required=True)
    ap.add_argument("--out", required=True)
    ap.add_argument("--num-dialogues", type=int, default=3000, help="set from the measured mean dialogue length to land on 50 to 100 hours")
    ap.add_argument("--concurrency", type=int, default=64)
    ap.add_argument("--seed", type=int, default=0)
    ap.add_argument("--shard", type=int, default=0, help="write only dialogues with index % num-shards == shard (one process per LLM replica)")
    ap.add_argument("--num-shards", type=int, default=1)
    ap.add_argument("--api-key", default="none")
    ap.add_argument("--extra-body", default='{"chat_template_kwargs": {"enable_thinking": false}}')
    args = ap.parse_args()

    out = Path(args.out)
    out.parent.mkdir(parents=True, exist_ok=True)
    done = {json.loads(line)["id"] for line in out.open(encoding="utf-8")} if out.exists() else set()
    casts = [c for c in (make_cast(i, args.num_dialogues, args.seed) for i in range(args.num_dialogues) if i % args.num_shards == args.shard)
             if c["id"] not in done]
    print(f"{len(done)} already written, {len(casts)} to write")

    sem, ok, failed = asyncio.Semaphore(args.concurrency), 0, 0
    timeout = aiohttp.ClientTimeout(total=600)
    async with aiohttp.ClientSession(timeout=timeout, headers={"Authorization": f"Bearer {args.api_key}"}) as session:
        with out.open("a", encoding="utf-8") as f:
            for fut in asyncio.as_completed([one(session, args, c, sem, json.loads(args.extra_body)) for c in casts]):
                d = await fut
                if d:
                    f.write(json.dumps(d, ensure_ascii=False) + "\n")
                    f.flush()
                    ok += 1
                else:
                    failed += 1
                if (ok + failed) % 100 == 0:
                    print(f"written {ok}, failed {failed}")
    print(f"done: written {ok}, failed after retries {failed}")


if __name__ == "__main__":
    asyncio.run(main())