File size: 4,568 Bytes
a2b0c04 | 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 | """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()
|