Download code/scripts/fix.py from JagritGumber/shortlist: direct link, hf CLI and curl.
- Browser
- Download file 4.57 kB
-
https://huggingface.co/datasets/JagritGumber/shortlist/resolve/main/code/scripts/fix.py
- Command line
-
hf download hf://datasets/JagritGumber/shortlist/code/scripts/fix.py
-
curl -L -o fix.py https://huggingface.co/datasets/JagritGumber/shortlist/resolve/main/code/scripts/fix.py
4.57 kB
| """Have Beam diagnose a failed learnability check from the environment's source and write a fix. | |
| dotenvx run -- python scripts/fix.py connect4_env --evidence runs/fixes/connect4_env.evidence.md | |
| Beam sees the environment's server code and models plus the evidence (what the ladder measured). It answers | |
| with a diagnosis and the full new contents of each file it changes. The patched environment is written to | |
| runs/fixes/envs/<env>/ (a copy; the vendored repo is untouched), with Beam's reply and a diff, so the | |
| ladder can re-run against it with --envs-dir runs/fixes/envs. | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import difflib | |
| import json | |
| import re | |
| import shutil | |
| import sys | |
| from pathlib import Path | |
| sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) | |
| from shortlist import beam # noqa: E402 | |
| from shortlist.serve import OPENENV, ROOT # noqa: E402 | |
| SYSTEM = """You maintain reinforcement-learning environments for training language models. | |
| You are given an environment's source code and evidence from an automated learnability check. | |
| Find the root cause in the code, then fix it with the smallest change that makes the reward reflect the agent's skill. | |
| Keep the action and observation schemas, class names and the server API unchanged, so existing clients keep working. | |
| Answer in exactly this shape: | |
| DIAGNOSIS: | |
| <a short plain-English explanation of the root cause, naming the file and lines> | |
| FIX: | |
| <one or two sentences on what you changed> | |
| Then, for every file you change, its complete new contents: | |
| ### FILE: <path relative to the environment folder> | |
| ```python | |
| <complete file> | |
| ```""" | |
| def gather(env_dir: Path) -> dict[str, str]: | |
| files = {} | |
| for path in sorted(env_dir.rglob("*.py")): | |
| rel = path.relative_to(env_dir).as_posix() | |
| if "test" in rel or rel.startswith("."): | |
| continue | |
| files[rel] = path.read_text() | |
| return files | |
| def main() -> None: | |
| parser = argparse.ArgumentParser() | |
| parser.add_argument("env") | |
| parser.add_argument("--evidence", required=True) | |
| parser.add_argument("--effort", default="high") | |
| args = parser.parse_args() | |
| src = OPENENV / "envs" / args.env | |
| files = gather(src) | |
| evidence = Path(args.evidence).read_text() | |
| code = "\n\n".join(f"### FILE: {rel}\n```python\n{text}\n```" for rel, text in files.items()) | |
| messages = [ | |
| {"role": "system", "content": SYSTEM}, | |
| {"role": "user", "content": f"Environment: {args.env}\n\nEvidence from the learnability check:\n{evidence}\n\nSource:\n{code}"}, | |
| ] | |
| # This request has no tools, so it calls the client directly rather than beam.complete(). | |
| response = beam.client().chat.completions.create( | |
| model=beam.MODEL, messages=messages, reasoning_effort=args.effort, max_completion_tokens=beam.MAX_TOKENS[args.effort], | |
| ) | |
| beam.USAGE.add(response.usage) | |
| message = response.choices[0].message | |
| text = message.content or "" | |
| out = ROOT / "runs" / "fixes" | |
| out.mkdir(parents=True, exist_ok=True) | |
| (out / f"{args.env}.beam-reply.md").write_text(text) | |
| (out / f"{args.env}.beam-reasoning.md").write_text(getattr(message, "reasoning_content", "") or "") | |
| changed = {m.group(1).strip(): m.group(2) for m in re.finditer(r"### FILE: (.+?)\n```(?:python)?\n(.*?)\n```", text, re.S)} | |
| if not changed: | |
| print("Beam returned no file changes. Reply saved."); print(text[:2000]); return | |
| dest = out / "envs" / args.env | |
| if dest.exists(): | |
| shutil.rmtree(dest) | |
| shutil.copytree(src, dest, ignore=shutil.ignore_patterns("__pycache__", "*.egg-info")) | |
| diff = [] | |
| root = dest.resolve() | |
| for rel, new in changed.items(): | |
| # File paths come from model output: only write .py files that stay inside the patched copy. | |
| target = (dest / rel).resolve() | |
| if Path(rel).is_absolute() or not target.is_relative_to(root) or target.suffix != ".py": | |
| print(f"Refusing to write {rel!r}: outside the environment folder or not a .py file.") | |
| continue | |
| old = target.read_text() if target.exists() else "" | |
| target.write_text(new.rstrip() + "\n") | |
| diff += difflib.unified_diff(old.splitlines(True), (new.rstrip() + "\n").splitlines(True), f"a/envs/{args.env}/{rel}", f"b/envs/{args.env}/{rel}") | |
| (out / f"{args.env}.patch").write_text("".join(diff)) | |
| diagnosis = text.split("### FILE:")[0].strip() | |
| print(diagnosis) | |
| print(f"\nChanged: {list(changed)}\nPatched copy: {dest}\nUsage: {json.dumps(beam.USAGE.summary())}") | |
| if __name__ == "__main__": | |
| main() | |