"""Beam writes the ladder setup for a community environment from its README, schema and first observation. dotenvx run -- python scripts/setup_env.py --from-census runs/hub/sweep/census.jsonl --limit 20 For each Space it writes runs/hub/setups/__.json: how many steps an episode may take, how an episode is scored, what counts as solved and the maximum reward, each backed by a quote from the README, or left empty when the README doesn't say. The ladder reads these files (shortlist.suite.community), so adding an environment no longer needs a hand-written entry. """ from __future__ import annotations import argparse import json import sys from pathlib import Path import requests sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) from openenv.core.generic_client import GenericEnvClient # noqa: E402 from shortlist import beam # noqa: E402 from shortlist.serve import ROOT # noqa: E402 SETUPS = ROOT / "runs" / "hub" / "setups" SYSTEM = """You configure a test harness for a reinforcement-learning environment, using only what its README, action schema and first observation say. Answer with one JSON object and nothing else: { "task": "one plain sentence: what the agent must do", "max_steps": integer, how many actions a reasonable episode needs (at most 15), "score": "return" if the reward is paid at the end or summed over the episode, "mean_step" if every step is scored on its own, "max_score": number or null, the best episode score the README states or clearly implies, "solved_at": number or null, the episode score that means the task was fully solved, if the README defines one, "reset_kwargs": [ up to 3 objects of keyword arguments for reset() that select different tasks, e.g. {"seed": 1} or {"task_id": "easy"}; use [] if the README names none ], "evidence": "short quotes from the README supporting max_score, solved_at and reset_kwargs, or 'none'" } Never guess a number the README doesn't support: use null instead.""" def safe_name(space: str) -> str: return space.replace("/", "__") def gather(space: str, api_url: str) -> dict: readme = requests.get(f"https://huggingface.co/spaces/{space}/raw/main/README.md", timeout=30) text = readme.text if readme.ok else "" if text.startswith("---"): text = text.split("---", 2)[-1] schema = requests.get(api_url + "/schema", timeout=30).json().get("action", {}) with GenericEnvClient(base_url=api_url).sync() as env: obs = env.reset().observation or {} return {"readme": text.strip()[:12000], "schema": schema, "observation": json.dumps(obs, default=str)[:4000]} def write_setup(space: str, api_url: str, effort: str) -> dict: facts = gather(space, api_url) user = (f"Environment: {space}\n\nREADME:\n{facts['readme'] or '(no README)'}\n\nAction schema:\n{json.dumps(facts['schema'])[:4000]}" f"\n\nFirst observation after reset():\n{facts['observation']}") response = beam.client().chat.completions.create( model=beam.MODEL, messages=[{"role": "system", "content": SYSTEM}, {"role": "user", "content": user}], reasoning_effort=effort, max_completion_tokens=beam.MAX_TOKENS[effort], ) beam.USAGE.add(response.usage) text = response.choices[0].message.content or "" setup = None for start in range(len(text)): if text[start] == "{": try: setup = json.loads(text[start:text.rfind("}") + 1]) break except json.JSONDecodeError: continue if not isinstance(setup, dict): return {"space": space, "error": "Beam's reply had no JSON object", "reply": text[:500]} # Keep only well-formed values; anything else falls back to the harness default. clean = {"space": space, "api_url": api_url, "written_by": f"{beam.MODEL} ({effort} effort)", "task": str(setup.get("task", ""))[:300], "evidence": str(setup.get("evidence", ""))[:600]} steps = setup.get("max_steps") clean["max_steps"] = max(1, min(15, int(steps))) if isinstance(steps, (int, float)) else 10 clean["score"] = setup.get("score") if setup.get("score") in ("return", "mean_step") else "return" for key in ("max_score", "solved_at"): v = setup.get(key) clean[key] = float(v) if isinstance(v, (int, float)) and not isinstance(v, bool) else None kwargs = setup.get("reset_kwargs") clean["reset_kwargs"] = [k for k in kwargs if isinstance(k, dict)][:3] if isinstance(kwargs, list) else [] return clean def main() -> None: ap = argparse.ArgumentParser() ap.add_argument("--from-census", default="runs/hub/sweep/census.jsonl") ap.add_argument("--classes", default="passes floor checks,suspicious floor") ap.add_argument("--limit", type=int, default=20) ap.add_argument("--effort", default="low") args = ap.parse_args() SETUPS.mkdir(parents=True, exist_ok=True) rows = [json.loads(l) for l in Path(args.from_census).read_text().splitlines()] wanted = set(args.classes.split(",")) picks = sorted([r for r in rows if r["class"] in wanted and r.get("api_url")], key=lambda r: -r.get("likes", 0))[: args.limit] for r in picks: path = SETUPS / f"{safe_name(r['id'])}.json" if path.exists(): continue try: setup = write_setup(r["id"], r["api_url"], args.effort) except beam.DailyLimitReached: print("Daily Beam allowance used up; run again after 00:00 UTC.") break except Exception as error: # noqa: BLE001 setup = {"space": r["id"], "error": f"{type(error).__name__}: {error}"[:300]} setup["census_class"] = r["class"] path.write_text(json.dumps(setup, indent=2)) print(f"{r['id']:55s} steps {setup.get('max_steps')} max {setup.get('max_score')} solved {setup.get('solved_at')} " f"resets {len(setup.get('reset_kwargs', []))} {setup.get('error', '')[:80]}", flush=True) print(json.dumps({"beam_usage": beam.USAGE.summary()})) if __name__ == "__main__": main()