"""INFILLING_LONG format generator. Variant of infilling that produces 60-120 line code samples instead of 30-60. Teaches the model to use distant code as context — critical for IDE autocomplete where the model needs to predict middle from far-apart prefix/suffix. Output shape: a single ```{subject}``` block with a substantial multi-component code sample. Multiple functions, possibly a class + helpers + main usage, with cross-references between them. Seed selection: Looks for seeds/{subject}_infilling_long.json first. Falls back to seeds/{subject}_infilling.json then seeds/{subject}.json. Usage (from /workspace/pluto_run/): python generators/generate_infilling_long.py --subject python --limit 50 python generators/generate_infilling_long.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 = "infilling_long" def build_system_prompt(subject): subject_name = subject.capitalize() if subject != "cpp" else "C++" return ( f"Output a SUBSTANTIAL {subject_name} code sample. The code MUST be " f"between 70 and 130 lines. This is a hard requirement. Short answers " f"will be rejected.\n\n" f"Format: a single ```{subject}``` code block with no prose around it.\n\n" f"Required components (all of these):\n" f" - 5+ imports at the top\n" f" - At least one class with __init__ and 2-3 methods (15-25 lines)\n" f" - At least 3 module-level helper functions (10-20 lines each)\n" f" - A main() function or `if __name__ == \"__main__\":` block " f"that demonstrates usage (10-15 lines)\n" f" - Realistic error handling (try/except blocks, validation)\n" f" - Type hints on every function\n" f" - Docstrings on every function and method\n" f" - Cross-references: helpers called from class methods, class used in main\n\n" f"Style: production-grade {subject_name}, not toy code. Include realistic " f"data validation, edge case handling, and logging where appropriate. " f"Use real library APIs.\n\n" f"NO `pass`, NO `...`, NO TODO comments, NO placeholder code.\n\n" f"After the closing ``` of the code block, STOP. NO prose around it." ) PERSONAS = [ "a senior backend engineer writing production-grade code", "a library author building reference implementations", "an experienced developer building real-world utilities", "a staff engineer writing internal tooling", "a tooling engineer building developer infrastructure", "a careful engineer who handles edge cases properly", "a systems programmer writing performance-aware code", "a tech lead writing canonical example modules", ] AUDIENCES = [ "an intermediate developer studying complete patterns", "an experienced engineer learning from canonical examples", "a senior reviewer studying clean implementations", "a developer learning from realistic code samples", ] 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): candidates = [ f"seeds/{subject}_infilling_long.json", f"seeds/{subject}_infilling.json", f"seeds/{subject}.json", ] for path in candidates: if os.path.exists(path): print(f"Using seeds: {path}") return path raise SystemExit(f"No seeds found in any of: {candidates}") 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"Write a substantial {subject} code sample (60-120 lines) " f"with multiple cross-referenced components." ) try: response = await client.chat.completions.create( model=MODEL, messages=[ {"role": "system", "content": system_prompt}, {"role": "user", "content": prompt}, ], temperature=0.7, top_p=0.95, max_tokens=2800, ) 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: topics = [t for t in topics if topic_hash(t) not in done] print(f"Resume: {len(done)} on disk, {len(topics)} remaining") if not topics: print("Nothing to do.") return print(f"Subject: {subject} 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 = failed = too_short = 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 tps = total_tokens / max(elapsed, 0.001) avg = total_tokens / max(written, 1) pbar.update(1) pbar.set_postfix_str(f"ok={written} fail={failed} short={too_short} " f"tok/s={tps:,.0f} avg_tok={avg:.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} | Failed: {failed} | Too-short: {too_short}") if written: print(f" Throughput: {written/elapsed:.2f} samples/s, {total_tokens/elapsed:,.0f} tok/s") print(f"\nOutput: {output_file} ({sum(1 for _ in open(output_file))} total)") 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=96) args = p.parse_args() asyncio.run(main(args.subject, args.limit, args.concurrent))