File size: 9,678 Bytes
6189eaf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
"""DEBUG_DIALOGUE format generator (multi-subject).

Multi-turn debugging conversations between a developer and an AI assistant.
Trains the model on interactive reasoning over time:
- Reading buggy code and error messages
- Hypothesis formation and revision
- Asking clarifying questions
- Iterating toward a fix

Output shape (as a 4-turn dialogue):
    **User:** [bug description + buggy ```{subject}``` code]
    **Assistant:** [diagnosis, proposed fix with reasoning]
    **User:** [tries fix, reports result - partial fix or new error]
    **Assistant:** [final fix + root cause explanation]

Seed selection:
  Looks for seeds/{subject}_debug_dialogue.json first.
  Falls back to seeds/{subject}.json.

Usage (from /workspace/pluto_run/):
    python generators/generate_debug_dialogue.py --subject python --limit 50
    python generators/generate_debug_dialogue.py --subject python --concurrent 96
"""

import argparse
import asyncio
import hashlib
import json
import os
import random
import time
from openai import AsyncOpenAI
from tqdm import tqdm


client = AsyncOpenAI(base_url="http://localhost:8000/v1", api_key="dummy")
MODEL = "qwen-coder"
SEED = 42
FORMAT = "debug_dialogue"


def build_system_prompt(subject):
    subject_name = subject.capitalize() if subject != "cpp" else "C++"
    return (
        f"You are creating a multi-turn debugging dialogue for a training corpus. "
        f"The dialogue is between a developer with a real bug and an AI assistant. "
        f"Show 4 turns where they work toward the fix. Use exactly this format:\n\n"
        f"**User:** [describes the bug they're seeing — what they expected, what "
        f"actually happened, error messages if any. Include the buggy {subject} "
        f"code in a ```{subject}``` code block]\n\n"
        f"**Assistant:** [diagnoses the problem; either asks one targeted "
        f"clarifying question, or proposes a fix with reasoning about the root "
        f"cause. Include corrected ```{subject}``` code if proposing a fix]\n\n"
        f"**User:** [reports what happened when they tried the fix — partial "
        f"success with a new error, or 'still broken' with a more specific symptom. "
        f"This makes the bug realistic; not all bugs reveal themselves at once]\n\n"
        f"**Assistant:** [final fix with explanation of the actual root cause "
        f"and why the first attempt was incomplete. Include the corrected "
        f"```{subject}``` code]\n\n"
        f"Make the bug subtle and realistic - the kind that takes a real engineer "
        f"two iterations to nail. Avoid trivial typos. Aim for bugs in: edge "
        f"cases, off-by-one errors, mutable state, race conditions, async "
        f"misuse, scope issues, type confusion, library API misuse, etc. "
        f"Length: 500-900 words. After the final assistant turn, STOP."
    )


PERSONAS = [
    "a senior engineer mentoring through debugging conversations",
    "an experienced developer with deep debugging instincts",
    "a code reviewer skilled at root-cause analysis",
    "a tech lead who walks juniors through bug reports",
    "a staff engineer who debugs by understanding intent first",
    "a careful debugger who asks before assuming",
    "a teaching engineer who explains the why behind every fix",
]

AUDIENCES = [
    "an intermediate developer asking for help",
    "a junior developer stuck on a real bug",
    "a self-taught programmer learning to debug systematically",
    "an engineer new to this codebase or library",
    "a developer learning debugging methodology",
]


def topic_hash(topic):
    return hashlib.sha256(topic.encode("utf-8")).hexdigest()[:16]


def load_done_topics(output_file):
    done = set()
    if os.path.exists(output_file):
        with open(output_file) as f:
            for line in f:
                try:
                    rec = json.loads(line)
                    if "topic" in rec:
                        done.add(topic_hash(rec["topic"]))
                except Exception:
                    pass
    return done


def resolve_seeds_path(subject):
    """Prefer subject-specific filtered seeds, fall back to general seeds."""
    filtered = f"seeds/{subject}_debug_dialogue.json"
    general = f"seeds/{subject}.json"
    if os.path.exists(filtered):
        print(f"Using filtered seeds: {filtered}")
        return filtered
    if os.path.exists(general):
        print(f"Using general seeds: {general}")
        return general
    raise SystemExit(
        f"No seeds for subject '{subject}'. "
        f"Create {filtered} or {general}."
    )


