"""REFINEMENT format generator (multi-subject). Shape: bad code -> issues called out -> good code -> why each change. Structure: ## Problem one-line topic context ## Initial flawed but working code ## Issues 3-5 specific problems with bullets ## Refined improved code addressing every issue ## Why ties each change back to an issue Seed selection: Looks for seeds/{subject}_refinement.json first (filtered for refinement-friendly topics). Falls back to seeds/{subject}.json. Usage (from /workspace/pluto_run/): python generators/generate_refinement.py --subject python --limit 50 python generators/generate_refinement.py --subject python python generators/generate_refinement.py --subject python --concurrent 192 """ 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 = "refinement" def build_system_prompt(subject): subject_name = subject.capitalize() if subject != "cpp" else "C++" return ( f"You are a senior {subject_name} code reviewer creating a refactor " f"example for a training corpus. Show before-and-after code with the " f"specific issues called out. Use exactly this structure with these " f"section headers:\n\n" f"## Problem\n[one or two sentences stating what the code is supposed to do]\n\n" f"## Initial\n```{subject}\n[working but flawed code, 10-25 lines]\n```\n\n" f"## Issues\n[3-5 bullet points, each pointing at a real, substantive problem: " f"poor naming, missing error handling, O(n^2) when O(n) is possible, " f"non-idiomatic, fragile to edge cases, mutable default args, etc.]\n\n" f"## Refined\n```{subject}\n[improved code that fixes every issue]\n```\n\n" f"## Why\n[one paragraph tying each change back to its issue]\n\n" f"Length: 600-1200 words. The flaws must be real (not contrived) and the " f"refined version must measurably improve correctness, performance, " f"readability, or robustness. Stop after the Why section." ) PERSONAS = [ "a senior backend engineer who emphasizes correctness", "a refactoring specialist with deep code-review experience", "a tech lead writing internal style-guide examples", "a library maintainer reviewing a contributor's PR", "a staff engineer mentoring through critique", "a code reviewer with a track record of catching subtle bugs", "a performance engineer who sees the hot path first", "a principal engineer documenting common anti-patterns", ] AUDIENCES = [ "an intermediate developer learning to review code", "a junior developer wanting to write idiomatic code", "an experienced engineer studying anti-patterns", "a senior engineer using these as teaching material", "a self-taught developer leveling up code quality", ] 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}_refinement.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"Write a refactor example for this {subject} topic: {topic}" ) try: response = await client.chat.completions.create( model=MODEL, messages=[ {"role": "system", "content": system_prompt}, {"role": "user", "content": prompt}, ], temperature=0.8, top_p=0.95, max_tokens=2200, ) content = response.choices[0].message.content if not content or len(content) < 100: 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))