Download data/gen_dialogues.py from RightNowAI/duplex-v0: direct link, hf CLI and curl.
- Browser
- Download file 7.8 kB
-
https://huggingface.co/RightNowAI/duplex-v0/resolve/main/data/gen_dialogues.py
- Command line
-
hf download hf://RightNowAI/duplex-v0/data/gen_dialogues.py
-
curl -L -o gen_dialogues.py https://huggingface.co/RightNowAI/duplex-v0/resolve/main/data/gen_dialogues.py
7.8 kB
| """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()) | |