async def generate_one(topic, persona, audience, system_prompt, subject, sem):
    async with sem:
        prompt = (
            f"Persona: {persona}\n"
            f"Audience: {audience}\n\n"
            f"Topic: {topic}\n\n"
            f"Generate a 4-turn debugging dialogue around a realistic bug "
            f"related to this {subject} topic."
        )
        try:
            response = await client.chat.completions.create(
                model=MODEL,
                messages=[
                    {"role": "system", "content": system_prompt},
                    {"role": "user", "content": prompt},
                ],
                temperature=0.85,
                top_p=0.95,
                max_tokens=2000,
            )
            content = response.choices[0].message.content
            if not content or len(content) < 200:
                return {"_status": "too_short", "topic": topic}
            return {
                "_status": "ok",
                "format": FORMAT,
                "subject": subject,
                "topic": topic,
                "topic_hash": topic_hash(topic),
                "persona": persona,
                "audience": audience,
                "messages": [
                    {"role": "system", "content": system_prompt},
                    {"role": "user", "content": prompt},
                    {"role": "assistant", "content": content},
                ],
                "tokens": response.usage.completion_tokens,
                "char_count": len(content),
            }
        except Exception as e:
            return {"_status": "error", "_error": f"{type(e).__name__}: {e}", "topic": topic}


async def main(subject, limit, concurrent):
    seeds_file = resolve_seeds_path(subject)
    output_file = f"data/{subject}/{FORMAT}.jsonl"

    os.makedirs(os.path.dirname(output_file), exist_ok=True)

    system_prompt = build_system_prompt(subject)

    topics = json.load(open(seeds_file))
    rng = random.Random(SEED)
    rng.shuffle(topics)

    if limit:
        topics = topics[:limit]
        print(f"SMOKE TEST: limiting to {limit} samples")

    done = load_done_topics(output_file)
    if done:
        before = len(topics)
        topics = [t for t in topics if topic_hash(t) not in done]
        print(f"Resume: {len(done)} already on disk, {len(topics)} remaining")

    if not topics:
        print("Nothing to do.")
        return

    print(f"Subject:    {subject}")
    print(f"Format:     {FORMAT}")
    print(f"Generating: {len(topics)} samples (concurrency={concurrent})")
    print(f"Output:     {output_file}")
    print("=" * 70)

    sem = asyncio.Semaphore(concurrent)
    tasks = [
        generate_one(t, rng.choice(PERSONAS), rng.choice(AUDIENCES),
                     system_prompt, subject, sem)
        for t in topics
    ]

    written = 0
    failed = 0
    too_short = 0
    total_tokens = 0
    last_error = ""
    t_start = time.time()

    pbar = tqdm(
        total=len(topics),
        desc=f"{subject}/{FORMAT}",
        unit="sample",
        dynamic_ncols=True,
        smoothing=0.1,
        bar_format="{l_bar}{bar}| {n_fmt}/{total_fmt} [{elapsed}<{remaining}, {rate_fmt}{postfix}]",
    )

    with open(output_file, "a") as f:
        for coro in asyncio.as_completed(tasks):
            result = await coro
            status = result.get("_status", "error") if result else "error"

            if status == "ok":
                result.pop("_status", None)
                f.write(json.dumps(result, ensure_ascii=False) + "\n")
                f.flush()
                written += 1
                total_tokens += result.get("tokens", 0)
            elif status == "too_short":
                too_short += 1
            else:
                failed += 1
                last_error = result.get("_error", "")[:50] if result else ""

            elapsed = time.time() - t_start
            tok_per_sec = total_tokens / max(elapsed, 0.001)
            avg_tokens = total_tokens / max(written, 1)

            pbar.update(1)
            pbar.set_postfix_str(
                f"ok={written} fail={failed} short={too_short} "
                f"tok/s={tok_per_sec:,.0f} avg_tok={avg_tokens:.0f}"
                + (f" err={last_error}" if last_error else "")
            )

    pbar.close()

    elapsed = time.time() - t_start
    print("=" * 70)
    print(f"DONE in {elapsed/60:.1f} min")
    print(f"  Written:    {written}")
    print(f"  Failed:     {failed}")
    print(f"  Too-short:  {too_short}")
    if written:
        print(f"  Throughput: {written/elapsed:.2f} samples/s, "
              f"{total_tokens/elapsed:,.0f} tok/s")
    print(f"\nOutput: {output_file} "
          f"({sum(1 for _ in open(output_file))} total samples on disk)")


if __name__ == "__main__":
    p = argparse.ArgumentParser()
    p.add_argument("--subject", required=True)
    p.add_argument("--limit", type=int, default=None)
    p.add_argument("--concurrent", type=int, default=128)
    args = p.parse_args()
    asyncio.run(main(args.subject, args.limit, args.concurrent))