AdithyaSK HF Staff commited on
Commit
c8c36ec
·
verified ·
1 Parent(s): 2f149fb

Serve RetroEnv snapshot 350672d1218e

Browse files
Files changed (47) hide show
  1. .dockerignore +7 -0
  2. Dockerfile +29 -0
  3. README.md +120 -4
  4. core/pyproject.toml +21 -0
  5. core/retroenv/__init__.py +9 -0
  6. core/retroenv/adapters.py +379 -0
  7. core/retroenv/benchmark.py +99 -0
  8. core/retroenv/chemistry.py +280 -0
  9. core/retroenv/classes.py +478 -0
  10. core/retroenv/corpus.py +310 -0
  11. core/retroenv/disconnections.py +420 -0
  12. core/retroenv/environment.py +311 -0
  13. core/retroenv/evalsets.py +167 -0
  14. core/retroenv/graph.py +285 -0
  15. core/retroenv/leakage.py +77 -0
  16. core/retroenv/models.py +189 -0
  17. core/retroenv/reactions.py +274 -0
  18. core/retroenv/retrieval.py +330 -0
  19. core/retroenv/serving.py +387 -0
  20. core/retroenv/store.py +98 -0
  21. core/retroenv/tools.py +219 -0
  22. core/retroenv/training.py +146 -0
  23. core/retroenv/verifier.py +405 -0
  24. openenv/Dockerfile +29 -0
  25. openenv/README.md +126 -0
  26. openenv/corpus-manifest.json +115 -0
  27. openenv/deploy.py +135 -0
  28. openenv/openenv.yaml +16 -0
  29. openenv/prepare.py +203 -0
  30. openenv/pyproject.toml +32 -0
  31. openenv/retroenv_openenv/__init__.py +1 -0
  32. openenv/retroenv_openenv/agent.py +287 -0
  33. openenv/retroenv_openenv/agent_anthropic.py +208 -0
  34. openenv/retroenv_openenv/agent_reference.py +587 -0
  35. openenv/retroenv_openenv/agent_responses.py +167 -0
  36. openenv/retroenv_openenv/client.py +260 -0
  37. openenv/retroenv_openenv/config.py +107 -0
  38. openenv/retroenv_openenv/environment.py +260 -0
  39. openenv/retroenv_openenv/molecule3d.py +128 -0
  40. openenv/retroenv_openenv/render.py +285 -0
  41. openenv/retroenv_openenv/server.py +45 -0
  42. openenv/retroenv_openenv/static/3Dmol-LICENSE.txt +90 -0
  43. openenv/retroenv_openenv/static/3Dmol-min.js +0 -0
  44. openenv/retroenv_openenv/static/3Dmol-min.js.LICENSE.txt +5 -0
  45. openenv/retroenv_openenv/ui.py +389 -0
  46. openenv/rollout.py +89 -0
  47. openenv/start.sh +7 -0
.dockerignore ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ **/__pycache__
2
+ **/*.egg-info
3
+ **/.pytest_cache
4
+ **/.venv
5
+ **/.env
6
+ openenv/tests
7
+ openenv/prepared
Dockerfile ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Build context: envs/retro_route (core/ and openenv/ side by side), which is
2
+ # also the layout deploy.py uploads to a Space.
3
+ # docker build -f openenv/Dockerfile -t retroenv .
4
+ FROM python:3.12-slim
5
+ # The serving index stores RDKit fingerprints and canonical SMILES; the same RDKit lets the
6
+ # server use them as built. Another version still works, but recomputes them at startup.
7
+ ARG RDKIT_VERSION=2026.3.6
8
+ ENV PYTHONUNBUFFERED=1 PIP_NO_CACHE_DIR=1 HOME=/home/user \
9
+ PORT=8000 ENABLE_WEB_INTERFACE=true MAX_CONCURRENT_ENVS=64 \
10
+ RETROENV_CORPUS_MANIFEST=/app/openenv/corpus-manifest.json \
11
+ RETROENV_BUCKET_ROOT=/data \
12
+ RETROENV_PREPARED_DIR=/home/user/prepared
13
+ # RDKit's molecule drawing (the playground) links against X11 render libraries.
14
+ RUN apt-get update && apt-get install -y --no-install-recommends \
15
+ libxrender1 libxext6 libexpat1 libfreetype6 libfontconfig1 \
16
+ && rm -rf /var/lib/apt/lists/*
17
+ WORKDIR /app
18
+ COPY core /app/core
19
+ COPY openenv /app/openenv
20
+ RUN pip install "rdkit==${RDKIT_VERSION}" /app/core /app/openenv \
21
+ && useradd --create-home --uid 1000 user \
22
+ && chown -R user:user /app
23
+ USER user
24
+ EXPOSE 8000
25
+ HEALTHCHECK --interval=30s --timeout=5s --start-period=120s \
26
+ CMD python -c "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8000/health')"
27
+ # The image holds code and the pinned corpus-manifest.json only. At startup prepare.py takes
28
+ # the snapshot from the bucket mounted at /data, or downloads it when nothing is mounted.
29
+ CMD ["bash", "/app/openenv/start.sh"]
README.md CHANGED
@@ -1,10 +1,126 @@
1
  ---
2
- title: Retroenv
3
- emoji: 📊
4
  colorFrom: gray
5
- colorTo: pink
6
  sdk: docker
 
 
7
  pinned: false
 
 
8
  ---
9
 
10
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
+ title: RetroEnv
3
+ emoji: ⚗️
4
  colorFrom: gray
5
+ colorTo: green
6
  sdk: docker
7
+ app_port: 8000
8
+ base_path: /web
9
  pinned: false
10
+ tags: [openenv, chemistry, retrosynthesis, tool-use]
11
+ short_description: Plan retrosynthesis routes with verifier-backed rewards.
12
  ---
13
 
14
+ # RetroEnv: OpenEnv server
15
+
16
+ An agent gets a target molecule and works back to purchasable starting materials. It uses tools to inspect molecules, search a fixed stock and training precedents, and check disconnections. It ends the episode by submitting molecule/reaction trees with `emit_routes`, and the verifier judges every step against a frozen reaction library; matching the patent route only adds a bonus.
17
+
18
+ The same server is used for training, evaluation and the browser playground at `/web`.
19
+
20
+ ## Read the code
21
+
22
+ - [`retroenv_openenv/environment.py`](retroenv_openenv/environment.py): the MCP tools, the Task API, `reset`, and the terminal reward.
23
+ - [`retroenv_openenv/client.py`](retroenv_openenv/client.py): `RetroEnvClient` for one episode per WebSocket session, and `RemoteRetroRouteEnv` for TRL's `environment_factory`.
24
+ - [`retroenv_openenv/agent.py`](retroenv_openenv/agent.py), [`agent_anthropic.py`](retroenv_openenv/agent_anthropic.py), [`agent_responses.py`](retroenv_openenv/agent_responses.py): model loops for OpenAI-compatible chat, the Claude Messages API and the OpenAI Responses API.
25
+ - [`retroenv_openenv/ui.py`](retroenv_openenv/ui.py): the playground.
26
+ - [`../core/retroenv`](../core/retroenv): chemistry, stock search, tasks and the verifier. Every front-end shares it.
27
+
28
+ ## The episode
29
+
30
+ | Step | What happens |
31
+ |---|---|
32
+ | `reset(split, index)` | Returns the prompt, target, depth budget, route count, constraints and tool names. It never returns known routes, patents or the stock list. |
33
+ | tool calls | MCP `call_tool`. Up to 32 calls per episode (`RETROENV_MAX_TOOL_CALLS`); `emit_routes` always stays available. |
34
+ | `emit_routes(submission)` | Scores the trees. That step returns `done=True` with the dense reward, once. |
35
+
36
+ | Tool | Answers from |
37
+ |---|---|
38
+ | `inspect_molecule`, `pubchem_lookup` | RDKit on the given SMILES |
39
+ | `stock_retrieve` | The task's stock (excluded building blocks absent): exact, InChIKey, class, SMARTS or similarity search, capped at 20 results |
40
+ | `reaction_precedent_search`, `search_literature`, `reaction_conditions_search` | Train-visible corpus reactions only |
41
+ | `validate_disconnection` | Train-visible reactions and frequent templates, never this task's hidden routes. Removed by `RETROENV_TOOLSET=unaided`. |
42
+ | `reaction_class_lookup` | The verifier's own reaction classifier |
43
+ | `emit_routes` | The verifier |
44
+
45
+ The Task API lists splits and public task rows without references: `GET /retro_route/splits`, and `POST /retro_route/task`, `/tasks`, `/task_range` and `/num_tasks`. The API docs are at `/docs`.
46
+
47
+ ## Data and splits
48
+
49
+ The server serves a pinned snapshot of [LiteFold/RetroEnv](https://huggingface.co/datasets/LiteFold/RetroEnv)
50
+ from the public bucket [FineEnvs/retroenv-bucket](https://huggingface.co/buckets/FineEnvs/retroenv-bucket).
51
+ `corpus-manifest.json`, beside the server code, pins it: the release revision, the serving index and the
52
+ SHA-256 of every file a server reads.
53
+
54
+ | Split | Tasks | Use |
55
+ |---|---:|---|
56
+ | `train` | 75,224 | RL rollouts |
57
+ | `dev` | 1,079 | checkpoint selection |
58
+ | `test_id` | 1,083 | unseen targets, training distribution |
59
+ | `test_hard` | 1,119 | longer, novel or rarer chemistry |
60
+ | `final_eval` | 50 | 17 easy, 17 medium, 16 hard from the two test splits (`dataset/build_final_eval.py`) |
61
+
62
+ `final_eval` names tasks of the test splits, so they score exactly as there.
63
+
64
+ ## Run locally
65
+
66
+ From the project folder (`09-retroenv`):
67
+
68
+ ```bash
69
+ uv sync --extra dev --extra eval
70
+ uv run bash envs/retro_route/openenv/start.sh
71
+ ```
72
+
73
+ `start.sh` runs `prepare.py`, which downloads the pinned snapshot from the bucket (about 115 MB,
74
+ once), checks every file's SHA-256, and starts the server; a restart reuses the checked files.
75
+ Startup then takes about 10 s. To serve a local release directory without an index instead:
76
+
77
+ ```bash
78
+ RETROENV_BENCHMARK_DIR=data/release/RetroEnv-RL uv run uvicorn retroenv_openenv.server:app --port 8000
79
+ ```
80
+
81
+ Open <http://localhost:8000/web/> for the playground. Its Plan tab works the way the task does: pick
82
+ the molecule still to make, take a cut the rule library proposes (or type one), check it and its
83
+ pieces with the real tools, and add it to a route drawn as it grows; "Fill from the plan" turns that
84
+ route into the `emit_routes` submission. Each molecule is drawn in 2D and, from an RDKit conformer,
85
+ in 3D (vendored [3Dmol.js](https://3dmol.csb.pitt.edu/), so it works offline). To run one model
86
+ episode against the server:
87
+
88
+ ```bash
89
+ uv run python envs/retro_route/openenv/rollout.py --server http://127.0.0.1:8000 \
90
+ --split final_eval --index 0 --provider anthropic --model claude-opus-5-5
91
+ ```
92
+
93
+ ## Docker and Spaces
94
+
95
+ The image holds code and `corpus-manifest.json` only. On a Space the bucket is mounted read-only at
96
+ `/data` and `prepare.py` copies the snapshot from there; with nothing mounted it downloads it.
97
+
98
+ ```bash
99
+ python deploy.py --stage-only --stage-dir /tmp/retroenv-space
100
+ docker build -t retroenv /tmp/retroenv-space
101
+ docker run --rm -p 8000:8000 retroenv # downloads the pinned snapshot
102
+ ```
103
+
104
+ [FineEnvs/retroenv](https://huggingface.co/spaces/FineEnvs/retroenv) is deployed with:
105
+
106
+ ```bash
107
+ python deploy.py --repo FineEnvs/retroenv --public
108
+ ```
109
+
110
+ `deploy.py` refuses to deploy unless every file the manifest names is already in the bucket, mounts
111
+ the bucket, and sets the variables below. A new snapshot comes from `dataset/publish_bucket.py`,
112
+ which also rewrites `corpus-manifest.json`.
113
+
114
+ | Variable | Default | Meaning |
115
+ |---|---|---|
116
+ | `RETROENV_CORPUS_MANIFEST` | `corpus-manifest.json` here | The serving snapshot to fetch and check |
117
+ | `RETROENV_BUCKET_ROOT` | `/data` in the image | A mounted copy of the bucket; files missing there are downloaded |
118
+ | `RETROENV_BUCKET_ID` | the manifest's | The bucket to download from, if it was renamed |
119
+ | `RETROENV_PREPARED_DIR` | `prepared` | Where the checked snapshot is kept between restarts |
120
+ | `RETROENV_BENCHMARK_DIR` | none | A local release or prepared directory, used as is |
121
+ | `RETROENV_TASKS_REPO` | none | A release dataset `org/name[@revision]`, served without an index |
122
+ | `RETROENV_TOOLSET` | `full` | `unaided` removes `validate_disconnection` (an ablation) |
123
+ | `RETROENV_MAX_TOOL_CALLS` | `32` | Tool budget per episode |
124
+ | `RETROENV_DEFAULT_SPLIT` | `train` | Split used by a reset that names none |
125
+ | `MAX_CONCURRENT_ENVS` | `64` | WebSocket sessions per process |
126
+ | `ENABLE_WEB_INTERFACE` | `true` | Mount the playground at `/web` |
core/pyproject.toml ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [build-system]
2
+ requires = ["setuptools>=69", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "retroenv-core"
7
+ version = "0.3.0"
8
+ description = "RetroEnv domain logic: RDKit chemistry, stock search, tasks, verifier, and the tool session"
9
+ requires-python = ">=3.11"
10
+ dependencies = ["rdkit>=2024.3.5", "rdchiral>=1.1", "numpy>=1.26"]
11
+
12
+ [project.optional-dependencies]
13
+ ord = ["ord-schema>=0.3", "pyarrow>=15"]
14
+ sources = ["ord-schema>=0.3", "pyarrow>=15", "py7zr>=0.22"]
15
+
16
+ [project.scripts]
17
+ retroenv-build-corpus = "retroenv.corpus:main"
18
+ retroenv-prepare-source = "retroenv.adapters:main"
19
+
20
+ [tool.setuptools.packages.find]
21
+ include = ["retroenv*"]
core/retroenv/__init__.py ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ """RetroEnv: dataset and environment primitives for verifiable retrosynthesis."""
2
+
3
+ from .benchmark import Benchmark, load_benchmark
4
+ from .environment import RetroRouteSession
5
+ from .store import TaskStore
6
+ from .verifier import RouteVerifier
7
+
8
+ __all__ = ["Benchmark", "RetroRouteSession", "RouteVerifier", "TaskStore", "load_benchmark"]
9
+ __version__ = "0.3.0"
core/retroenv/adapters.py ADDED
@@ -0,0 +1,379 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Stream downloaded source formats into RetroEnv's flat normalization contract."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import csv
7
+ import io
8
+ import json
9
+ import sys
10
+ import tempfile
11
+ import zipfile
12
+ from pathlib import Path
13
+ from typing import Any, Iterable, Iterator
14
+
15
+ from .chemistry import audit_atom_mapping
16
+
17
+ SOURCE_META = {
18
+ "crd": ("crd-1976-2024", "CC-BY-4.0"),
19
+ "uspto_lowe": ("uspto-lowe-1976-2016", "CC0-1.0"),
20
+ "creed": ("creed", "CC-BY-NC-4.0"),
21
+ "frea": ("frea-rxnverif", "CC-BY-4.0"),
22
+ "ord": ("ord-data", "CC-BY-SA-4.0"),
23
+ "paroutes_v2": ("paroutes-v2-benchmark", "CC-BY-4.0"),
24
+ "uspto_llm": ("uspto-llm", "CC-BY-4.0"),
25
+ }
26
+
27
+
28
+ def adapt_crd(path: Path) -> Iterator[dict[str, Any]]:
29
+ archive = _one(path, "*.zip") if path.is_dir() else path
30
+ with zipfile.ZipFile(archive) as zipped:
31
+ names = [name for name in zipped.namelist() if not name.endswith("/")]
32
+ if len(names) != 1:
33
+ raise ValueError(f"expected one data file in {archive}, found {names}")
34
+ with zipped.open(names[0]) as binary:
35
+ text = io.TextIOWrapper(binary, encoding="utf-8", errors="strict")
36
+ for line_number, line in enumerate(text, 1):
37
+ reaction = line.strip()
38
+ if reaction:
39
+ yield {
40
+ "reaction_smiles": reaction,
41
+ "source_name": SOURCE_META["crd"][0],
42
+ "source_license": SOURCE_META["crd"][1],
43
+ "source_record_id": f"line-{line_number}",
44
+ "evidence_kind": "observed",
45
+ }
46
+
47
+
48
+ def adapt_frea(path: Path) -> Iterator[dict[str, Any]]:
49
+ csv_path = _one(path, "**/rxnverif_v*.csv") if path.is_dir() else path
50
+ with csv_path.open("r", encoding="utf-8", newline="") as handle:
51
+ for row_number, row in enumerate(csv.DictReader(handle), 1):
52
+ feasible = str(row.get("feasible", "")).strip() == "1"
53
+ method = row.get("method") or ("positive" if feasible else "generated_negative")
54
+ yield {
55
+ "reaction_smiles": f"{row['reactants']}>>{row['product']}",
56
+ "source_name": SOURCE_META["frea"][0],
57
+ "source_license": SOURCE_META["frea"][1],
58
+ "source_record_id": f"row-{row_number}",
59
+ "source_group_id": f"product:{row['product']}",
60
+ "evidence_kind": "observed" if feasible else "generated",
61
+ "annotations": {"feasible": feasible, "generation_method": method},
62
+ }
63
+
64
+
65
+ def adapt_creed(path: Path, *, release: str = "CREED-CCV") -> Iterator[dict[str, Any]]:
66
+ try:
67
+ import pyarrow.parquet as pq
68
+ except ImportError as exc:
69
+ raise RuntimeError("install the 'sources' extra to adapt CREED") from exc
70
+ release_dir = path / release if path.is_dir() else path
71
+ for parquet_path in sorted(release_dir.glob("*.parquet")):
72
+ parquet = pq.ParquetFile(parquet_path)
73
+ row_offset = 0
74
+ for batch in parquet.iter_batches(batch_size=1024, columns=["product_smiles", "reactant_candidates"]):
75
+ for local_index, row in enumerate(batch.to_pylist()):
76
+ product_group = f"{parquet_path.name}:{row_offset + local_index}"
77
+ for candidate_index, candidate in enumerate(row["reactant_candidates"] or []):
78
+ product = candidate.get("product_isomeric_smiles") or row["product_smiles"]
79
+ reactants = candidate.get("reactants_isomeric_smiles") or []
80
+ if not product or not reactants:
81
+ continue
82
+ score = candidate.get("chemcensor_score")
83
+ yield {
84
+ "reaction_smiles": f"{'.'.join(reactants)}>>{product}",
85
+ "source_name": SOURCE_META["creed"][0],
86
+ "source_license": SOURCE_META["creed"][1],
87
+ "source_record_id": f"{product_group}:{candidate_index}",
88
+ "source_group_id": product_group,
89
+ "evidence_kind": "generated",
90
+ "annotations": {
91
+ "release": release,
92
+ "chemcensor_score": score,
93
+ },
94
+ }
95
+ row_offset += batch.num_rows
96
+
97
+
98
+ def adapt_uspto_lowe(path: Path) -> Iterator[dict[str, Any]]:
99
+ try:
100
+ import py7zr
101
+ except ImportError as exc:
102
+ raise RuntimeError("install the 'sources' extra to adapt Lowe USPTO archives") from exc
103
+ archives = sorted(path.glob("*_smiles.7z")) if path.is_dir() else [path]
104
+ if not archives:
105
+ raise FileNotFoundError(f"no *_smiles.7z files under {path}")
106
+ for archive_path in archives:
107
+ with tempfile.TemporaryDirectory(prefix="retroenv-lowe-") as temporary:
108
+ with py7zr.SevenZipFile(archive_path, mode="r") as archive:
109
+ archive.extractall(temporary)
110
+ for extracted in sorted(Path(temporary).rglob("*")):
111
+ if not extracted.is_file():
112
+ continue
113
+ with extracted.open("r", encoding="utf-8", errors="replace") as handle:
114
+ for line_number, line in enumerate(handle, 1):
115
+ fields = line.rstrip("\n").split("\t")
116
+ reaction_index = next(
117
+ (index for index, value in enumerate(fields) if value.count(">") == 2),
118
+ None,
119
+ )
120
+ if reaction_index is None:
121
+ continue
122
+ reaction = fields[reaction_index]
123
+ tail = fields[reaction_index + 1 :]
124
+ patent = tail[0].strip() if tail else ""
125
+ year = next(
126
+ (int(value) for value in tail if value.isdigit() and 1970 <= int(value) <= 2030),
127
+ None,
128
+ )
129
+ yield {
130
+ "reaction_smiles": reaction,
131
+ "source_name": SOURCE_META["uspto_lowe"][0],
132
+ "source_license": SOURCE_META["uspto_lowe"][1],
133
+ "source_record_id": f"{archive_path.name}:{extracted.name}:{line_number}",
134
+ "source_group_id": patent or None,
135
+ "publication_year": year,
136
+ "evidence_kind": "observed",
137
+ }
138
+
139
+
140
+ def adapt_uspto_llm(path: Path, *, release: str = "single_step") -> Iterator[dict[str, Any]]:
141
+ """Stream mapped single-step or step-divided USPTO-LLM CSV from its zip."""
142
+ root = path if path.is_dir() else path.parent
143
+ if release == "single_step":
144
+ archive_path = root / "single_step.zip" if path.is_dir() else path
145
+ member = "single_step/HGAR/uspto_llm_atommap.csv"
146
+ elif release == "multi_step":
147
+ archive_path = root / "multi_step.zip" if path.is_dir() else path
148
+ member = "multi_step/uspto_multiple_step.csv"
149
+ else:
150
+ raise ValueError("USPTO-LLM release must be 'single_step' or 'multi_step'")
151
+ with zipfile.ZipFile(archive_path) as zipped:
152
+ if member not in zipped.namelist():
153
+ raise FileNotFoundError(f"{member!r} is absent from {archive_path}")
154
+ with zipped.open(member) as binary:
155
+ text = io.TextIOWrapper(binary, encoding="utf-8-sig", errors="strict", newline="")
156
+ for row_number, row in enumerate(csv.DictReader(text), 1):
157
+ record_id = str(row.get("id") or row.get("reaction_id") or f"row-{row_number}")
158
+ raw_reaction = str(row.get("rs>>ps") or row.get("reactants>>products") or "")
159
+ parts = raw_reaction.split(">")
160
+ if len(parts) == 2:
161
+ reaction = f"{parts[0]}>>{parts[1]}"
162
+ middle = ""
163
+ elif len(parts) == 3:
164
+ reaction = f"{parts[0]}>>{parts[2]}"
165
+ middle = parts[1]
166
+ else:
167
+ # Let the generic normalizer reject malformed chemistry with
168
+ # a source record attached instead of silently dropping it.
169
+ reaction = raw_reaction
170
+ middle = ""
171
+ tokens = record_id.split("-")
172
+ patent_id = "-".join(tokens[1:-1]) if len(tokens) >= 3 else record_id
173
+ year = int(tokens[0][:4]) if tokens and tokens[0][:4].isdigit() else None
174
+ conditions = {
175
+ key: value
176
+ for key, value in {
177
+ "solvents": row.get("solvents"),
178
+ "catalyst": row.get("catalyst"),
179
+ "temperature": row.get("temperature"),
180
+ "time": row.get("time"),
181
+ "multi_step_context": middle or None,
182
+ }.items()
183
+ if value not in (None, "", "[]")
184
+ }
185
+ yield {
186
+ "reaction_smiles": reaction,
187
+ "source_name": SOURCE_META["uspto_llm"][0],
188
+ "source_license": SOURCE_META["uspto_llm"][1],
189
+ "source_record_id": record_id,
190
+ "source_group_id": patent_id,
191
+ "publication_year": year,
192
+ "evidence_kind": "observed",
193
+ "conditions": conditions,
194
+ "annotations": {"release": release, "llm_extracted": True},
195
+ }
196
+
197
+
198
+ def adapt_paroutes_v2(path: Path, *, release: str = "n1") -> Iterator[dict[str, Any]]:
199
+ """Convert PaRoutes molecule/reaction trees to explicit provenance-backed routes."""
200
+ if release not in {"n1", "n5"}:
201
+ raise ValueError("PaRoutes release must be 'n1' or 'n5'")
202
+ route_path = path / f"ref_routes_{release}.json" if path.is_dir() else path
203
+ with route_path.open("r", encoding="utf-8") as handle:
204
+ routes = json.load(handle)
205
+ if not isinstance(routes, list):
206
+ raise ValueError(f"expected a route list in {route_path}")
207
+ for route_index, root in enumerate(routes):
208
+ route_id = f"paroutes-v2:{release}:{route_index}"
209
+ steps: list[dict[str, Any]] = []
210
+
211
+ def visit(molecule: dict[str, Any]) -> None:
212
+ if molecule.get("type") != "mol" or not molecule.get("smiles"):
213
+ raise ValueError(f"{route_id}: malformed molecule node")
214
+ reactions = [child for child in molecule.get("children") or [] if child.get("type") == "reaction"]
215
+ if not reactions:
216
+ return
217
+ if len(reactions) != 1:
218
+ raise ValueError(f"{route_id}: molecule node contains {len(reactions)} reaction alternatives")
219
+ reaction = reactions[0]
220
+ precursors = [
221
+ child for child in reaction.get("children") or [] if child.get("type") == "mol" and child.get("smiles")
222
+ ]
223
+ if not precursors:
224
+ raise ValueError(f"{route_id}: reaction has no precursor molecule nodes")
225
+ metadata = reaction.get("metadata") or {}
226
+ mapped_reaction = str(metadata.get("smiles") or "")
227
+ try:
228
+ mapping_status = audit_atom_mapping(mapped_reaction)["status"]
229
+ except Exception:
230
+ mapping_status = "unmapped"
231
+ steps.append(
232
+ {
233
+ "product": str(molecule["smiles"]),
234
+ "reactants": [str(precursor["smiles"]) for precursor in precursors],
235
+ "reaction_id": str(
236
+ metadata.get("reaction_hash") or metadata.get("ID") or f"{route_id}:step:{len(steps)}"
237
+ ),
238
+ "mapping_status": mapping_status,
239
+ }
240
+ )
241
+ for precursor in precursors:
242
+ visit(precursor)
243
+
244
+ visit(root)
245
+ if not steps:
246
+ raise ValueError(f"{route_id}: route contains no reaction steps")
247
+ yield {
248
+ "route_id": route_id,
249
+ "target_smiles": str(root["smiles"]),
250
+ "steps": steps,
251
+ "source": [
252
+ {
253
+ "name": SOURCE_META["paroutes_v2"][0],
254
+ "license": SOURCE_META["paroutes_v2"][1],
255
+ "record_id": f"{release}:{route_index}",
256
+ "group_id": route_id,
257
+ }
258
+ ],
259
+ "annotations": {"release": release, "source_format": "paroutes_tree"},
260
+ }
261
+
262
+
263
+ def adapt_ord(path: Path) -> Iterator[dict[str, Any]]:
264
+ """Adapt ORD protobuf-in-Parquet while preserving reaction roles and patent IDs."""
265
+ try:
266
+ from ord_schema.datasets import load_dataset
267
+ except ImportError as exc:
268
+ raise RuntimeError("install the 'sources' extra to adapt ORD") from exc
269
+ files = sorted(path.glob("data/**/*.parquet")) if path.is_dir() else [path]
270
+ for parquet_path in files:
271
+ dataset = load_dataset(str(parquet_path))
272
+ for row_number, reaction in enumerate(dataset.reactions, 1):
273
+ reactants: list[str] = []
274
+ reagents: list[str] = []
275
+ for reaction_input in reaction.inputs.values():
276
+ for component in reaction_input.components:
277
+ smiles = _compound_smiles(component)
278
+ if not smiles:
279
+ continue
280
+ role = _enum_name(component, "reaction_role")
281
+ (reactants if "REACTANT" in role else reagents).append(smiles)
282
+ products: list[str] = []
283
+ for outcome in reaction.outcomes:
284
+ for product in outcome.products:
285
+ compound = getattr(product, "compound", product)
286
+ smiles = _compound_smiles(compound)
287
+ if smiles:
288
+ products.append(smiles)
289
+ if not reactants or not products:
290
+ continue
291
+ patent = getattr(getattr(reaction, "provenance", None), "patent", None)
292
+ patent_id = _first_text_attr(patent, ("document_id", "patent_number", "title"))
293
+ yield {
294
+ "reactants": reactants,
295
+ "reagents": reagents,
296
+ "products": products,
297
+ "source_name": SOURCE_META["ord"][0],
298
+ "source_license": SOURCE_META["ord"][1],
299
+ "source_record_id": str(getattr(reaction, "reaction_id", "") or f"{parquet_path.name}:{row_number}"),
300
+ "source_group_id": patent_id,
301
+ "evidence_kind": "observed",
302
+ "annotations": {
303
+ "ord_dataset_file": str(parquet_path.relative_to(path) if path.is_dir() else parquet_path.name)
304
+ },
305
+ }
306
+
307
+
308
+ def _compound_smiles(compound: Any) -> str | None:
309
+ for identifier in getattr(compound, "identifiers", ()):
310
+ name = _enum_name(identifier, "type")
311
+ if "SMILES" in name and getattr(identifier, "value", ""):
312
+ return str(identifier.value)
313
+ return None
314
+
315
+
316
+ def _enum_name(message: Any, field: str) -> str:
317
+ try:
318
+ descriptor = message.DESCRIPTOR.fields_by_name[field]
319
+ value = getattr(message, field)
320
+ return descriptor.enum_type.values_by_number[value].name
321
+ except Exception:
322
+ return ""
323
+
324
+
325
+ def _first_text_attr(value: Any, names: Iterable[str]) -> str | None:
326
+ if value is None:
327
+ return None
328
+ for name in names:
329
+ result = getattr(value, name, None)
330
+ if result:
331
+ return str(result)
332
+ return None
333
+
334
+
335
+ def _one(root: Path, pattern: str) -> Path:
336
+ matches = sorted(root.glob(pattern))
337
+ if len(matches) != 1:
338
+ raise ValueError(f"expected exactly one {pattern!r} under {root}, found {len(matches)}")
339
+ return matches[0]
340
+
341
+
342
+ def write_jsonl(rows: Iterable[dict[str, Any]], output: Path, limit: int | None = None) -> int:
343
+ output.parent.mkdir(parents=True, exist_ok=True)
344
+ count = 0
345
+ with output.open("w", encoding="utf-8") as handle:
346
+ for row in rows:
347
+ if limit is not None and count >= limit:
348
+ break
349
+ handle.write(json.dumps(row, sort_keys=True, separators=(",", ":")) + "\n")
350
+ count += 1
351
+ return count
352
+
353
+
354
+ def main(argv: list[str] | None = None) -> int:
355
+ parser = argparse.ArgumentParser(description=__doc__)
356
+ parser.add_argument("source", choices=sorted(SOURCE_META))
357
+ parser.add_argument("input", type=Path)
358
+ parser.add_argument("output", type=Path)
359
+ parser.add_argument("--release", help="CREED release or USPTO-LLM mode")
360
+ parser.add_argument("--limit", type=int)
361
+ args = parser.parse_args(argv)
362
+ if args.limit is not None and args.limit < 1:
363
+ parser.error("--limit must be positive")
364
+ adapters = {
365
+ "crd": lambda: adapt_crd(args.input),
366
+ "frea": lambda: adapt_frea(args.input),
367
+ "creed": lambda: adapt_creed(args.input, release=args.release or "CREED-CCV"),
368
+ "uspto_lowe": lambda: adapt_uspto_lowe(args.input),
369
+ "uspto_llm": lambda: adapt_uspto_llm(args.input, release=args.release or "single_step"),
370
+ "paroutes_v2": lambda: adapt_paroutes_v2(args.input, release=args.release or "n1"),
371
+ "ord": lambda: adapt_ord(args.input),
372
+ }
373
+ count = write_jsonl(adapters[args.source](), args.output, args.limit)
374
+ print(json.dumps({"source": args.source, "rows": count, "output": str(args.output)}))
375
+ return 0
376
+
377
+
378
+ if __name__ == "__main__":
379
+ sys.exit(main())
core/retroenv/benchmark.py ADDED
@@ -0,0 +1,99 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Load one built release directory: tasks, stock, reaction library and precedent corpus.
2
+
3
+ Layout (the Hugging Face dataset repo root)::
4
+
5
+ manifest.json split rules and build provenance
6
+ tasks-private/<split>.jsonl tasks with hidden known routes
7
+ stocks/<stock_id>.smi building blocks
8
+ library/reactions.jsonl.gz corpus reactions (stereo-free keys, class, patents, visibility)
9
+ library/templates.json retro-template counts from every corpus reaction
10
+ library/templates-visible.json retro-template counts from train-visible reactions only
11
+ library/reagents.json common reagents tolerated as extra precursors
12
+
13
+ A prepared directory may add two things beside the release files (see ``serving``):
14
+
15
+ serving/serving.sqlite the serving index; when present, tasks, stock and
16
+ precedents load from it instead of being recomputed
17
+ evalsets/<name>.json frozen evaluation sets, each served as a split
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ import json
23
+ from dataclasses import dataclass
24
+ from functools import lru_cache
25
+ from pathlib import Path
26
+ from typing import Any
27
+
28
+ from .environment import RetroRouteSession
29
+ from .evalsets import EvalsetStore, load_evalset
30
+ from .leakage import LeakageRules
31
+ from .reactions import DEFAULT_MIN_COUNT, ReactionLibrary, iter_reactions
32
+ from .retrieval import PrecedentIndex
33
+ from .serving import INDEX_FILE, ServingIndex
34
+ from .store import TaskStore
35
+
36
+
37
+ @dataclass
38
+ class Benchmark:
39
+ root: Path
40
+ store: Any # TaskStore, SqliteTaskStore, or either wrapped in EvalsetStore
41
+ manifest: dict[str, Any]
42
+ rules: LeakageRules
43
+ library: ReactionLibrary
44
+ tool_library: ReactionLibrary
45
+ precedents: PrecedentIndex
46
+
47
+ @classmethod
48
+ def load(cls, root: str | Path) -> "Benchmark":
49
+ root = Path(root)
50
+ manifest_path = root / "manifest.json"
51
+ manifest = json.loads(manifest_path.read_text()) if manifest_path.exists() else {}
52
+ rules = LeakageRules.from_manifest(manifest)
53
+ library_dir = root / "library"
54
+ min_count = int(manifest.get("library", {}).get("min_template_count", DEFAULT_MIN_COUNT))
55
+ rows = list(iter_reactions(library_dir / "reactions.jsonl.gz"))
56
+ reagents = json.loads((library_dir / "reagents.json").read_text())
57
+ library = ReactionLibrary(
58
+ ((row["product"], tuple(row["reactants"])) for row in rows),
59
+ json.loads((library_dir / "templates.json").read_text()),
60
+ reagents,
61
+ min_count=min_count,
62
+ )
63
+ tool_library = ReactionLibrary(
64
+ ((row["product"], tuple(row["reactants"])) for row in rows if row["visible"]),
65
+ json.loads((library_dir / "templates-visible.json").read_text()),
66
+ reagents,
67
+ min_count=min_count,
68
+ )
69
+ index_path = root / "serving" / INDEX_FILE
70
+ if index_path.exists():
71
+ index = ServingIndex(index_path)
72
+ store: Any = index.task_store()
73
+ precedents = index.precedents(rules, library_dir / "reactions.jsonl.gz")
74
+ else:
75
+ store = TaskStore(root / "tasks-private", root / "stocks")
76
+ precedents = PrecedentIndex(rows, rules)
77
+ evalsets = [load_evalset(path) for path in sorted((root / "evalsets").glob("*.json"))]
78
+ if evalsets:
79
+ store = EvalsetStore(store, evalsets)
80
+ return cls(
81
+ root=root,
82
+ store=store,
83
+ manifest=manifest,
84
+ rules=rules,
85
+ library=library,
86
+ tool_library=tool_library,
87
+ precedents=precedents,
88
+ )
89
+
90
+ def session(self, **kwargs: Any) -> RetroRouteSession:
91
+ return RetroRouteSession(
92
+ library=self.library, tool_library=self.tool_library, precedent_index=self.precedents, **kwargs
93
+ )
94
+
95
+
96
+ @lru_cache(maxsize=4)
97
+ def load_benchmark(root: str) -> Benchmark:
98
+ """Process-wide cache; a release directory is immutable once built."""
99
+ return Benchmark.load(root)
core/retroenv/chemistry.py ADDED
@@ -0,0 +1,280 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Deterministic RDKit operations used by normalization and verification."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import itertools
7
+ from collections import Counter
8
+ from typing import Any, Iterable
9
+
10
+ from rdkit import Chem
11
+ from rdkit.Chem import Descriptors, rdChemReactions, rdMolDescriptors
12
+ from rdkit.Chem.Scaffolds import MurckoScaffold
13
+
14
+
15
+ class ChemistryError(ValueError):
16
+ """An input cannot be represented under the environment's RDKit policy."""
17
+
18
+
19
+ def stable_hash(text: str, *, prefix: str = "", length: int = 24) -> str:
20
+ digest = hashlib.sha256(text.encode("utf-8")).hexdigest()[:length]
21
+ return f"{prefix}{digest}"
22
+
23
+
24
+ def parse_molecule(smiles: str) -> Chem.Mol:
25
+ text = (smiles or "").strip()
26
+ if not text:
27
+ raise ChemistryError("empty SMILES")
28
+ mol = Chem.MolFromSmiles(text, sanitize=False)
29
+ if mol is None:
30
+ raise ChemistryError(f"cannot parse SMILES: {text!r}")
31
+ try:
32
+ Chem.SanitizeMol(mol)
33
+ Chem.AssignStereochemistry(mol, cleanIt=True, force=True)
34
+ except Exception as exc:
35
+ raise ChemistryError(f"SMILES does not sanitize: {text!r}: {exc}") from exc
36
+ return mol
37
+
38
+
39
+ def canonicalize_smiles(smiles: str, *, keep_atom_maps: bool = False, isomeric: bool = True) -> str:
40
+ mol = parse_molecule(smiles)
41
+ mapped = any(atom.GetAtomMapNum() for atom in mol.GetAtoms())
42
+ if mapped and not keep_atom_maps:
43
+ for atom in mol.GetAtoms():
44
+ atom.SetAtomMapNum(0)
45
+ # Map numbers break ring cis/trans symmetry during stereo perception; reparse without them.
46
+ mol = parse_molecule(Chem.MolToSmiles(mol, isomericSmiles=isomeric))
47
+ return Chem.MolToSmiles(mol, canonical=True, isomericSmiles=isomeric)
48
+
49
+
50
+ def canonicalize_components(
51
+ value: str | Iterable[str], *, keep_atom_maps: bool = False, isomeric: bool = True
52
+ ) -> tuple[str, ...]:
53
+ if isinstance(value, str):
54
+ raw = value.split(".") if value.strip() else []
55
+ else:
56
+ raw = [part for item in value for part in str(item).split(".")]
57
+ components = [
58
+ canonicalize_smiles(item.strip(), keep_atom_maps=keep_atom_maps, isomeric=isomeric)
59
+ for item in raw
60
+ if item.strip()
61
+ ]
62
+ return tuple(sorted(components))
63
+
64
+
65
+ def split_reaction_smiles(reaction_smiles: str) -> tuple[str, str, str]:
66
+ parts = (reaction_smiles or "").strip().split(">")
67
+ if len(parts) != 3:
68
+ raise ChemistryError("reaction SMILES must have reactants>reagents>products form")
69
+ if not parts[0].strip() or not parts[2].strip():
70
+ raise ChemistryError("reaction SMILES needs non-empty reactants and products")
71
+ return parts[0].strip(), parts[1].strip(), parts[2].strip()
72
+
73
+
74
+ def canonicalize_reaction(
75
+ reaction_smiles: str, *, keep_atom_maps: bool = False
76
+ ) -> tuple[str, tuple[str, ...], tuple[str, ...], tuple[str, ...]]:
77
+ reactants, reagents, products = split_reaction_smiles(reaction_smiles)
78
+ r = canonicalize_components(reactants, keep_atom_maps=keep_atom_maps)
79
+ a = canonicalize_components(reagents, keep_atom_maps=keep_atom_maps)
80
+ p = canonicalize_components(products, keep_atom_maps=keep_atom_maps)
81
+ return f"{'.'.join(r)}>{'.'.join(a)}>{'.'.join(p)}", r, a, p
82
+
83
+
84
+ def primary_product(products: Iterable[str]) -> str:
85
+ candidates = list(products)
86
+ if not candidates:
87
+ raise ChemistryError("reaction has no products")
88
+ # Stable tie break after preferring the molecule with the largest heavy-atom count.
89
+ return max(candidates, key=lambda value: (parse_molecule(value).GetNumHeavyAtoms(), value))
90
+
91
+
92
+ def audit_atom_mapping(reaction_smiles: str) -> dict[str, Any]:
93
+ """Audit map uniqueness and atom identity without pretending maps are required."""
94
+ reactants, _, products = split_reaction_smiles(reaction_smiles)
95
+ reactant_mols = [parse_molecule(item) for item in reactants.split(".") if item]
96
+ product_mols = [parse_molecule(item) for item in products.split(".") if item]
97
+
98
+ def collect(mols: list[Chem.Mol]) -> tuple[dict[int, tuple[int, int]], int, list[int]]:
99
+ mapped: dict[int, tuple[int, int]] = {}
100
+ duplicates: list[int] = []
101
+ total = 0
102
+ for mol in mols:
103
+ for atom in mol.GetAtoms():
104
+ total += 1
105
+ number = atom.GetAtomMapNum()
106
+ if not number:
107
+ continue
108
+ if number in mapped:
109
+ duplicates.append(number)
110
+ mapped[number] = (atom.GetAtomicNum(), atom.GetIsotope())
111
+ return mapped, total, sorted(set(duplicates))
112
+
113
+ left, left_total, left_duplicates = collect(reactant_mols)
114
+ right, right_total, right_duplicates = collect(product_mols)
115
+ mapped_atoms = len(left) + len(right)
116
+ if mapped_atoms == 0:
117
+ return {
118
+ "status": "unmapped",
119
+ "reactant_coverage": 0.0,
120
+ "product_coverage": 0.0,
121
+ "errors": [],
122
+ }
123
+
124
+ errors: list[str] = []
125
+ if left_duplicates:
126
+ errors.append(f"duplicate reactant atom maps: {left_duplicates}")
127
+ if right_duplicates:
128
+ errors.append(f"duplicate product atom maps: {right_duplicates}")
129
+ missing = sorted(set(right) - set(left))
130
+ if missing:
131
+ errors.append(f"product atom maps absent from reactants: {missing}")
132
+ mismatched = sorted(number for number in set(left) & set(right) if left[number] != right[number])
133
+ if mismatched:
134
+ errors.append(f"mapped atom element/isotope changed: {mismatched}")
135
+
136
+ left_coverage = len(left) / left_total if left_total else 0.0
137
+ right_coverage = len(right) / right_total if right_total else 0.0
138
+ if errors:
139
+ status = "invalid"
140
+ elif left_coverage == 1.0 and right_coverage == 1.0:
141
+ status = "complete"
142
+ else:
143
+ status = "partial"
144
+ return {
145
+ "status": status,
146
+ "reactant_coverage": round(left_coverage, 6),
147
+ "product_coverage": round(right_coverage, 6),
148
+ "errors": errors,
149
+ }
150
+
151
+
152
+ def canonical_step_key(product: str, reactants: Iterable[str], *, isomeric: bool = True) -> str:
153
+ canonical_product = canonicalize_smiles(product, isomeric=isomeric)
154
+ canonical_reactants = canonicalize_components(reactants, isomeric=isomeric)
155
+ return f"{canonical_product}<<{'.'.join(canonical_reactants)}"
156
+
157
+
158
+ def inspect_molecule(smiles: str) -> dict[str, Any]:
159
+ mol = parse_molecule(smiles)
160
+ canonical = canonicalize_smiles(smiles)
161
+ chiral_centres = Chem.FindMolChiralCenters(mol, includeUnassigned=True, useLegacyImplementation=False)
162
+ return {
163
+ "valid": True,
164
+ "canonical_smiles": canonical,
165
+ "formula": rdMolDescriptors.CalcMolFormula(mol),
166
+ "molecular_weight": round(Descriptors.MolWt(mol), 4),
167
+ "heavy_atoms": mol.GetNumHeavyAtoms(),
168
+ "rings": rdMolDescriptors.CalcNumRings(mol),
169
+ "formal_charge": Chem.GetFormalCharge(mol),
170
+ "chiral_centres": len(chiral_centres),
171
+ "unassigned_chiral_centres": sum(1 for _, assignment in chiral_centres if assignment == "?"),
172
+ "murcko_scaffold": scaffold_smiles(canonical),
173
+ }
174
+
175
+
176
+ def scaffold_smiles(smiles: str) -> str:
177
+ mol = parse_molecule(smiles)
178
+ scaffold = MurckoScaffold.GetScaffoldForMol(mol)
179
+ if scaffold.GetNumAtoms() == 0:
180
+ # All acyclic molecules otherwise share the empty scaffold.
181
+ return f"acyclic:{canonicalize_smiles(smiles)}"
182
+ return Chem.MolToSmiles(scaffold, canonical=True, isomericSmiles=True)
183
+
184
+
185
+ def is_single_ring_scaffold(scaffold: str) -> bool:
186
+ """True for acyclic keys and one-ring scaffolds (benzene, pyridine, piperidine, ...)."""
187
+ if scaffold.startswith("acyclic:"):
188
+ return True
189
+ mol = Chem.MolFromSmiles(scaffold)
190
+ return mol is not None and rdMolDescriptors.CalcNumRings(mol) == 1
191
+
192
+
193
+ def scaffold_group_key(smiles: str, *, exact_single_ring: bool = False, generic: frozenset[str] = frozenset()) -> str:
194
+ """Murcko scaffold used for split grouping.
195
+
196
+ A one-ring scaffold such as benzene is shared by thousands of unrelated
197
+ compounds, so grouping on it merges most of a large benchmark into one
198
+ split. With ``exact_single_ring`` those molecules group by their exact
199
+ canonical structure instead, as acyclic molecules already do; Morgan
200
+ near-duplicate edges still catch close analogues. ``generic`` extends the
201
+ same rule to named multi-ring scaffolds, such as biphenyl or indole, that a
202
+ benchmark found in hundreds of unrelated tasks.
203
+ """
204
+ scaffold = scaffold_smiles(smiles)
205
+ if scaffold in generic or (exact_single_ring and is_single_ring_scaffold(scaffold)):
206
+ return f"exact:{canonicalize_smiles(smiles)}"
207
+ return scaffold
208
+
209
+
210
+ def template_produces(
211
+ reaction_smarts: str,
212
+ reactants: Iterable[str],
213
+ expected_product: str,
214
+ *,
215
+ max_permutations: int = 24,
216
+ max_outcomes: int = 256,
217
+ ) -> bool:
218
+ """Return whether a trusted SMARTS produces the expected canonical product."""
219
+ if not reaction_smarts:
220
+ return False
221
+ try:
222
+ reaction = rdChemReactions.ReactionFromSmarts(reaction_smarts)
223
+ rdChemReactions.SanitizeRxn(reaction)
224
+ except Exception:
225
+ return False
226
+ required = reaction.GetNumReactantTemplates()
227
+ raw = list(reactants)
228
+ if required != len(raw) or required > 5:
229
+ return False
230
+ try:
231
+ mols = tuple(parse_molecule(item) for item in raw)
232
+ expected = canonicalize_smiles(expected_product)
233
+ except ChemistryError:
234
+ return False
235
+
236
+ permutations: Iterable[tuple[Chem.Mol, ...]]
237
+ count = _factorial_bounded(len(mols), max_permutations + 1)
238
+ if count <= max_permutations:
239
+ permutations = itertools.permutations(mols)
240
+ else:
241
+ permutations = (mols,)
242
+
243
+ seen = 0
244
+ for ordered in permutations:
245
+ try:
246
+ outcomes = reaction.RunReactants(ordered, maxProducts=max_outcomes)
247
+ except Exception:
248
+ continue
249
+ for outcome in outcomes:
250
+ seen += 1
251
+ if seen > max_outcomes:
252
+ return False
253
+ for product in outcome:
254
+ try:
255
+ Chem.SanitizeMol(product)
256
+ value = Chem.MolToSmiles(product, canonical=True, isomericSmiles=True)
257
+ value = canonicalize_smiles(value)
258
+ except Exception:
259
+ continue
260
+ if value == expected:
261
+ return True
262
+ return False
263
+
264
+
265
+ def formula_counter(smiles_values: Iterable[str]) -> Counter[str]:
266
+ """Debug helper; formula equality is not used as a reaction-feasibility gate."""
267
+ counter: Counter[str] = Counter()
268
+ for value in smiles_values:
269
+ for atom in parse_molecule(value).GetAtoms():
270
+ counter[atom.GetSymbol()] += 1
271
+ return counter
272
+
273
+
274
+ def _factorial_bounded(value: int, stop: int) -> int:
275
+ result = 1
276
+ for number in range(2, value + 1):
277
+ result *= number
278
+ if result >= stop:
279
+ return result
280
+ return result
core/retroenv/classes.py ADDED
@@ -0,0 +1,478 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Deterministic, rule-based reaction classes for arbitrary (product, reactants) pairs.
2
+
3
+ The verifier, the reaction_class_lookup tool and the dataset builder all call
4
+ ``classify_step``, so a forbidden-class constraint is judged by exactly the
5
+ labeller the agent can query. Rules compare functional-group counts between the
6
+ reactant side and the product with SMARTS; the first matching rule wins.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from dataclasses import dataclass
12
+ from functools import lru_cache
13
+ from typing import Callable, Iterable
14
+
15
+ from rdkit import Chem, RDLogger
16
+ from rdkit.Chem import rdMolDescriptors
17
+
18
+ RDLogger.DisableLog("rdApp.*")
19
+
20
+ CLASSIFIER_VERSION = "retroenv-classes-1"
21
+
22
+ EWG = "$([N+](=O)[O-]),$(C#N),$(C(F)(F)F),$([CX3]=O),$([SX4](=O)=O)"
23
+ ACTIVATION = ["$(c:n)", "$(c:a:a:n)", f"$(c:c-[{EWG}])", f"$(c:a:a:c-[{EWG}])"]
24
+ ACTIVATED = ",".join(ACTIVATION)
25
+ UNACTIVATED = ";".join(f"!{a}" for a in ACTIVATION)
26
+ ETHER_O = "[OX2;H0;!$(O[CX3]=[O,S,N]);!$(O[S,P,Si,B])]"
27
+ TRIFLATE = "OS(=O)(=O)C(F)(F)F"
28
+
29
+ GROUPS: dict[str, str | list[str]] = {
30
+ "boc": "[CH3]C([CH3])([CH3])OC(=O)[#7]",
31
+ "cbz_fmoc": ["[#7]C(=O)O[CH2]c1ccccc1", "[#7]C(=O)O[CH2]C1c2ccccc2-c2ccccc21"],
32
+ "silyl": ["[#8]-[Si]", "[CX2]#[CX2]-[Si]"],
33
+ "acetal_pg": [
34
+ "[#7,#8]-!@[CH1]1OCCCC1",
35
+ "[#7,#8]-!@[CH2]O[CH3]",
36
+ "[#7,#8]-!@[CH2]OCC[Si]",
37
+ "[CX4]1O[CX4][CX4]O1",
38
+ "[CX4]1O[CX4][CX4][CX4]O1",
39
+ "[CX4;!R;!$(C(~[OX2])(~[OX2])~[#7,#8]);!$(C([CH3])[CH3])](-[OX2][CH3,$([CH2][CH3])])-[OX2][CH3,$([CH2][CH3])]",
40
+ ],
41
+ "benzyl": [
42
+ "[#7,#8;!$([#8][CX3]=O);!$([#7,#8]C(=O)O[CH2]c1ccccc1)]-!@[CH2]c1ccccc1",
43
+ "[CX3;!$(C[#7])](=O)O[CH2]c1ccccc1",
44
+ "[#7,#8]-!@[CX4](c1ccccc1)c1ccccc1",
45
+ ],
46
+ "n_sulfonyl": "[#7]-[SX4](=O)(=O)c",
47
+ "thiocarbonyl": "[#6]=[SX1]",
48
+ "acid": "[CX3](=O)[OX2H1,OX1-]",
49
+ "acyl_halide": "[CX3](=O)[F,Cl,Br,I]",
50
+ "anhydride": "[CX3](=O)[OX2][CX3]=O",
51
+ "ester": "[CX3;!$(C(=O)([#7,#8,#16])[#7,#8,#16])](=O)[OX2][#6;!$([CX3]=O)]",
52
+ "amide": "[CX3;!$(C(=O)([#7,#8,#16])[#7,#8,#16])](=O)[#7]",
53
+ "urea": "[#7][CX3](=[O,S])[#7]",
54
+ "carbamate": "[#7][CX3](=O)[OX2][#6]",
55
+ "amidine": "[CX3;!R;!$(C=O)](=[NX2])[#7]",
56
+ "isocyanate": "N=C=[O,S]",
57
+ "aldehyde": "[CX3;H1,H2;!$(C[#7,#8,#16])]=O",
58
+ "ketone": "[#6][CX3](=O)[#6]",
59
+ "aryl_carbonyl": "c-[CX3;!$(C[#7,#8,#16,F,Cl,Br,I])]=O",
60
+ "nitrile": "[CX2]#[NX1]",
61
+ "aryl_nitrile": "c-[CX2]#[NX1]",
62
+ "imine": "[CX3]=[NX2;!R]",
63
+ "sulfonamide": "[SX4](=O)(=O)[#7]",
64
+ "sulfonate_ester": "[SX4](=O)(=O)[OX2][#6]",
65
+ "aryl_N": "c-[#7]",
66
+ "aryl_O": f"c-{ETHER_O}",
67
+ "aryl_S": "c-[SX2]",
68
+ "alkyl_N": "[CX4]-[#7]",
69
+ "alkyl_O": f"[CX4]-{ETHER_O}",
70
+ "alkyl_S": "[CX4]-[SX2]",
71
+ "aryl_vinyl": "[c,$([CX3]=[CX3])]-[CX3]=[CX3]",
72
+ "aryl_alkyne": "[c,$([CX3]=[CX3])]-[CX2]#[CX2]",
73
+ "terminal_alkene": "[CH2]=[CX3]",
74
+ "arx_activated": [
75
+ f"[c;{ACTIVATED}]-[Cl,Br,I,$([SX4](=O)(=O)[CH3]),$([SX3](=O)[CH3]),$([SX2][CH3]),$([SX2H1]),$([N+](=O)[O-])]",
76
+ "c-F",
77
+ ],
78
+ "arx": [f"[c;{UNACTIVATED}]-[Cl,Br,I]", f"c-{TRIFLATE}", f"[CX3]=[CX3]-[Br,I,$({TRIFLATE})]"],
79
+ "alkyl_x": ["[CX4;!$(C([Cl,Br,I])[Cl,Br,I])]-[Cl,Br,I]", "[CX4]-OS(=O)(=O)[#6,$([OX2][CX4])]"],
80
+ "epoxide": "[CX4]1[O,N][CX4]1",
81
+ "michael": "[CX3]=[CX3]-[$([CX3]=O),$(C#N),$([SX4](=O)=O),$([N+](=O)[O-])]",
82
+ "boron": "[#6]-[#5]",
83
+ "tin_zinc": "[#6]-[Sn,Zn]",
84
+ "organometal": "[#6]-[Mg,Li,Zn,Cu]",
85
+ "alcohol": "[CX4]-[OX2H]",
86
+ "phenol": "c-[OX2H]",
87
+ "oxo_het": "c=[OX1]",
88
+ "c_x": "[#6]-[F,Cl,Br,I]",
89
+ "nitro": "[#6]-[#7+](=O)[O-]",
90
+ "azide": "[#6]-N=[N+]=[N-]",
91
+ "nh2": "[NX3;H2;!$(N[C,S]=[O,S,N])]-[#6]",
92
+ "acyl_pg_ester": ["[CH3][CX3](=O)[OX2][#6]", "[CH3]C([CH3])([CH3])[CX3](=O)[OX2][CX4]"],
93
+ "cc_double": "[CX3]=[CX3]",
94
+ "cc_triple": "[CX2]#[CX2]",
95
+ "s_ox": "[#16]=[OX1]",
96
+ "n_oxide": "[#7+;!$([#7+]=O)]-[OX1-]",
97
+ "phosphorus": "[#15]",
98
+ "n_h": ["[#7;H1,H2,H3]", "[#7;H2,H3]", "[#7;H3]"],
99
+ }
100
+ _PATTERNS = {
101
+ name: [Chem.MolFromSmarts(s) for s in ([smarts] if isinstance(smarts, str) else smarts)]
102
+ for name, smarts in GROUPS.items()
103
+ }
104
+ AROMATIC, HETERO_AROMATIC, CARBON = (Chem.MolFromSmarts(s) for s in ("[a]", "[a;!#6]", "[#6]"))
105
+ # Halogen sources such as CBr4 or CHCl3 must not count as substrate C-X bonds.
106
+ SUBSTRATE_ONLY = {"c_x"}
107
+ REAGENT_MAX_HEAVY = 5
108
+
109
+
110
+ class _Side:
111
+ def __init__(self, mol: Chem.Mol):
112
+ self.mol = mol
113
+ frags = Chem.GetMolFrags(mol)
114
+ self._reagent_atoms = frozenset(
115
+ i for frag in frags if len(frags) > 1 and len(frag) <= REAGENT_MAX_HEAVY for i in frag
116
+ )
117
+
118
+ def count(self, name: str) -> int:
119
+ skip = self._reagent_atoms if name in SUBSTRATE_ONLY else frozenset()
120
+ return sum(
121
+ match[0] not in skip
122
+ for pattern in _PATTERNS[name]
123
+ for match in self.mol.GetSubstructMatches(pattern, uniquify=True, maxMatches=10000)
124
+ )
125
+
126
+ def scalar(self) -> dict[str, int]:
127
+ def atoms(pattern: Chem.Mol) -> set[int]:
128
+ return {m[0] for m in self.mol.GetSubstructMatches(pattern, maxMatches=100000)}
129
+
130
+ aromatic, hetero, carbons = atoms(AROMATIC), atoms(HETERO_AROMATIC), atoms(CARBON)
131
+ rings = self.mol.GetRingInfo().AtomRings()
132
+ return {
133
+ "rings": rdMolDescriptors.CalcNumRings(self.mol),
134
+ "het_aromatic_rings": sum(set(ring) <= aromatic and not hetero.isdisjoint(ring) for ring in rings),
135
+ "aromatic_atoms": len(aromatic),
136
+ "heavy": self.mol.GetNumHeavyAtoms(),
137
+ "largest_carbon_piece": max(len(carbons.intersection(f)) for f in Chem.GetMolFrags(self.mol)),
138
+ }
139
+
140
+
141
+ class _Delta:
142
+ """Product-minus-reactants counts, computed lazily per functional group."""
143
+
144
+ def __init__(self, product: _Side, reactants: _Side):
145
+ self._product, self._reactants = product, reactants
146
+ product_scalar, reactant_scalar = product.scalar(), reactants.scalar()
147
+ self._cache = {key: (product_scalar[key], reactant_scalar[key]) for key in product_scalar}
148
+
149
+ def __getattr__(self, name: str) -> int:
150
+ if name.startswith("_"):
151
+ raise AttributeError(name)
152
+ if name not in self._cache:
153
+ self._cache[name] = (self._product.count(name), self._reactants.count(name))
154
+ product, reactants = self._cache[name]
155
+ return product - reactants
156
+
157
+
158
+ def _lost(d: _Delta, *names: str) -> bool:
159
+ return any(getattr(d, n) < 0 for n in names)
160
+
161
+
162
+ def _gained(d: _Delta, *names: str) -> bool:
163
+ return any(getattr(d, n) > 0 for n in names)
164
+
165
+
166
+ def _aryl_lg_lost(d: _Delta) -> bool:
167
+ return d.arx + d.arx_activated < 0
168
+
169
+
170
+ ACYL_DONOR = ("acid", "acyl_halide", "ester", "anhydride")
171
+ CARBONYL = ("aldehyde", "ketone")
172
+ OH = ("alcohol", "phenol", "oxo_het", "acid")
173
+ HETERO_ALKYL = ("alkyl_N", "alkyl_O", "alkyl_S")
174
+ ARYL_HETERO = ("aryl_N", "aryl_O", "aryl_S")
175
+
176
+ # (rule, confidence, predicate); the first matching rule wins.
177
+ RULES: list[tuple[str, str, Callable[[_Delta], bool]]] = [
178
+ (
179
+ "heteroaromatic ring formation",
180
+ "medium",
181
+ lambda d: (
182
+ (d.rings > max(d.acetal_pg, 0) or (d.rings == 0 and d.largest_carbon_piece > 0))
183
+ and d.het_aromatic_rings > 0
184
+ ),
185
+ ),
186
+ ("cyclisation", "medium", lambda d: d.rings > max(d.acetal_pg, 0)),
187
+ ("Boc deprotection", "high", lambda d: d.boc < 0),
188
+ ("Boc protection", "high", lambda d: d.boc > 0),
189
+ ("Cbz/Fmoc deprotection", "high", lambda d: d.cbz_fmoc < 0),
190
+ ("Cbz/Fmoc protection", "high", lambda d: d.cbz_fmoc > 0),
191
+ ("acetal/THP/MOM/SEM deprotection", "high", lambda d: d.acetal_pg < 0),
192
+ ("acetal/THP/MOM/SEM protection", "high", lambda d: d.acetal_pg > 0),
193
+ ("silyl deprotection", "high", lambda d: d.silyl < 0),
194
+ ("silyl protection", "high", lambda d: d.silyl > 0 and not _aryl_lg_lost(d)),
195
+ ("benzyl deprotection", "high", lambda d: d.benzyl < 0),
196
+ ("sulfonyl (Ts/Ns) deprotection", "medium", lambda d: d.n_sulfonyl < 0 and d.n_h > 0),
197
+ ("Chan-Lam coupling", "medium", lambda d: d.boron < 0 and _gained(d, "aryl_N", "aryl_O") and not _aryl_lg_lost(d)),
198
+ ("Suzuki coupling", "high", lambda d: d.boron < 0 and (_aryl_lg_lost(d) or _lost(d, "alkyl_x"))),
199
+ ("borylation", "high", lambda d: d.boron > 0),
200
+ ("Sonogashira coupling", "high", lambda d: d.aryl_alkyne > 0 and _aryl_lg_lost(d)),
201
+ (
202
+ "Heck reaction",
203
+ "medium",
204
+ lambda d: d.aryl_vinyl > 0 and _aryl_lg_lost(d) and _lost(d, "terminal_alkene", "michael"),
205
+ ),
206
+ ("cyanation", "medium", lambda d: d.aryl_nitrile > 0 and _aryl_lg_lost(d)),
207
+ (
208
+ "Stille/Negishi/Kumada coupling",
209
+ "medium",
210
+ lambda d: (
211
+ _lost(d, "tin_zinc", "organometal")
212
+ and _aryl_lg_lost(d)
213
+ and not _lost(d, *CARBONYL, "nitrile", "ester", "amide")
214
+ ),
215
+ ),
216
+ ("sulfonamide formation", "high", lambda d: d.sulfonamide > 0),
217
+ ("O-sulfonylation", "high", lambda d: d.sulfonate_ester > 0),
218
+ (
219
+ "urea formation",
220
+ "high",
221
+ lambda d: d.urea > 0 and (d.n_h < 0 or _lost(d, "isocyanate", "acyl_halide", "carbamate", "acid")),
222
+ ),
223
+ (
224
+ "carbamate formation",
225
+ "high",
226
+ lambda d: d.carbamate > 0 and (d.n_h < 0 or _lost(d, "isocyanate", "acyl_halide", "alcohol", "phenol", "acid")),
227
+ ),
228
+ ("amide coupling", "high", lambda d: d.amide > 0 and (d.n_h < 0 or _lost(d, *ACYL_DONOR))),
229
+ ("esterification", "high", lambda d: d.ester > 0 and _lost(d, *ACYL_DONOR, "alcohol", "phenol")),
230
+ ("amidine/guanidine formation", "medium", lambda d: d.amidine > 0),
231
+ ("SNAr", "high", lambda d: _gained(d, *ARYL_HETERO) and _aryl_lg_lost(d) and d.arx_activated < 0),
232
+ ("Buchwald-Hartwig/Ullmann coupling", "medium", lambda d: _gained(d, *ARYL_HETERO) and _aryl_lg_lost(d)),
233
+ ("reductive amination", "high", lambda d: d.alkyl_N > 0 and _lost(d, *CARBONYL) and not _lost(d, "amide")),
234
+ ("Michael addition", "medium", lambda d: _lost(d, "michael") and d.largest_carbon_piece > 0),
235
+ ("N-alkylation", "high", lambda d: d.alkyl_N > 0 and _lost(d, "alkyl_x", "epoxide")),
236
+ ("O-alkylation", "high", lambda d: d.alkyl_O > 0 and _lost(d, "alkyl_x", "epoxide")),
237
+ ("S-alkylation", "high", lambda d: d.alkyl_S > 0 and _lost(d, "alkyl_x", "epoxide")),
238
+ (
239
+ "Mitsunobu / dehydrative alkylation",
240
+ "medium",
241
+ lambda d: _gained(d, *HETERO_ALKYL) and _lost(d, "alcohol") and not _lost(d, "amide", *ACYL_DONOR),
242
+ ),
243
+ (
244
+ "Grignard/organolithium addition",
245
+ "high",
246
+ lambda d: _lost(d, "organometal") and _lost(d, *CARBONYL, "nitrile", "ester", "amide", "acyl_halide"),
247
+ ),
248
+ ("Wittig/HWE olefination", "high", lambda d: d.phosphorus < 0 and d.cc_double > 0),
249
+ (
250
+ "halogen-metal exchange addition",
251
+ "low",
252
+ lambda d: (
253
+ _aryl_lg_lost(d)
254
+ and d.largest_carbon_piece > 0
255
+ and _lost(d, *CARBONYL, "ester", "amide", "nitrile")
256
+ and not _gained(d, *ARYL_HETERO)
257
+ ),
258
+ ),
259
+ (
260
+ "other C-C coupling (aryl halide)",
261
+ "low",
262
+ lambda d: _aryl_lg_lost(d) and d.largest_carbon_piece > 0 and not _gained(d, *ARYL_HETERO, *HETERO_ALKYL),
263
+ ),
264
+ (
265
+ "Friedel-Crafts acylation/formylation",
266
+ "medium",
267
+ lambda d: (
268
+ d.aryl_carbonyl > 0 and _lost(d, "acyl_halide", "anhydride", "acid", "amide") and not _aryl_lg_lost(d)
269
+ ),
270
+ ),
271
+ (
272
+ "C-alkylation",
273
+ "medium",
274
+ lambda d: (
275
+ _lost(d, "alkyl_x") and (d.largest_carbon_piece > 0 or d.nitrile > 0) and not _gained(d, *HETERO_ALKYL)
276
+ ),
277
+ ),
278
+ (
279
+ "aldol/Claisen/Knoevenagel",
280
+ "low",
281
+ lambda d: (
282
+ d.largest_carbon_piece > 0
283
+ and _lost(d, *CARBONYL, "ester", "nitrile", "acyl_halide")
284
+ and not _gained(d, "alkyl_N", "alkyl_O", "aryl_N", "aryl_O", "imine", "c_x")
285
+ ),
286
+ ),
287
+ ("Curtius rearrangement", "medium", lambda d: d.acid < 0 and d.nh2 > 0 and not _gained(d, "amide")),
288
+ ("nitro reduction", "high", lambda d: d.nitro < 0 and d.n_h > 0),
289
+ ("nitrile/azide reduction", "high", lambda d: _lost(d, "nitrile", "azide") and d.nh2 > 0),
290
+ (
291
+ "ester hydrolysis",
292
+ "high",
293
+ lambda d: (d.ester < 0 and d.acid > 0) or (d.acyl_pg_ester < 0 and _gained(d, "alcohol", "phenol")),
294
+ ),
295
+ (
296
+ "amide/nitrile hydrolysis",
297
+ "medium",
298
+ lambda d: (
299
+ (d.nitrile < 0 and _gained(d, "amide", "acid"))
300
+ or (_lost(d, "amide", "carbamate", "urea") and (d.acid > 0 or d.n_h > 0) and d.alkyl_N <= 0)
301
+ ),
302
+ ),
303
+ (
304
+ "ester/acid reduction",
305
+ "high",
306
+ lambda d: _lost(d, "ester", "acid", "amide", "nitrile") and _gained(d, "alcohol", "aldehyde"),
307
+ ),
308
+ ("amide reduction", "medium", lambda d: d.amide < 0 and d.alkyl_N > 0),
309
+ ("ketone/aldehyde reduction", "high", lambda d: _lost(d, *CARBONYL) and d.alcohol > 0),
310
+ ("ether cleavage (O-dealkylation)", "medium", lambda d: d.alkyl_O < 0 and _gained(d, "phenol", "alcohol")),
311
+ ("deoxyhalogenation", "high", lambda d: _lost(d, *OH) and d.c_x > 0),
312
+ ("Sandmeyer/diazotisation", "medium", lambda d: d.nh2 < 0 and _gained(d, "c_x", "aryl_nitrile", "phenol")),
313
+ ("halogenation", "medium", lambda d: d.c_x > 0),
314
+ ("nitration", "high", lambda d: d.nitro > 0),
315
+ ("thionation", "medium", lambda d: d.thiocarbonyl > 0),
316
+ (
317
+ "oxidation",
318
+ "medium",
319
+ lambda d: (
320
+ (d.alcohol < 0 and _gained(d, *CARBONYL, "acid"))
321
+ or (d.aldehyde < 0 and d.acid > 0)
322
+ or _gained(d, "s_ox", "n_oxide", "epoxide")
323
+ or (d.boron < 0 and d.phenol > 0)
324
+ or (d.alkyl_x < 0 and _gained(d, *CARBONYL))
325
+ or (d.cc_double < 0 and d.alcohol > 0)
326
+ or (d.aromatic_atoms > 0 and d.rings == 0)
327
+ ),
328
+ ),
329
+ ("imine/oxime/hydrazone formation", "medium", lambda d: _lost(d, *CARBONYL) and d.imine > 0),
330
+ ("dehydration to nitrile", "medium", lambda d: d.nitrile > 0 and _lost(d, "amide", "imine", "aldehyde")),
331
+ (
332
+ "hydrogenation",
333
+ "medium",
334
+ lambda d: d.heavy == 0 and (_lost(d, "cc_double", "cc_triple", "imine") or d.aromatic_atoms < 0),
335
+ ),
336
+ ("dehalogenation", "medium", lambda d: d.c_x < 0 and d.largest_carbon_piece <= 0),
337
+ ("deoxygenation", "low", lambda d: _lost(d, "alcohol", *CARBONYL) and d.heavy < 0),
338
+ ]
339
+
340
+ PROTECTION = "protection/deprotection"
341
+ COUPLING = "metal-catalysed coupling"
342
+ ACYLATION = "acylation/sulfonylation"
343
+ HETERO = "heteroatom alkylation/arylation"
344
+ CC = "C-C bond formation"
345
+ REDUCTION = "reduction"
346
+ CLEAVAGE = "hydrolysis/cleavage"
347
+ HALO = "halogenation/nitration"
348
+ RING = "ring formation"
349
+ CONDENSATION = "condensation/dehydration"
350
+ OTHER_FGI = "other FGI"
351
+
352
+ OTHER_PROTECTION = "other protection (Cbz/Fmoc/silyl/acetal)"
353
+ OTHER_DEPROTECTION = "other deprotection (Cbz/Fmoc/silyl/acetal/sulfonyl)"
354
+ OTHER_CROSS = "other cross-coupling (Heck/Stille/Negishi/cyanation/borylation)"
355
+ ENOLATE = "enolate/Michael chemistry"
356
+ CARBONYL_REDUCTION = "carbonyl/nitrile/azide reduction"
357
+ CONDENSATIONS = "condensation (imine/oxime/amidine/guanidine)"
358
+ OTHER_FGI_CLASS = "other FGI (dehydration/thionation/Curtius)"
359
+ ARYL_AMINATION = "Buchwald-Hartwig/Ullmann/Chan-Lam coupling"
360
+
361
+ # rule -> (agent-facing class, family)
362
+ TAXONOMY: dict[str, tuple[str, str]] = {
363
+ "heteroaromatic ring formation": ("heteroaromatic ring formation", RING),
364
+ "cyclisation": ("cyclisation (non-aromatic ring)", RING),
365
+ "Boc deprotection": ("Boc deprotection", PROTECTION),
366
+ "Boc protection": ("Boc protection", PROTECTION),
367
+ "Cbz/Fmoc deprotection": (OTHER_DEPROTECTION, PROTECTION),
368
+ "Cbz/Fmoc protection": (OTHER_PROTECTION, PROTECTION),
369
+ "acetal/THP/MOM/SEM deprotection": (OTHER_DEPROTECTION, PROTECTION),
370
+ "acetal/THP/MOM/SEM protection": (OTHER_PROTECTION, PROTECTION),
371
+ "silyl deprotection": (OTHER_DEPROTECTION, PROTECTION),
372
+ "silyl protection": (OTHER_PROTECTION, PROTECTION),
373
+ "benzyl deprotection": ("benzyl deprotection", PROTECTION),
374
+ "sulfonyl (Ts/Ns) deprotection": (OTHER_DEPROTECTION, PROTECTION),
375
+ "Chan-Lam coupling": (ARYL_AMINATION, COUPLING),
376
+ "Suzuki coupling": ("Suzuki coupling", COUPLING),
377
+ "borylation": (OTHER_CROSS, COUPLING),
378
+ "Sonogashira coupling": ("Sonogashira coupling", COUPLING),
379
+ "Heck reaction": (OTHER_CROSS, COUPLING),
380
+ "cyanation": (OTHER_CROSS, COUPLING),
381
+ "Stille/Negishi/Kumada coupling": (OTHER_CROSS, COUPLING),
382
+ "other C-C coupling (aryl halide)": (OTHER_CROSS, COUPLING),
383
+ "Buchwald-Hartwig/Ullmann coupling": (ARYL_AMINATION, COUPLING),
384
+ "sulfonamide formation": ("sulfonamide formation", ACYLATION),
385
+ "O-sulfonylation": ("O-sulfonylation (mesylate/tosylate/triflate)", ACYLATION),
386
+ "urea formation": ("urea/carbamate formation", ACYLATION),
387
+ "carbamate formation": ("urea/carbamate formation", ACYLATION),
388
+ "amide coupling": ("amide coupling", ACYLATION),
389
+ "esterification": ("esterification", ACYLATION),
390
+ "amidine/guanidine formation": (CONDENSATIONS, CONDENSATION),
391
+ "SNAr": ("SNAr", HETERO),
392
+ "reductive amination": ("reductive amination", HETERO),
393
+ "Michael addition": (ENOLATE, CC),
394
+ "N-alkylation": ("N-alkylation", HETERO),
395
+ "O-alkylation": ("O-/S-alkylation", HETERO),
396
+ "S-alkylation": ("O-/S-alkylation", HETERO),
397
+ "Mitsunobu / dehydrative alkylation": ("Mitsunobu / dehydrative alkylation", HETERO),
398
+ "Grignard/organolithium addition": ("Grignard/organolithium addition", CC),
399
+ "halogen-metal exchange addition": ("Grignard/organolithium addition", CC),
400
+ "Wittig/HWE olefination": ("Wittig/HWE olefination", CC),
401
+ "Friedel-Crafts acylation/formylation": ("Friedel-Crafts acylation/formylation", CC),
402
+ "C-alkylation": (ENOLATE, CC),
403
+ "aldol/Claisen/Knoevenagel": (ENOLATE, CC),
404
+ "Curtius rearrangement": (OTHER_FGI_CLASS, OTHER_FGI),
405
+ "nitro reduction": ("nitro reduction", REDUCTION),
406
+ "nitrile/azide reduction": (CARBONYL_REDUCTION, REDUCTION),
407
+ "ester hydrolysis": ("ester hydrolysis", CLEAVAGE),
408
+ "amide/nitrile hydrolysis": ("amide/nitrile hydrolysis", CLEAVAGE),
409
+ "ester/acid reduction": (CARBONYL_REDUCTION, REDUCTION),
410
+ "amide reduction": (CARBONYL_REDUCTION, REDUCTION),
411
+ "ketone/aldehyde reduction": (CARBONYL_REDUCTION, REDUCTION),
412
+ "ether cleavage (O-dealkylation)": ("ether cleavage (O-dealkylation)", CLEAVAGE),
413
+ "deoxyhalogenation": ("halogenation/nitration", HALO),
414
+ "Sandmeyer/diazotisation": ("halogenation/nitration", HALO),
415
+ "halogenation": ("halogenation/nitration", HALO),
416
+ "nitration": ("halogenation/nitration", HALO),
417
+ "thionation": (OTHER_FGI_CLASS, OTHER_FGI),
418
+ "oxidation": ("oxidation", "oxidation"),
419
+ "imine/oxime/hydrazone formation": (CONDENSATIONS, CONDENSATION),
420
+ "dehydration to nitrile": (OTHER_FGI_CLASS, CONDENSATION),
421
+ "hydrogenation": ("hydrogenation (C=C/C#C/arene)", REDUCTION),
422
+ "dehalogenation": ("other reduction (dehalogenation/deoxygenation)", REDUCTION),
423
+ "deoxygenation": ("other reduction (dehalogenation/deoxygenation)", REDUCTION),
424
+ "other": ("other", "other"),
425
+ }
426
+ REACTION_CLASSES: tuple[str, ...] = tuple(sorted({name for name, _ in TAXONOMY.values()}))
427
+ # Classes whose labels matched reagent evidence well enough to be enforced as constraints.
428
+ CONSTRAINABLE_CLASSES: tuple[str, ...] = (
429
+ "amide coupling",
430
+ "Suzuki coupling",
431
+ "Sonogashira coupling",
432
+ ARYL_AMINATION,
433
+ "SNAr",
434
+ "reductive amination",
435
+ "nitro reduction",
436
+ "Boc protection",
437
+ "Boc deprotection",
438
+ "ester hydrolysis",
439
+ "sulfonamide formation",
440
+ "urea/carbamate formation",
441
+ "esterification",
442
+ )
443
+
444
+
445
+ @dataclass(frozen=True)
446
+ class ReactionClass:
447
+ name: str
448
+ family: str
449
+ rule: str
450
+ confidence: str
451
+
452
+ def to_dict(self) -> dict[str, str]:
453
+ return {"reaction_class": self.name, "family": self.family, "rule": self.rule, "confidence": self.confidence}
454
+
455
+
456
+ OTHER = ReactionClass("other", "other", "other", "none")
457
+
458
+
459
+ @lru_cache(maxsize=200_000)
460
+ def _classify(product: str, reactants: tuple[str, ...]) -> ReactionClass:
461
+ product_mol = Chem.MolFromSmiles(product)
462
+ reactant_mol = Chem.MolFromSmiles(".".join(reactants))
463
+ if product_mol is None or reactant_mol is None or not reactant_mol.GetNumAtoms():
464
+ return OTHER
465
+ delta = _Delta(_Side(product_mol), _Side(reactant_mol))
466
+ for rule, confidence, predicate in RULES:
467
+ if predicate(delta):
468
+ name, family = TAXONOMY[rule]
469
+ return ReactionClass(name, family, rule, confidence)
470
+ return OTHER
471
+
472
+
473
+ def classify_step(product: str, reactants: Iterable[str]) -> ReactionClass:
474
+ """Classify one step from plain SMILES; never raises."""
475
+ try:
476
+ return _classify(product, tuple(sorted(reactants)))
477
+ except Exception:
478
+ return OTHER
core/retroenv/corpus.py ADDED
@@ -0,0 +1,310 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Streaming raw-reaction normalization with provenance-preserving deduplication."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import csv
7
+ import json
8
+ import sys
9
+ from collections import Counter
10
+ from pathlib import Path
11
+ from typing import Any, Iterable, Iterator
12
+
13
+ from rdkit.Chem import rdChemReactions
14
+
15
+ from .chemistry import (
16
+ ChemistryError,
17
+ audit_atom_mapping,
18
+ canonicalize_reaction,
19
+ primary_product,
20
+ stable_hash,
21
+ )
22
+
23
+ SCHEMA_VERSION = "litefold-reaction-v1"
24
+ EVIDENCE_KINDS = {"observed", "generated", "simulated"}
25
+
26
+
27
+ def iter_rows(path: Path) -> Iterator[tuple[int, dict[str, Any]]]:
28
+ """Yield one-based input positions and rows from JSONL, CSV, or TSV."""
29
+ suffix = path.suffix.lower()
30
+ with path.open("r", encoding="utf-8", newline="") as handle:
31
+ if suffix in {".jsonl", ".ndjson"}:
32
+ for line_number, line in enumerate(handle, 1):
33
+ if not line.strip():
34
+ continue
35
+ value = json.loads(line)
36
+ if not isinstance(value, dict):
37
+ raise ValueError(f"{path}:{line_number}: row is not an object")
38
+ yield line_number, value
39
+ return
40
+ if suffix not in {".csv", ".tsv"}:
41
+ raise ValueError(f"unsupported input extension {suffix!r}: {path}")
42
+ delimiter = "\t" if suffix == ".tsv" else ","
43
+ for line_number, row in enumerate(csv.DictReader(handle, delimiter=delimiter), 2):
44
+ yield line_number, dict(row)
45
+
46
+
47
+ def normalize_row(
48
+ row: dict[str, Any],
49
+ *,
50
+ source_name: str | None = None,
51
+ source_license: str | None = None,
52
+ evidence_kind: str = "observed",
53
+ reaction_column: str = "reaction_smiles",
54
+ ) -> dict[str, Any]:
55
+ """Normalize one source row or raise a reason suitable for a rejects file."""
56
+ raw_reaction = _text(row.get(reaction_column))
57
+ if not raw_reaction:
58
+ reactants = _component_text(row.get("reactants"))
59
+ reagents = _component_text(row.get("reagents"))
60
+ products = _component_text(row.get("products"))
61
+ raw_reaction = f"{reactants}>{reagents}>{products}"
62
+
63
+ canonical, reactants, reagents, products = canonicalize_reaction(raw_reaction)
64
+ mapped_canonical, _, _, _ = canonicalize_reaction(raw_reaction, keep_atom_maps=True)
65
+ mapping = audit_atom_mapping(raw_reaction)
66
+ if mapping["status"] == "invalid":
67
+ raise ChemistryError("invalid atom mapping: " + "; ".join(mapping["errors"]))
68
+
69
+ name = _text(row.get("source_name")) or source_name
70
+ license_id = _text(row.get("source_license")) or source_license
71
+ if not name:
72
+ raise ValueError("source_name is required per row or via --source-name")
73
+ if not license_id:
74
+ raise ValueError("source_license is required per row or via --source-license")
75
+
76
+ kind = (_text(row.get("evidence_kind")) or evidence_kind).lower()
77
+ if kind not in EVIDENCE_KINDS:
78
+ raise ValueError(f"evidence_kind must be one of {sorted(EVIDENCE_KINDS)}, got {kind!r}")
79
+
80
+ reaction_smarts = _text(row.get("reaction_smarts"))
81
+ template_hash = None
82
+ if reaction_smarts:
83
+ try:
84
+ reaction = rdChemReactions.ReactionFromSmarts(reaction_smarts)
85
+ rdChemReactions.SanitizeRxn(reaction)
86
+ except Exception as exc:
87
+ raise ChemistryError(f"invalid reaction_smarts: {exc}") from exc
88
+ template_hash = stable_hash(reaction_smarts, prefix="tpl_")
89
+
90
+ reaction_hash = stable_hash(canonical, prefix="crh_", length=32)
91
+ source = {
92
+ "name": name,
93
+ "license": license_id,
94
+ "record_id": _text(row.get("source_record_id") or row.get("id")),
95
+ # Patent/application/route grouping is required for split leakage audits.
96
+ # It is deliberately distinct from the per-reaction record identifier.
97
+ "group_id": _text(row.get("source_group_id") or row.get("patent_id") or row.get("route_group_id")),
98
+ "url": _text(row.get("source_url")),
99
+ "publication_year": _integer_or_none(row.get("publication_year")),
100
+ }
101
+ source = {key: value for key, value in source.items() if value is not None}
102
+
103
+ confidence = _float_or_none(row.get("confidence"))
104
+ if confidence is not None and not 0.0 <= confidence <= 1.0:
105
+ raise ValueError("confidence must be in [0, 1]")
106
+ conditions = _jsonish(row.get("conditions"))
107
+ reaction_class = _text(row.get("reaction_class"))
108
+ return {
109
+ "schema_version": SCHEMA_VERSION,
110
+ "reaction_id": stable_hash(canonical, prefix="rxn_", length=24),
111
+ "canonical_reaction_hash": reaction_hash,
112
+ "reaction_smiles": canonical,
113
+ "mapped_reaction_smiles": (mapped_canonical if mapping["status"] != "unmapped" else None),
114
+ "reactants": list(reactants),
115
+ "reagents": list(reagents),
116
+ "products": list(products),
117
+ "primary_product": primary_product(products),
118
+ "atom_mapping": mapping,
119
+ "reaction_class": reaction_class,
120
+ "reaction_class_candidates": [reaction_class] if reaction_class else [],
121
+ "reaction_smarts": reaction_smarts,
122
+ "reaction_smarts_candidates": [reaction_smarts] if reaction_smarts else [],
123
+ "template_hash": template_hash,
124
+ "conditions": [conditions] if conditions not in (None, "", {}) else [],
125
+ "confidence": confidence,
126
+ "confidence_values": [confidence] if confidence is not None else [],
127
+ "annotations": [annotations] if (annotations := _jsonish(row.get("annotations"))) not in (None, "", {}) else [],
128
+ "evidence_kind": kind,
129
+ "evidence_kinds": [kind],
130
+ "source": [source],
131
+ }
132
+
133
+
134
+ def merge_duplicate(existing: dict[str, Any], incoming: dict[str, Any]) -> None:
135
+ """Merge mutable metadata while leaving canonical chemistry untouched."""
136
+ if existing["canonical_reaction_hash"] != incoming["canonical_reaction_hash"]:
137
+ raise ValueError("attempted to merge different reactions")
138
+ _extend_unique(existing["source"], incoming["source"])
139
+ _extend_unique(existing["reaction_class_candidates"], incoming["reaction_class_candidates"])
140
+ _extend_unique(existing["reaction_smarts_candidates"], incoming["reaction_smarts_candidates"])
141
+ _extend_unique(existing["conditions"], incoming["conditions"])
142
+ _extend_unique(existing["confidence_values"], incoming["confidence_values"])
143
+ _extend_unique(existing["annotations"], incoming["annotations"])
144
+ _extend_unique(existing["evidence_kinds"], incoming["evidence_kinds"])
145
+
146
+ classes = existing["reaction_class_candidates"]
147
+ existing["reaction_class"] = classes[0] if len(classes) == 1 else None
148
+ templates = existing["reaction_smarts_candidates"]
149
+ existing["reaction_smarts"] = templates[0] if len(templates) == 1 else None
150
+ existing["template_hash"] = stable_hash(templates[0], prefix="tpl_") if len(templates) == 1 else None
151
+ kinds = existing["evidence_kinds"]
152
+ existing["evidence_kind"] = kinds[0] if len(kinds) == 1 else "mixed"
153
+ confidences = existing["confidence_values"]
154
+ existing["confidence"] = max(confidences) if confidences else None
155
+
156
+ # Prefer the strongest mapping evidence available among identical chemistry.
157
+ rank = {"unmapped": 0, "partial": 1, "complete": 2}
158
+ old = existing["atom_mapping"]["status"]
159
+ new = incoming["atom_mapping"]["status"]
160
+ if rank.get(new, -1) > rank.get(old, -1):
161
+ existing["atom_mapping"] = incoming["atom_mapping"]
162
+ existing["mapped_reaction_smiles"] = incoming["mapped_reaction_smiles"]
163
+
164
+
165
+ def build_corpus(
166
+ inputs: Iterable[Path],
167
+ output: Path,
168
+ rejects: Path,
169
+ *,
170
+ source_name: str | None,
171
+ source_license: str | None,
172
+ evidence_kind: str = "observed",
173
+ reaction_column: str = "reaction_smiles",
174
+ report_path: Path | None = None,
175
+ ) -> dict[str, Any]:
176
+ records: dict[str, dict[str, Any]] = {}
177
+ counts: Counter[str] = Counter()
178
+ reject_rows: list[dict[str, Any]] = []
179
+
180
+ for input_path in inputs:
181
+ for line_number, row in iter_rows(input_path):
182
+ counts["rows_read"] += 1
183
+ try:
184
+ record = normalize_row(
185
+ row,
186
+ source_name=source_name,
187
+ source_license=source_license,
188
+ evidence_kind=evidence_kind,
189
+ reaction_column=reaction_column,
190
+ )
191
+ except Exception as exc:
192
+ counts["rows_rejected"] += 1
193
+ reject_rows.append(
194
+ {
195
+ "input": str(input_path),
196
+ "line": line_number,
197
+ "error_type": type(exc).__name__,
198
+ "reason": str(exc),
199
+ "row": row,
200
+ }
201
+ )
202
+ continue
203
+ key = record["canonical_reaction_hash"]
204
+ if key in records:
205
+ counts["duplicates_merged"] += 1
206
+ merge_duplicate(records[key], record)
207
+ else:
208
+ records[key] = record
209
+ counts["unique_reactions"] += 1
210
+ counts[f"mapping_{record['atom_mapping']['status']}"] += 1
211
+
212
+ report = {
213
+ "schema_version": SCHEMA_VERSION,
214
+ "inputs": [str(path) for path in inputs],
215
+ "counts": dict(sorted(counts.items())),
216
+ }
217
+ _write_jsonl(output, (records[key] for key in sorted(records)))
218
+ _write_jsonl(rejects, reject_rows)
219
+ if report_path:
220
+ report_path.parent.mkdir(parents=True, exist_ok=True)
221
+ report_path.write_text(json.dumps(report, indent=2, sort_keys=True) + "\n")
222
+ return report
223
+
224
+
225
+ def _write_jsonl(path: Path, rows: Iterable[dict[str, Any]]) -> None:
226
+ path.parent.mkdir(parents=True, exist_ok=True)
227
+ with path.open("w", encoding="utf-8") as handle:
228
+ for row in rows:
229
+ handle.write(json.dumps(row, sort_keys=True, separators=(",", ":")) + "\n")
230
+
231
+
232
+ def _extend_unique(target: list[Any], values: Iterable[Any]) -> None:
233
+ seen = {json.dumps(value, sort_keys=True, default=str) for value in target}
234
+ for value in values:
235
+ key = json.dumps(value, sort_keys=True, default=str)
236
+ if key not in seen:
237
+ target.append(value)
238
+ seen.add(key)
239
+ target.sort(key=lambda item: json.dumps(item, sort_keys=True, default=str))
240
+
241
+
242
+ def _component_text(value: Any) -> str:
243
+ if isinstance(value, (list, tuple)):
244
+ return ".".join(str(item).strip() for item in value if str(item).strip())
245
+ return _text(value) or ""
246
+
247
+
248
+ def _text(value: Any) -> str | None:
249
+ if value is None:
250
+ return None
251
+ text = str(value).strip()
252
+ return text or None
253
+
254
+
255
+ def _integer_or_none(value: Any) -> int | None:
256
+ text = _text(value)
257
+ return int(text) if text is not None else None
258
+
259
+
260
+ def _float_or_none(value: Any) -> float | None:
261
+ text = _text(value)
262
+ return float(text) if text is not None else None
263
+
264
+
265
+ def _jsonish(value: Any) -> Any:
266
+ if not isinstance(value, str):
267
+ return value
268
+ text = value.strip()
269
+ if not text:
270
+ return None
271
+ if text[0] in '[{"' or text in {"true", "false", "null"}:
272
+ try:
273
+ return json.loads(text)
274
+ except json.JSONDecodeError:
275
+ pass
276
+ return text
277
+
278
+
279
+ def build_parser() -> argparse.ArgumentParser:
280
+ parser = argparse.ArgumentParser(description=__doc__)
281
+ parser.add_argument("inputs", nargs="+", type=Path)
282
+ parser.add_argument("--output", type=Path, required=True)
283
+ parser.add_argument("--rejects", type=Path, required=True)
284
+ parser.add_argument("--report", type=Path)
285
+ parser.add_argument("--source-name")
286
+ parser.add_argument("--source-license")
287
+ parser.add_argument("--evidence-kind", choices=sorted(EVIDENCE_KINDS), default="observed")
288
+ parser.add_argument("--reaction-column", default="reaction_smiles")
289
+ return parser
290
+
291
+
292
+ def main(argv: list[str] | None = None) -> int:
293
+ args = build_parser().parse_args(argv)
294
+ report_path = args.report or args.output.with_suffix(".report.json")
295
+ report = build_corpus(
296
+ args.inputs,
297
+ args.output,
298
+ args.rejects,
299
+ source_name=args.source_name,
300
+ source_license=args.source_license,
301
+ evidence_kind=args.evidence_kind,
302
+ reaction_column=args.reaction_column,
303
+ report_path=report_path,
304
+ )
305
+ print(json.dumps(report, indent=2, sort_keys=True))
306
+ return 0 if not report["counts"].get("rows_rejected") else 2
307
+
308
+
309
+ if __name__ == "__main__":
310
+ sys.exit(main())
core/retroenv/disconnections.py ADDED
@@ -0,0 +1,420 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """The chemistry a planner reasons with: reaction families, reagent roles and strategic cuts.
2
+
3
+ Everything here is rule-based on structures alone, so any statement built from it
4
+ can be checked against the molecules. ``step_family`` names the reaction a step
5
+ performs, ``role`` names what a reagent is (a boronic acid, an aryl halide, an
6
+ amine), and ``strategic_disconnections`` proposes the cuts a chemist would
7
+ consider first: amide, sulfonamide, ester and ether bonds, biaryl bonds, and C-N
8
+ bonds made by alkylation, reductive amination or aryl substitution. A proposal is
9
+ a plausible disconnection, not a claim that it was the route actually used.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ from dataclasses import dataclass
15
+ from functools import lru_cache
16
+ from typing import Iterable
17
+
18
+ from rdkit import Chem
19
+
20
+ from .chemistry import canonicalize_smiles
21
+
22
+ PATTERNS = {
23
+ "boronic": Chem.MolFromSmarts("[#6]B([OX2])[OX2]"),
24
+ "acyl_halide": Chem.MolFromSmarts("C(=O)[Cl,Br]"),
25
+ "acid": Chem.MolFromSmarts("[CX3](=O)[OX2H1]"),
26
+ "amine": Chem.MolFromSmarts("[NX3;H2,H1;!$(NC=O)]"),
27
+ "alcohol": Chem.MolFromSmarts("[OX2H][CX4,c]"),
28
+ "carbonyl": Chem.MolFromSmarts("[CX3H1,CX3H0;!$(C(=O)[O,N])](=O)[#6,#1]"),
29
+ "halide": Chem.MolFromSmarts("[#6][Cl,Br,I]"),
30
+ "sulfonyl_halide": Chem.MolFromSmarts("S(=O)(=O)[Cl,F]"),
31
+ "isocyanate": Chem.MolFromSmarts("N=C=O"),
32
+ }
33
+ BOC = Chem.MolFromSmarts("CC(C)(C)OC(=O)[N,O,n]")
34
+ BOC2O = Chem.MolFromSmiles("CC(C)(C)OC(=O)OC(=O)OC(C)(C)C")
35
+
36
+
37
+ @lru_cache(maxsize=65536)
38
+ def _mol(smiles: str):
39
+ return Chem.MolFromSmiles(smiles)
40
+
41
+
42
+ def _has(smiles: str, key: str) -> bool:
43
+ mol = _mol(smiles)
44
+ return mol is not None and mol.HasSubstructMatch(PATTERNS[key])
45
+
46
+
47
+ def step_family(reactants: Iterable[str], product: str) -> str:
48
+ """Coarse rule-based reaction family; 'other' when no rule fires."""
49
+ reactants = list(reactants)
50
+ mols = [_mol(r) for r in reactants]
51
+ if any(m is not None and m.HasSubstructMatch(BOC2O) for m in mols):
52
+ return "Boc protection"
53
+ if len(reactants) == 1:
54
+ p = _mol(product)
55
+ if mols[0].HasSubstructMatch(BOC) and len(p.GetSubstructMatches(BOC)) < len(mols[0].GetSubstructMatches(BOC)):
56
+ return "Boc deprotection"
57
+ return "one-reactant FGI"
58
+ if any(_has(r, "boronic") for r in reactants):
59
+ return "Suzuki-type coupling"
60
+ if any(_has(r, "sulfonyl_halide") for r in reactants):
61
+ return "sulfonylation"
62
+ if any(_has(r, "isocyanate") for r in reactants):
63
+ return "urea / carbamate"
64
+ if any(_has(r, "acyl_halide") or _has(r, "acid") for r in reactants) and any(
65
+ _has(r, "amine") or _has(r, "alcohol") for r in reactants
66
+ ):
67
+ return "amide/ester coupling"
68
+ if any(_has(r, "carbonyl") for r in reactants) and any(_has(r, "amine") for r in reactants):
69
+ return "reductive amination"
70
+ if any(_has(r, "halide") for r in reactants):
71
+ return "alkylation / SNAr"
72
+ return "other"
73
+
74
+
75
+ # --- What a reagent is ---------------------------------------------------------
76
+
77
+ SMALL = {
78
+ "N": "ammonia",
79
+ "O": "water",
80
+ "CO": "methanol",
81
+ "CCO": "ethanol",
82
+ "CN": "methylamine",
83
+ "CNC": "dimethylamine",
84
+ "C=O": "formaldehyde",
85
+ "CC(=O)O": "acetic acid",
86
+ "CI": "methyl iodide",
87
+ "CS(=O)(=O)Cl": "methanesulfonyl chloride",
88
+ "CC(C)(C)OC(=O)OC(=O)OC(C)(C)C": "Boc anhydride",
89
+ "CC(=O)Cl": "acetyl chloride",
90
+ "CC(=O)OC(C)=O": "acetic anhydride",
91
+ "NN": "hydrazine",
92
+ "NO": "hydroxylamine",
93
+ }
94
+ # First match wins, so the more specific groups come first.
95
+ ROLES = [
96
+ (name, Chem.MolFromSmarts(smarts))
97
+ for name, smarts in (
98
+ ("boronic acid", "[#6]B([OX2H])[OX2H]"),
99
+ ("boronate ester", "[#6]B([OX2][#6])[OX2][#6]"),
100
+ ("sulfonyl chloride", "[#6]S(=O)(=O)[Cl,F]"),
101
+ ("acyl chloride", "[#6]C(=O)[Cl,Br]"),
102
+ ("chloroformate", "[#6]OC(=O)Cl"),
103
+ ("isocyanate", "N=C=O"),
104
+ ("carboxylic acid", "[CX3](=O)[OX2H1]"),
105
+ ("sulfonate ester", "[#6]S(=O)(=O)O[CX4]"),
106
+ ("aldehyde", "[CX3H1](=O)[#6]"),
107
+ ("ketone", "[#6][CX3](=O)[#6]"),
108
+ ("heteroaryl halide", "[$(c([Cl,Br,I,F])n),$(c([Cl,Br,I,F])an),$(c([Cl,Br,I,F])aan)]"),
109
+ ("aryl halide", "c[Cl,Br,I]"),
110
+ ("alkyl halide", "[CX4][Cl,Br,I]"),
111
+ ("amine", "[NX3;H2,H1;!$(N[C,S]=[O,S,N]);!$(N-a)]"),
112
+ ("aniline", "[NX3;H2,H1;!$(N[C,S]=O)]-c"),
113
+ ("phenol", "c[OX2H]"),
114
+ ("alcohol", "[CX4][OX2H]"),
115
+ ("ester", "[#6][CX3](=O)O[#6]"),
116
+ ("nitro compound", "[N+](=O)[O-]"),
117
+ ("azide", "[N-]=[N+]=[N-]"),
118
+ ("organic azide", "[#6]N=[N+]=[N-]"),
119
+ ("cyanide", "[C-]#N"),
120
+ ("nitrile", "C#N"),
121
+ )
122
+ ]
123
+
124
+
125
+ # The groups that take part in each family, so a reagent is named for the group that
126
+ # reacts: in a mesylation, 4-bromophenethyl alcohol is the alcohol, not the aryl halide.
127
+ FAMILY_ROLES = {
128
+ "Suzuki-type coupling": ("boronic acid", "boronate ester", "heteroaryl halide", "aryl halide"),
129
+ "amide/ester coupling": ("acyl chloride", "carboxylic acid", "amine", "aniline", "alcohol", "phenol"),
130
+ "sulfonylation": ("sulfonyl chloride", "amine", "aniline", "alcohol", "phenol"),
131
+ "reductive amination": ("aldehyde", "ketone", "amine", "aniline"),
132
+ "alkylation / SNAr": (
133
+ "alkyl halide",
134
+ "sulfonate ester",
135
+ "heteroaryl halide",
136
+ "aryl halide",
137
+ "amine",
138
+ "aniline",
139
+ "phenol",
140
+ "alcohol",
141
+ ),
142
+ "urea / carbamate": ("isocyanate", "chloroformate", "amine", "aniline", "alcohol"),
143
+ "Boc protection": ("amine", "aniline"),
144
+ }
145
+ _ROLE_PATTERNS = dict(ROLES)
146
+
147
+
148
+ @lru_cache(maxsize=65536)
149
+ def role(smiles: str, family: str | None = None) -> str:
150
+ """The reagent's characteristic group, in words a chemist would use.
151
+
152
+ With a ``family``, the group that reaction uses wins over others the molecule
153
+ happens to carry.
154
+ """
155
+ canonical = canonicalize_smiles(smiles)
156
+ if canonical in SMALL:
157
+ return SMALL[canonical]
158
+ mol = _mol(canonical)
159
+ for name in FAMILY_ROLES.get(family or "", ()):
160
+ if mol.HasSubstructMatch(_ROLE_PATTERNS[name]):
161
+ return name
162
+ for name, pattern in ROLES:
163
+ if mol.HasSubstructMatch(pattern):
164
+ return name
165
+ return "building block"
166
+
167
+
168
+ AMINES = {"amine", "aniline", "ammonia", "methylamine", "dimethylamine", "hydrazine", "hydroxylamine"}
169
+ NUCLEOPHILES = AMINES | {"phenol", "alcohol", "methanol", "ethanol", "water", "azide", "cyanide"}
170
+ TERMINAL_ALKYNE = Chem.MolFromSmarts("[CH]#C")
171
+ # Names too coarse to state as fact: text omits the reaction type rather than guess it.
172
+ UNCERTAIN = {"halide substitution", "functional-group interconversion", "a reported transformation"}
173
+
174
+
175
+ def reaction_phrase(family: str, reactants: Iterable[str], product: str) -> str:
176
+ """The forward reaction a step performs, e.g. 'Suzuki coupling' or 'nitro reduction'."""
177
+ reactants = list(reactants)
178
+ roles = {role(r, family) for r in reactants}
179
+ if family == "Suzuki-type coupling":
180
+ return "Suzuki coupling"
181
+ if family == "amide/ester coupling":
182
+ if "chloroformate" in roles:
183
+ return "carbamate formation"
184
+ return "amide coupling" if roles & AMINES else "esterification"
185
+ if family == "sulfonylation":
186
+ if roles & AMINES:
187
+ return "sulfonamide formation"
188
+ return "mesylation" if "methanesulfonyl chloride" in roles else "sulfonylation"
189
+ if family == "reductive amination":
190
+ return "reductive amination"
191
+ if family == "alkylation / SNAr":
192
+ if roles & {"acyl chloride", "acetyl chloride"}:
193
+ return "acylation"
194
+ if roles & {"alkyl halide", "sulfonate ester", "methyl iodide"}:
195
+ if "azide" in roles:
196
+ return "azide displacement"
197
+ if "cyanide" in roles:
198
+ return "cyanide displacement"
199
+ return "alkylation"
200
+ aryl = roles & {"aryl halide", "heteroaryl halide"}
201
+ if aryl and any(_mol(r).HasSubstructMatch(TERMINAL_ALKYNE) for r in reactants):
202
+ return "Sonogashira coupling"
203
+ if "heteroaryl halide" in roles and roles & NUCLEOPHILES:
204
+ return "SNAr substitution"
205
+ if "aryl halide" in roles and roles & AMINES:
206
+ return "Buchwald-Hartwig amination"
207
+ if "aryl halide" in roles and roles & {"phenol", "alcohol"}:
208
+ return "aryl ether coupling"
209
+ return "halide substitution"
210
+ if family == "urea / carbamate":
211
+ return "urea or carbamate formation"
212
+ if family in ("Boc protection", "Boc deprotection"):
213
+ return family
214
+ if family == "one-reactant FGI" and reactants:
215
+ for name, lost, gained in FGI:
216
+ if _count(reactants[0], lost) > _count(product, lost) and (
217
+ gained is None or _count(product, gained) > _count(reactants[0], gained)
218
+ ):
219
+ return name
220
+ return "functional-group interconversion"
221
+ return "a reported transformation"
222
+
223
+
224
+ # The partner a chemist names first ("Suzuki coupling of the aryl halide with the
225
+ # boronic acid", "alkylation of the amine with the mesylate").
226
+ SUBSTRATE_FIRST = {
227
+ "Suzuki coupling": ("heteroaryl halide", "aryl halide"),
228
+ "amide coupling": ("carboxylic acid", "acyl chloride", "acetic acid", "acetyl chloride"),
229
+ "esterification": ("carboxylic acid", "acyl chloride", "acetic acid", "acetyl chloride"),
230
+ "sulfonamide formation": tuple(AMINES),
231
+ "mesylation": ("alcohol", "phenol", "amine", "aniline"),
232
+ "sulfonylation": ("alcohol", "phenol", "amine", "aniline"),
233
+ "reductive amination": ("aldehyde", "ketone", "formaldehyde"),
234
+ "alkylation": tuple(NUCLEOPHILES),
235
+ "SNAr substitution": ("heteroaryl halide",),
236
+ "Buchwald-Hartwig amination": ("aryl halide",),
237
+ "aryl ether coupling": ("aryl halide",),
238
+ "Sonogashira coupling": ("heteroaryl halide", "aryl halide"),
239
+ "urea or carbamate formation": tuple(NUCLEOPHILES),
240
+ "Boc protection": ("amine", "aniline"),
241
+ "carbamate formation": tuple(NUCLEOPHILES),
242
+ "acylation": (),
243
+ "azide displacement": ("sulfonate ester", "alkyl halide"),
244
+ "cyanide displacement": ("sulfonate ester", "alkyl halide"),
245
+ }
246
+ # A one-reactant step, said the way a chemist would.
247
+ SINGLE = {
248
+ "Boc deprotection": "removal of the Boc group",
249
+ "nitro reduction": "reduction of the nitro group",
250
+ "azide reduction": "reduction of the azide",
251
+ "nitrile reduction": "reduction of the nitrile",
252
+ "ester hydrolysis": "hydrolysis of the ester",
253
+ "ester reduction": "reduction of the ester to the alcohol",
254
+ "O-demethylation": "O-demethylation of the methyl ether",
255
+ "debenzylation": "removal of the benzyl group",
256
+ "carbonyl reduction": "reduction of the carbonyl",
257
+ "alcohol oxidation": "oxidation of the alcohol",
258
+ }
259
+ # Phrases whose verb reads better on its own when the partner is named after it.
260
+ VERB = {"azide displacement": "displacement", "cyanide displacement": "displacement"}
261
+ # The reagent a chemist names last.
262
+ REAGENT_LAST = {"acylation": ("acyl chloride", "acetyl chloride")}
263
+ NAMED = set(SMALL.values())
264
+
265
+
266
+ def _named(role_name: str) -> str:
267
+ return role_name if role_name in NAMED else f"the {role_name}"
268
+
269
+
270
+ def describe(family: str, reactants: Iterable[str], product: str) -> str:
271
+ """The forward reaction with its partners, e.g. 'mesylation of the alcohol with methanesulfonyl chloride'."""
272
+ reactants = list(reactants)
273
+ phrase = reaction_phrase(family, reactants, product)
274
+ if len(reactants) == 1:
275
+ if phrase in UNCERTAIN:
276
+ return "a reported one-step transformation of a single precursor"
277
+ return SINGLE.get(phrase) or f"{phrase} of {_named(role(reactants[0], family))}"
278
+ first, last = SUBSTRATE_FIRST.get(phrase, ()), REAGENT_LAST.get(phrase, ())
279
+ ordered = sorted(reactants, key=lambda r: (role(r, family) in last, role(r, family) not in first))
280
+ names = [_named(role(r, family)) for r in ordered]
281
+ if phrase in UNCERTAIN:
282
+ # Too coarse to name: say what reacts, not a reaction we cannot vouch for.
283
+ return f"a reported reaction of {names[0]} with {' and '.join(names[1:])}"
284
+ return f"{VERB.get(phrase, phrase)} of {names[0]} with {' and '.join(names[1:])}"
285
+
286
+
287
+ # --- Strategic disconnections ----------------------------------------------------
288
+
289
+
290
+ # One-reactant changes, most specific first: (name, group lost, group gained or None).
291
+ FGI = [
292
+ (name, Chem.MolFromSmarts(lost), Chem.MolFromSmarts(gained) if gained else None)
293
+ for name, lost, gained in (
294
+ ("nitro reduction", "[N+](=O)[O-]", "[NX3;H2]"),
295
+ ("azide reduction", "[#6]N=[N+]=[N-]", "[NX3;H2]"),
296
+ ("nitrile reduction", "C#N", "[CH2][NX3;H2]"),
297
+ ("ester hydrolysis", "[#6][CX3](=O)O[CX4]", "[CX3](=O)[OX2H1]"),
298
+ ("ester reduction", "[#6][CX3](=O)O[CX4]", "[CH2][OX2H]"),
299
+ ("O-demethylation", "c[OX2][CH3]", "c[OX2H]"),
300
+ ("debenzylation", "[O,N][CH2]c1ccccc1", None),
301
+ ("carbonyl reduction", "[#6][CX3](=O)[#6,#1]", "[CX4][OX2H]"),
302
+ ("alcohol oxidation", "[CX4][OX2H]", "[CX3]=O"),
303
+ )
304
+ ]
305
+
306
+
307
+ def _count(smiles: str, pattern) -> int:
308
+ return len(_mol(smiles).GetSubstructMatches(pattern))
309
+
310
+
311
+ @dataclass(frozen=True)
312
+ class Disconnection:
313
+ reactants: tuple[str, ...]
314
+ family: str
315
+ bond: str
316
+ score: float
317
+
318
+
319
+ # (family, bond in words, SMARTS whose atoms :1 and :2 are the bond, cap on 1, cap on 2, reliability)
320
+ RULES = [
321
+ ("amide/ester coupling", "amide C-N bond", "[#6][CX3:1](=O)-!@[NX3;!$(N[S](=O)=O):2]", "OH", "H", 1.0),
322
+ ("sulfonylation", "sulfonamide S-N bond", "[#6][SX4:1](=O)(=O)-!@[NX3:2]", "Cl", "H", 0.95),
323
+ ("Suzuki-type coupling", "biaryl C-C bond", "[c:1]-!@[c:2]", "SUZUKI", "SUZUKI", 0.95),
324
+ ("alkylation / SNAr", "aryl C-N bond", "[c:1]-!@[NX3;!$(N[C,S]=O):2]", "ARX", "H", 0.85),
325
+ ("reductive amination", "alkyl C-N bond", "[CX4;H2;$(C[#6]):1]-!@[NX3;!$(N[C,S]=O):2]", "=O", "H", 0.85),
326
+ ("alkylation / SNAr", "alkyl C-N bond", "[CX4;H2,H1;$(C[#6]):1]-!@[NX3;!$(N[C,S]=O):2]", "Br", "H", 0.8),
327
+ ("alkylation / SNAr", "ether C-O bond", "[CX4;H2:1]-!@[OX2:2]c", "Br", "H", 0.8),
328
+ ("amide/ester coupling", "ester C-O bond", "[#6][CX3:1](=O)-!@[OX2:2][#6]", "OH", "H", 0.75),
329
+ ]
330
+ _RULES = [(f, b, Chem.MolFromSmarts(s), c1, c2, w) for f, b, s, c1, c2, w in RULES]
331
+
332
+
333
+ def _cap(rw: Chem.RWMol, index: int, cap: str) -> None:
334
+ atom = rw.GetAtomWithIdx(index)
335
+ if cap == "H":
336
+ # A bracket atom keeps its hydrogens explicitly; the lost bond becomes one.
337
+ if atom.GetNoImplicit():
338
+ atom.SetNumExplicitHs(atom.GetNumExplicitHs() + 1)
339
+ return
340
+ if cap == "=O":
341
+ if atom.GetNoImplicit():
342
+ atom.SetNumExplicitHs(max(0, atom.GetNumExplicitHs() - 1))
343
+ oxygen = rw.AddAtom(Chem.Atom(8))
344
+ rw.AddBond(index, oxygen, Chem.BondType.DOUBLE)
345
+ return
346
+ if cap == "B(O)O":
347
+ boron = rw.AddAtom(Chem.Atom(5))
348
+ rw.AddBond(index, boron, Chem.BondType.SINGLE)
349
+ for _ in range(2):
350
+ rw.AddBond(boron, rw.AddAtom(Chem.Atom(8)), Chem.BondType.SINGLE)
351
+ return
352
+ element = {"OH": 8, "Cl": 17, "Br": 35}[cap]
353
+ rw.AddBond(index, rw.AddAtom(Chem.Atom(element)), Chem.BondType.SINGLE)
354
+
355
+
356
+ def _split(mol, a: int, b: int, cap_a: str, cap_b: str) -> tuple[str, ...] | None:
357
+ rw = Chem.RWMol(mol)
358
+ rw.RemoveBond(a, b)
359
+ _cap(rw, a, cap_a)
360
+ _cap(rw, b, cap_b)
361
+ try:
362
+ out = rw.GetMol()
363
+ Chem.SanitizeMol(out)
364
+ fragments = Chem.GetMolFrags(out, asMols=True)
365
+ if len(fragments) != 2:
366
+ return None
367
+ return tuple(sorted(canonicalize_smiles(Chem.MolToSmiles(f)) for f in fragments))
368
+ except Exception:
369
+ return None
370
+
371
+
372
+ def _boronic_partner_size(reactants: tuple[str, ...]) -> int:
373
+ return min(
374
+ _mol(s).GetNumHeavyAtoms() for s in reactants if any(atom.GetSymbol() == "B" for atom in _mol(s).GetAtoms())
375
+ )
376
+
377
+
378
+ def _heteroaryl(atom) -> bool:
379
+ ring = atom.GetOwningMol().GetRingInfo()
380
+ return any(
381
+ atom.GetIdx() in r and any(atom.GetOwningMol().GetAtomWithIdx(i).GetSymbol() == "N" for i in r)
382
+ for r in ring.AtomRings()
383
+ )
384
+
385
+
386
+ @lru_cache(maxsize=16384)
387
+ def strategic_disconnections(product: str) -> tuple[Disconnection, ...]:
388
+ """Plausible one-step cuts of ``product``, most attractive first.
389
+
390
+ The score adds the rule's reliability to how evenly the cut splits the molecule,
391
+ because chemists prefer reliable reactions and convergent routes. Bonds on a
392
+ stereocentre are skipped, since re-attaching the cap there could flip it.
393
+ """
394
+ mol = _mol(canonicalize_smiles(product))
395
+ if mol is None:
396
+ return ()
397
+ heavy = mol.GetNumHeavyAtoms()
398
+ found: dict[tuple[str, ...], Disconnection] = {}
399
+ for family, bond, pattern, cap_1, cap_2, reliability in _RULES:
400
+ mapped = {atom.GetAtomMapNum(): atom.GetIdx() for atom in pattern.GetAtoms() if atom.GetAtomMapNum()}
401
+ for match in mol.GetSubstructMatches(pattern):
402
+ a, b = match[mapped[1]], match[mapped[2]]
403
+ if any(mol.GetAtomWithIdx(i).GetChiralTag() != Chem.ChiralType.CHI_UNSPECIFIED for i in (a, b)):
404
+ continue
405
+ caps = [(cap_1, cap_2)]
406
+ if cap_1 == "SUZUKI":
407
+ caps = [("Br", "B(O)O"), ("B(O)O", "Br")]
408
+ elif cap_1 == "ARX":
409
+ caps = [("Cl" if _heteroaryl(mol.GetAtomWithIdx(a)) else "Br", cap_2)]
410
+ options = [r for r in (_split(mol, a, b, x, y) for x, y in caps) if r]
411
+ if cap_1 == "SUZUKI" and options:
412
+ # The boronic acid goes on the smaller partner, as it usually would.
413
+ options = [min(options, key=_boronic_partner_size)]
414
+ for reactants in options:
415
+ smallest = min(_mol(s).GetNumHeavyAtoms() for s in reactants)
416
+ score = reliability + 0.6 * min(0.5, smallest / max(heavy, 1))
417
+ key = reactants
418
+ if key not in found or found[key].score < score:
419
+ found[key] = Disconnection(reactants, family, bond, round(score, 4))
420
+ return tuple(sorted(found.values(), key=lambda d: (-d.score, d.reactants)))
core/retroenv/environment.py ADDED
@@ -0,0 +1,311 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Pure-Python multi-turn RetroRoute session used by every serving wrapper."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import uuid
6
+ from typing import Any, Iterable
7
+
8
+ from .chemistry import ChemistryError, canonicalize_components, canonicalize_smiles
9
+ from .chemistry import inspect_molecule as inspect_with_rdkit
10
+ from .classes import CONSTRAINABLE_CLASSES, classify_step
11
+ from .models import RetroTask
12
+ from .reactions import ReactionLibrary, StepKey, free_key
13
+ from .retrieval import PrecedentIndex, StockIndex, cached_stock_index, molecule_lookup
14
+ from .tools import tool_names
15
+ from .verifier import RouteVerifier
16
+
17
+ PROMPT = """Plan a retrosynthesis for the target {target}.
18
+ Return {route_range} by calling emit_routes exactly once. Each route's longest
19
+ linear sequence may have at most {max_depth} reaction(s).{constraints}
20
+
21
+ The stock is not in this prompt: stock_retrieve is its only access surface. Every
22
+ leaf must be in stock and may claim in_stock=true only after an exact lookup hit;
23
+ intermediates need not be in stock.
24
+
25
+ Each tree alternates molecule -> reaction -> molecule. A molecule is
26
+ {{"type":"mol","smiles":"...","in_stock":false,"children":[]}}. A reaction has
27
+ type="reaction", is_reaction=true, metadata (explanation, reaction_class,
28
+ confidence from 0 to 1, literature as a list, precursor_roles as an object), and
29
+ its precursor molecules as children. Distinct routes must differ at the first
30
+ disconnection. Every item in submission.routes is a root molecule object, never
31
+ wrapped in route, root or tree keys.
32
+
33
+ Each step is judged by a frozen reaction library (known reactions and frequent
34
+ reaction templates), not by matching a hidden answer; any valid route counts.
35
+ Library support is not proof that a reaction works experimentally."""
36
+
37
+
38
+ def describe_constraints(task: RetroTask) -> str:
39
+ lines = []
40
+ if task.constraints.forbidden_classes:
41
+ names = ", ".join(task.constraints.forbidden_classes)
42
+ lines.append(
43
+ f"Do not use these reaction classes in any step: {names}. Classes are assigned by "
44
+ "reaction_class_lookup, the same labeller the verifier uses."
45
+ )
46
+ if task.constraints.excluded_stock:
47
+ names = ", ".join(task.constraints.excluded_stock)
48
+ lines.append(
49
+ f"These building blocks are unavailable for this task and stock_retrieve will not return them: {names}."
50
+ )
51
+ if task.min_routes > 1:
52
+ lines.append(f"Return at least {task.min_routes} valid routes with different first disconnections.")
53
+ return "".join(f"\nConstraint: {line}" for line in lines)
54
+
55
+
56
+ def route_range(task: RetroTask) -> str:
57
+ if task.min_routes == task.max_routes:
58
+ return f"exactly {task.min_routes} synthesis tree(s)"
59
+ return f"{task.min_routes} to {task.max_routes} synthesis trees"
60
+
61
+
62
+ def task_prompt(task: RetroTask) -> str:
63
+ """The episode prompt: the target, the depth budget and the constraints, never a hidden route."""
64
+ return PROMPT.format(
65
+ target=task.target_smiles,
66
+ route_range=route_range(task),
67
+ max_depth=task.max_depth,
68
+ constraints=describe_constraints(task),
69
+ )
70
+
71
+
72
+ class RetroRouteSession:
73
+ """Stateful tool session; no tool reads the task's hidden routes."""
74
+
75
+ def __init__(
76
+ self,
77
+ *,
78
+ library: ReactionLibrary,
79
+ tool_library: ReactionLibrary | None = None,
80
+ precedent_index: PrecedentIndex | None = None,
81
+ max_tool_calls: int = 32,
82
+ max_search_results: int = 20,
83
+ pubchem_cache: dict[str, dict[str, Any]] | None = None,
84
+ toolset: str = "full",
85
+ ):
86
+ if max_tool_calls < 1:
87
+ raise ValueError("max_tool_calls must be positive")
88
+ self.toolset = toolset
89
+ self.tool_names = tool_names(toolset)
90
+ self.max_tool_calls = max_tool_calls
91
+ self.max_search_results = max_search_results
92
+ self.verifier = RouteVerifier(library)
93
+ # validate_disconnection must only know train-visible evidence.
94
+ self.tool_library = tool_library or library
95
+ self.precedent_index = precedent_index or PrecedentIndex(())
96
+ self.pubchem_cache = pubchem_cache or {}
97
+ self.task: RetroTask | None = None
98
+ self.stock: frozenset[str] = frozenset()
99
+ self.stock_index: StockIndex | None = None
100
+ self.excluded: frozenset[str] = frozenset()
101
+ self._own_reactions: frozenset[StepKey] = frozenset()
102
+ self.episode_id = ""
103
+ self.tool_calls = 0
104
+ self.done = False
105
+ self.final_score: dict[str, Any] | None = None
106
+
107
+ def reset(self, task: RetroTask, stock: Iterable[str], *, episode_id: str | None = None) -> dict[str, Any]:
108
+ self.task = task
109
+ raw_stock = stock if isinstance(stock, frozenset) else frozenset(stock)
110
+ self.stock_index = cached_stock_index(raw_stock)
111
+ self.stock = self.stock_index.known # one shared set, so the verifier's per-stock cache hits
112
+ self.excluded = frozenset(canonicalize_smiles(item) for item in task.constraints.excluded_stock)
113
+ # A train task must not confirm its own known reactions by corpus lookup.
114
+ self._own_reactions = (
115
+ frozenset(free_key(step.product, step.reactants) for route in task.reference_routes for step in route.steps)
116
+ if task.split == "train"
117
+ else frozenset()
118
+ )
119
+ self.episode_id = episode_id or str(uuid.uuid4())
120
+ self.tool_calls = 0
121
+ self.done = False
122
+ self.final_score = None
123
+ return self.observation("Episode started.")
124
+
125
+ def prompt(self) -> str:
126
+ return task_prompt(self._require_task())
127
+
128
+ def observation(self, feedback: str = "") -> dict[str, Any]:
129
+ task = self._require_task()
130
+ return {
131
+ "episode_id": self.episode_id,
132
+ "task_id": task.task_id,
133
+ "variant": task.variant,
134
+ "target_smiles": task.target_smiles,
135
+ "max_depth": task.max_depth,
136
+ "min_routes": task.min_routes,
137
+ "max_routes": task.max_routes,
138
+ "constraints": task.constraints.to_dict(),
139
+ "stock_id": task.stock_id,
140
+ "prompt": self.prompt(),
141
+ "available_tools": list(self.tool_names),
142
+ "tool_calls_used": self.tool_calls,
143
+ "tool_calls_remaining": max(0, self.max_tool_calls - self.tool_calls),
144
+ "done": self.done,
145
+ "feedback": feedback,
146
+ }
147
+
148
+ def inspect_molecule(self, smiles: str) -> dict[str, Any]:
149
+ blocked = self._consume("inspect_molecule")
150
+ if blocked:
151
+ return blocked
152
+ try:
153
+ return inspect_with_rdkit(smiles)
154
+ except Exception as exc:
155
+ return {"valid": False, "error": str(exc)}
156
+
157
+ def pubchem_lookup(self, query: str) -> dict[str, Any]:
158
+ """Resolve a SMILES locally; cached name/CAS hydration is build-time only."""
159
+ blocked = self._consume("pubchem_lookup")
160
+ return blocked or molecule_lookup(query, self.pubchem_cache)
161
+
162
+ def stock_retrieve(self, query: str, mode: str = "auto", limit: int = 10) -> dict[str, Any]:
163
+ """Search this task's stock (excluded building blocks are absent) with a hard 20-result cap."""
164
+ blocked = self._consume("stock_retrieve")
165
+ if blocked:
166
+ return blocked
167
+ assert self.stock_index is not None
168
+ return self.stock_index.retrieve(
169
+ query, mode=mode, limit=min(limit, self.max_search_results), excluded=self.excluded
170
+ )
171
+
172
+ def reaction_precedent_search(
173
+ self, product_smiles: str = "", reaction_class: str = "", limit: int = 10
174
+ ) -> dict[str, Any]:
175
+ """Capped analogues from the train-visible reaction corpus."""
176
+ blocked = self._consume("reaction_precedent_search")
177
+ if blocked:
178
+ return blocked
179
+ return self._search(product_smiles, reaction_class, limit)
180
+
181
+ def validate_disconnection(self, product_smiles: str, reactants: Iterable[str] | str) -> dict[str, Any]:
182
+ """Check one proposed cut against train-visible reactions and templates."""
183
+ blocked = self._consume("validate_disconnection")
184
+ if blocked:
185
+ return blocked
186
+ reactant_values = _reactant_list(reactants)
187
+ support = self.tool_library.support(product_smiles, reactant_values, exclude=self._own_reactions)
188
+ result = {
189
+ "supported": support.supported,
190
+ "support": {"corpus": "known_precedent", "template": "reaction_template"}.get(support.kind, support.kind),
191
+ "template_frequency": support.template_count,
192
+ "stereo_consistent": support.stereo_match,
193
+ "product": support.product,
194
+ "reactants": list(support.reactants),
195
+ }
196
+ if support.error:
197
+ result["error"] = support.error
198
+ if support.product:
199
+ result["reaction_class"] = classify_step(support.product, support.reactants).name
200
+ result["note"] = "train-visible evidence only; the final verifier uses a larger frozen library"
201
+ return result
202
+
203
+ def reaction_class_lookup(self, product_smiles: str, reactants: Iterable[str] | str) -> dict[str, Any]:
204
+ """Name the class of any proposed cut with the verifier's own labeller."""
205
+ blocked = self._consume("reaction_class_lookup")
206
+ if blocked:
207
+ return blocked
208
+ task = self._require_task()
209
+ try:
210
+ product = canonicalize_smiles(product_smiles)
211
+ reactant_values = canonicalize_components(_reactant_list(reactants))
212
+ except ChemistryError as exc:
213
+ return {"error": str(exc)}
214
+ label = classify_step(product, reactant_values)
215
+ return {
216
+ **label.to_dict(),
217
+ "forbidden_in_this_task": label.name in task.constraints.forbidden_classes,
218
+ "constrainable_classes": list(CONSTRAINABLE_CLASSES),
219
+ }
220
+
221
+ def reaction_conditions_search(
222
+ self, product_smiles: str = "", reactants: Iterable[str] | str = (), reaction_class: str = "", limit: int = 5
223
+ ) -> dict[str, Any]:
224
+ """Reagent sets reported for train-visible analogues of a cut or product."""
225
+ blocked = self._consume("reaction_conditions_search")
226
+ if blocked:
227
+ return blocked
228
+ if not reaction_class and product_smiles and reactants:
229
+ try:
230
+ reaction_class = classify_step(
231
+ canonicalize_smiles(product_smiles), canonicalize_components(_reactant_list(reactants))
232
+ ).name
233
+ except ChemistryError:
234
+ reaction_class = ""
235
+ result = self._search(product_smiles, reaction_class if reaction_class != "other" else "", limit)
236
+ return {
237
+ "reaction_class": reaction_class or None,
238
+ "conditions": [
239
+ {
240
+ "analogue_product": row["product_smiles"],
241
+ "reagents": row["reagents"],
242
+ "similarity": row["similarity"],
243
+ }
244
+ for row in result.get("results", [])
245
+ ],
246
+ "source": "train-visible analogues",
247
+ }
248
+
249
+ def search_literature(self, product_smiles: str = "", reaction_class: str = "", limit: int = 5) -> dict[str, Any]:
250
+ """Patent identifiers attached to train-visible analogues; no live web access."""
251
+ blocked = self._consume("search_literature")
252
+ if blocked:
253
+ return blocked
254
+ result = self._search(product_smiles, reaction_class, limit)
255
+ citations = [
256
+ {"patent": patent, "product_smiles": row["product_smiles"], "reaction_class": row["reaction_class"]}
257
+ for row in result.get("results", [])
258
+ for patent in row["patents"]
259
+ ]
260
+ return {
261
+ "results": citations[:limit],
262
+ "returned": min(limit, len(citations)),
263
+ "note": "frozen metadata only; live web search is disabled during rollouts",
264
+ }
265
+
266
+ def emit_routes(self, submission: dict[str, Any] | str) -> dict[str, Any]:
267
+ """Submit the final route trees; this is terminal."""
268
+ task = self._require_task()
269
+ if self.done:
270
+ return {"error": "episode is already complete", "done": True, "score": self.final_score}
271
+ result = self.verifier.score_submission(task, submission, self.stock)
272
+ self.done = True
273
+ self.final_score = result.to_dict()
274
+ return {"done": True, "score": self.final_score, "tool_calls_used": self.tool_calls}
275
+
276
+ def _search(self, product_smiles: str, reaction_class: str, limit: int) -> dict[str, Any]:
277
+ try:
278
+ return self.precedent_index.search(
279
+ task=self._require_task(),
280
+ product_smiles=product_smiles or None,
281
+ reaction_class=reaction_class or None,
282
+ limit=min(limit, self.max_search_results),
283
+ )
284
+ except Exception as exc:
285
+ return {"results": [], "error": str(exc)}
286
+
287
+ def _consume(self, tool_name: str) -> dict[str, Any] | None:
288
+ self._require_task()
289
+ if self.done:
290
+ return {"error": "episode is complete", "done": True}
291
+ if tool_name not in self.tool_names:
292
+ return {"error": f"{tool_name} is not available in the {self.toolset!r} toolset", "tool": tool_name}
293
+ if self.tool_calls >= self.max_tool_calls:
294
+ return {
295
+ "error": "tool-call budget exhausted; emit_routes is still available",
296
+ "tool": tool_name,
297
+ "tool_calls_remaining": 0,
298
+ }
299
+ self.tool_calls += 1
300
+ return None
301
+
302
+ def _require_task(self) -> RetroTask:
303
+ if self.task is None:
304
+ raise RuntimeError("reset() must be called before using tools")
305
+ return self.task
306
+
307
+
308
+ def _reactant_list(reactants: Iterable[str] | str) -> list[str]:
309
+ if isinstance(reactants, str):
310
+ return [part for part in reactants.split(".") if part]
311
+ return [str(item) for item in reactants]
core/retroenv/evalsets.py ADDED
@@ -0,0 +1,167 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Frozen evaluation subsets: a fixed list of release task ids, served as a split of its own.
2
+
3
+ An evaluation set names tasks that already exist in the release and never copies them, so it
4
+ scores exactly as those tasks do in their source split. Its ``evalset_id`` hashes the design
5
+ and the task list; a file whose id does not match its contents is refused, so a hand edit
6
+ cannot silently change what a board measures.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import hashlib
12
+ import json
13
+ from pathlib import Path
14
+ from typing import Any, Iterable
15
+
16
+ from .chemistry import canonicalize_smiles
17
+ from .models import RetroTask
18
+
19
+ EVALSET_VERSION = 1
20
+ TIERS = ("easy", "medium", "hard")
21
+
22
+
23
+ def evalset_id(record: dict[str, Any]) -> str:
24
+ body = {key: record[key] for key in ("evalset_version", "name", "seed", "design", "tasks")}
25
+ return hashlib.sha256(json.dumps(body, sort_keys=True, separators=(",", ":")).encode()).hexdigest()
26
+
27
+
28
+ def first_reaction(task: RetroTask) -> str:
29
+ """The class of the known route's first disconnection, preferring the patent route."""
30
+ target = canonicalize_smiles(task.target_smiles)
31
+ routes = sorted(task.reference_routes, key=lambda route: route.kind != "patent")
32
+ for route in routes:
33
+ for step in route.steps:
34
+ if canonicalize_smiles(step.product) == target:
35
+ return step.reaction_class or "other"
36
+ return "other"
37
+
38
+
39
+ def _order(seed: str, task_id: str) -> str:
40
+ return hashlib.sha256(f"{seed}:{task_id}".encode()).hexdigest()
41
+
42
+
43
+ def select_tiered(tasks: Iterable[RetroTask], quotas: dict[str, int], seed: str) -> list[RetroTask]:
44
+ """Pick ``quotas[tier]`` tasks per difficulty tier, spread over source split and route length.
45
+
46
+ Within a tier, candidates form strata by (source split, shortest-route depth), each ordered
47
+ by a seeded hash. Strata are visited round-robin, shallow first, and each visit prefers a
48
+ candidate whose first reaction class the tier has not used yet. The result depends only on
49
+ the candidates and the seed.
50
+ """
51
+ pool = list(tasks)
52
+ chosen: list[RetroTask] = []
53
+ for tier in TIERS:
54
+ quota = quotas.get(tier, 0)
55
+ strata: dict[tuple[int, str], list[RetroTask]] = {}
56
+ for task in pool:
57
+ if task.difficulty.get("tier") == tier:
58
+ key = (int(task.difficulty.get("min_depth") or task.max_depth), task.split)
59
+ strata.setdefault(key, []).append(task)
60
+ for members in strata.values():
61
+ members.sort(key=lambda task: _order(seed, task.task_id))
62
+ available = sum(len(members) for members in strata.values())
63
+ if available < quota:
64
+ raise ValueError(f"tier {tier!r} has {available} candidates, fewer than its quota of {quota}")
65
+ picked: list[RetroTask] = []
66
+ used: set[str] = set()
67
+ while len(picked) < quota:
68
+ for key in sorted(strata):
69
+ if len(picked) == quota:
70
+ break
71
+ members = strata[key]
72
+ if not members:
73
+ continue
74
+ fresh = next((task for task in members if first_reaction(task) not in used), members[0])
75
+ members.remove(fresh)
76
+ picked.append(fresh)
77
+ used.add(first_reaction(fresh))
78
+ chosen.extend(picked)
79
+ return chosen
80
+
81
+
82
+ def describe_task(task: RetroTask) -> dict[str, Any]:
83
+ return {
84
+ "task_id": task.task_id,
85
+ "source_split": task.split,
86
+ "tier": task.difficulty.get("tier"),
87
+ "min_depth": task.difficulty.get("min_depth"),
88
+ "max_depth": task.max_depth,
89
+ "first_reaction": first_reaction(task),
90
+ "heavy_atoms": task.difficulty.get("heavy_atoms"),
91
+ "target_smiles": task.target_smiles,
92
+ }
93
+
94
+
95
+ def make_evalset(name: str, tasks: Iterable[RetroTask], *, seed: str, design: dict[str, Any]) -> dict[str, Any]:
96
+ record = {
97
+ "evalset_version": EVALSET_VERSION,
98
+ "name": name,
99
+ "seed": seed,
100
+ "design": design,
101
+ "tasks": [describe_task(task) for task in tasks],
102
+ }
103
+ record["size"] = len(record["tasks"])
104
+ record["evalset_id"] = evalset_id(record)
105
+ return record
106
+
107
+
108
+ def load_evalset(path: str | Path) -> dict[str, Any]:
109
+ record = json.loads(Path(path).read_text())
110
+ if record.get("evalset_version") != EVALSET_VERSION:
111
+ raise ValueError(f"{path}: evaluation set version {record.get('evalset_version')}, expected {EVALSET_VERSION}")
112
+ if record.get("evalset_id") != evalset_id(record):
113
+ raise ValueError(f"{path}: evalset_id does not match its contents; regenerate it instead of editing it")
114
+ ids = [task["task_id"] for task in record["tasks"]]
115
+ if len(ids) != len(set(ids)) or len(ids) != record.get("size"):
116
+ raise ValueError(f"{path}: task ids must be unique and match size")
117
+ return record
118
+
119
+
120
+ class EvalsetStore:
121
+ """A task store plus evaluation sets, each served as a split of the same name."""
122
+
123
+ def __init__(self, base: Any, evalsets: Iterable[dict[str, Any]]):
124
+ self.base = base
125
+ self._evalsets: dict[str, tuple[RetroTask, ...]] = {}
126
+ for record in evalsets:
127
+ name = record["name"]
128
+ if name in base.splits() or name in self._evalsets:
129
+ raise ValueError(f"evaluation set {name!r} collides with an existing split")
130
+ self._evalsets[name] = tuple(self._resolve(record, entry) for entry in record["tasks"])
131
+
132
+ def _resolve(self, record: dict[str, Any], entry: dict[str, Any]) -> RetroTask:
133
+ task_id, split = entry["task_id"], entry.get("source_split")
134
+ position = self.base.position(split, task_id) if split in self.base.splits() else None
135
+ task = self.base.task(split, position) if position is not None else self.base.find(task_id)
136
+ if task is None:
137
+ raise ValueError(f"evaluation set {record['name']!r} names {task_id}, which this release lacks")
138
+ return task
139
+
140
+ def __getattr__(self, name: str) -> Any:
141
+ return getattr(self.base, name)
142
+
143
+ def evalset_names(self) -> list[str]:
144
+ return sorted(self._evalsets)
145
+
146
+ def splits(self) -> list[str]:
147
+ return sorted([*self.base.splits(), *self._evalsets])
148
+
149
+ def tasks(self, split: str):
150
+ if split in self._evalsets:
151
+ return self._evalsets[split]
152
+ return self.base.tasks(split)
153
+
154
+ def task(self, split: str, index: int) -> RetroTask:
155
+ return self.tasks(split)[index]
156
+
157
+ def public_task(self, split: str, index: int) -> dict:
158
+ return self.task(split, index).to_dict(include_hidden=False)
159
+
160
+ def position(self, split: str, task_id: str) -> int | None:
161
+ if split in self._evalsets:
162
+ return next((i for i, task in enumerate(self._evalsets[split]) if task.task_id == task_id), None)
163
+ return self.base.position(split, task_id)
164
+
165
+ def iter_all(self) -> Iterable[RetroTask]:
166
+ # Evaluation sets only re-list release tasks, so the release alone is every task once.
167
+ return self.base.iter_all()
core/retroenv/graph.py ADDED
@@ -0,0 +1,285 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Renderable route-tree schema, tolerant parsing, and route/tree conversion."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from dataclasses import dataclass, field
7
+ from functools import lru_cache
8
+ from typing import Any, Iterable
9
+
10
+ from .chemistry import canonicalize_components, canonicalize_smiles
11
+ from .models import ReactionStep, ReferenceRoute
12
+
13
+ GRAPH_SCHEMA_VERSION = "retro-route-graph-v1"
14
+
15
+
16
+ @dataclass
17
+ class ParsedTree:
18
+ """One submitted molecule/reaction tree and its parse diagnostics."""
19
+
20
+ root_smiles: str | None = None
21
+ steps: list[ReactionStep] = field(default_factory=list)
22
+ molecules_seen: int = 0
23
+ valid_molecules: int = 0
24
+ terminal_claims: list[tuple[str, bool]] = field(default_factory=list)
25
+ errors: list[str] = field(default_factory=list)
26
+ # Missing or malformed reaction metadata: costs structure points, never invalidates chemistry.
27
+ warnings: list[str] = field(default_factory=list)
28
+ # Longest linear sequence: reactions on the longest root-to-leaf path.
29
+ depth: int = 0
30
+
31
+ @property
32
+ def graph_valid(self) -> bool:
33
+ return not self.errors and self.root_smiles is not None and bool(self.steps)
34
+
35
+ @property
36
+ def molecule_validity(self) -> float:
37
+ return self.valid_molecules / self.molecules_seen if self.molecules_seen else 0.0
38
+
39
+ @property
40
+ def first_cut(self) -> tuple[str, ...]:
41
+ if not self.steps:
42
+ return ()
43
+ root = self.root_smiles
44
+ step = next((item for item in self.steps if item.product == root), self.steps[0])
45
+ return tuple(sorted(step.reactants))
46
+
47
+
48
+ @dataclass
49
+ class ParsedSubmission:
50
+ """A route-set payload; parsing never raises so partial reward remains possible."""
51
+
52
+ parse_valid: bool
53
+ trees: list[ParsedTree] = field(default_factory=list)
54
+ errors: list[str] = field(default_factory=list)
55
+ raw: Any = None
56
+
57
+
58
+ def parse_submission(value: Any) -> ParsedSubmission:
59
+ """Parse ``{"routes": [mol-tree, ...]}`` or one bare molecule tree.
60
+
61
+ Invalid chemistry and invalid graph edges are accumulated as diagnostics
62
+ instead of raising. This lets the reward distinguish parse failures from a
63
+ mostly-correct tree with one bad molecule.
64
+ """
65
+
66
+ if isinstance(value, str):
67
+ try:
68
+ value = json.loads(value)
69
+ except json.JSONDecodeError as exc:
70
+ return ParsedSubmission(False, errors=[f"invalid JSON: {exc}"], raw=value)
71
+ if not isinstance(value, dict):
72
+ return ParsedSubmission(False, errors=["submission must be a JSON object"], raw=value)
73
+
74
+ if value.get("type") == "mol":
75
+ routes = [value]
76
+ else:
77
+ routes = value.get("routes")
78
+ if not isinstance(routes, list):
79
+ return ParsedSubmission(False, errors=["submission.routes must be a list"], raw=value)
80
+
81
+ parsed = ParsedSubmission(True, raw=value)
82
+ if not routes:
83
+ parsed.errors.append("submission contains no route trees")
84
+ for index, tree in enumerate(routes):
85
+ result = ParsedTree()
86
+ _parse_molecule_node(tree, result, path=f"routes[{index}]", ancestry=())
87
+ parsed.trees.append(result)
88
+ return parsed
89
+
90
+
91
+ def _parse_molecule_node(
92
+ node: Any,
93
+ result: ParsedTree,
94
+ *,
95
+ path: str,
96
+ ancestry: tuple[str, ...],
97
+ ) -> str | None:
98
+ if not isinstance(node, dict):
99
+ result.errors.append(f"{path}: molecule node must be an object")
100
+ return None
101
+ if node.get("type") != "mol":
102
+ result.errors.append(f"{path}: expected type='mol'")
103
+
104
+ result.molecules_seen += 1
105
+ raw_smiles = node.get("smiles")
106
+ try:
107
+ smiles = canonicalize_smiles(str(raw_smiles or ""))
108
+ result.valid_molecules += 1
109
+ except Exception as exc:
110
+ result.errors.append(f"{path}.smiles: {exc}")
111
+ return None
112
+ if result.root_smiles is None:
113
+ result.root_smiles = smiles
114
+ if smiles in ancestry:
115
+ result.errors.append(f"{path}: route cycle through {smiles}")
116
+ return smiles
117
+
118
+ if "children" not in node:
119
+ result.errors.append(f"{path}.children is required")
120
+ children = node.get("children", [])
121
+ if not isinstance(children, list):
122
+ result.errors.append(f"{path}.children must be a list")
123
+ children = []
124
+ if not children:
125
+ claim = node.get("in_stock")
126
+ if not isinstance(claim, bool):
127
+ result.errors.append(f"{path}.in_stock must be boolean for a leaf")
128
+ claim = False
129
+ result.terminal_claims.append((smiles, bool(claim)))
130
+ return smiles
131
+ if node.get("in_stock") is not False:
132
+ result.errors.append(f"{path}.in_stock must be false for an expanded molecule")
133
+ if len(children) != 1:
134
+ result.errors.append(f"{path}: a molecule must have zero or one reaction child")
135
+
136
+ reaction = children[0] if children else None
137
+ if not isinstance(reaction, dict) or reaction.get("type") != "reaction":
138
+ result.errors.append(f"{path}.children[0]: expected type='reaction'")
139
+ return smiles
140
+ if reaction.get("is_reaction") is not True:
141
+ result.warnings.append(f"{path}.children[0].is_reaction must be true")
142
+ metadata = reaction.get("metadata", {})
143
+ if not isinstance(metadata, dict):
144
+ result.warnings.append(f"{path}.children[0].metadata must be an object")
145
+ metadata = {}
146
+ for required in ("explanation", "confidence", "literature", "precursor_roles"):
147
+ if required not in metadata:
148
+ result.warnings.append(f"{path}.children[0].metadata.{required} is required")
149
+ if not (metadata.get("reaction_class") or metadata.get("classification")):
150
+ result.warnings.append(f"{path}.children[0].metadata.reaction_class is required")
151
+ confidence = metadata.get("confidence")
152
+ if not isinstance(confidence, (int, float)) or isinstance(confidence, bool) or not 0 <= confidence <= 1:
153
+ result.warnings.append(f"{path}.children[0].metadata.confidence must be between 0 and 1")
154
+ if not isinstance(metadata.get("precursor_roles"), dict):
155
+ result.warnings.append(f"{path}.children[0].metadata.precursor_roles must be an object")
156
+ if "children" not in reaction:
157
+ result.errors.append(f"{path}.children[0].children is required")
158
+ reaction_children = reaction.get("children", [])
159
+ if not isinstance(reaction_children, list) or not reaction_children:
160
+ result.errors.append(f"{path}.children[0]: reaction needs molecule children")
161
+ return smiles
162
+
163
+ reactants: list[str] = []
164
+ for index, child in enumerate(reaction_children):
165
+ child_smiles = _parse_molecule_node(
166
+ child,
167
+ result,
168
+ path=f"{path}.children[0].children[{index}]",
169
+ ancestry=(*ancestry, smiles),
170
+ )
171
+ if child_smiles:
172
+ reactants.append(child_smiles)
173
+ if reactants:
174
+ try:
175
+ canonical_reactants = canonicalize_components(reactants)
176
+ except Exception as exc: # pragma: no cover - child parsing already catches this
177
+ result.errors.append(f"{path}: invalid reactants: {exc}")
178
+ else:
179
+ literature = metadata.get("literature") or []
180
+ if not isinstance(literature, list):
181
+ result.warnings.append(f"{path}: metadata.literature must be a list")
182
+ literature = []
183
+ conditions = metadata.get("conditions") or []
184
+ if isinstance(conditions, dict):
185
+ conditions = [conditions]
186
+ if not isinstance(conditions, list):
187
+ conditions = []
188
+ result.steps.append(
189
+ ReactionStep(
190
+ product=smiles,
191
+ reactants=canonical_reactants,
192
+ reaction_class=_text(metadata.get("reaction_class") or metadata.get("classification")),
193
+ conditions=tuple(item for item in conditions if isinstance(item, dict)),
194
+ literature=tuple(item for item in literature if isinstance(item, dict)),
195
+ )
196
+ )
197
+ result.depth = max(result.depth, len(ancestry) + 1)
198
+ return smiles
199
+
200
+
201
+ def route_to_graph(
202
+ target_smiles: str,
203
+ route: ReferenceRoute | Iterable[ReactionStep],
204
+ stock: Iterable[str],
205
+ *,
206
+ source: str = "baseline",
207
+ confidence: float = 1.0,
208
+ ) -> dict[str, Any]:
209
+ """Convert a flat, connected reference route into the renderable tree schema."""
210
+
211
+ steps = tuple(route.steps if isinstance(route, ReferenceRoute) else route)
212
+ by_product = {canonicalize_smiles(step.product): step for step in steps}
213
+ stock_set = (
214
+ _canonicalize_frozen_stock(stock)
215
+ if isinstance(stock, frozenset)
216
+ else frozenset(canonicalize_smiles(item) for item in stock)
217
+ )
218
+
219
+ def build(smiles: str, ancestry: tuple[str, ...]) -> dict[str, Any]:
220
+ canonical = canonicalize_smiles(smiles)
221
+ if canonical in ancestry:
222
+ raise ValueError(f"route contains a cycle through {canonical}")
223
+ step = by_product.get(canonical)
224
+ if step is None:
225
+ return {
226
+ "type": "mol",
227
+ "smiles": canonical,
228
+ "in_stock": canonical in stock_set,
229
+ "children": [],
230
+ }
231
+ metadata: dict[str, Any] = {
232
+ "source": source,
233
+ "explanation": (
234
+ f"Dataset-supported disconnection {step.reaction_id}."
235
+ if step.reaction_id
236
+ else "Dataset-supported disconnection."
237
+ ),
238
+ "reaction_class": step.reaction_class or "unknown",
239
+ "classification": step.reaction_class or "unknown",
240
+ "confidence": confidence,
241
+ "policy_probability": confidence,
242
+ "literature": list(step.literature),
243
+ "conditions": list(step.conditions),
244
+ "precursor_roles": {reactant: "precursor" for reactant in step.reactants},
245
+ }
246
+ return {
247
+ "type": "mol",
248
+ "smiles": canonical,
249
+ "in_stock": False,
250
+ "children": [
251
+ {
252
+ "type": "reaction",
253
+ "is_reaction": True,
254
+ "metadata": metadata,
255
+ "children": [build(reactant, (*ancestry, canonical)) for reactant in step.reactants],
256
+ }
257
+ ],
258
+ }
259
+
260
+ return build(target_smiles, ())
261
+
262
+
263
+ def routes_to_submission(
264
+ target_smiles: str,
265
+ routes: Iterable[ReferenceRoute],
266
+ stock: Iterable[str],
267
+ *,
268
+ source: str = "baseline",
269
+ ) -> dict[str, Any]:
270
+ return {
271
+ "schema_version": GRAPH_SCHEMA_VERSION,
272
+ "routes": [route_to_graph(target_smiles, route, stock, source=source) for route in routes],
273
+ }
274
+
275
+
276
+ def _text(value: Any) -> str | None:
277
+ if value is None:
278
+ return None
279
+ rendered = str(value).strip()
280
+ return rendered or None
281
+
282
+
283
+ @lru_cache(maxsize=8)
284
+ def _canonicalize_frozen_stock(stock: frozenset[str]) -> frozenset[str]:
285
+ return frozenset(canonicalize_smiles(item) for item in stock)
core/retroenv/leakage.py ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Leakage keys shared by the split builder and the precedent tool.
2
+
3
+ Two tasks leak into each other when they share a patent, a route molecule
4
+ (target or intermediate), a reaction, a scaffold group, or are Morgan
5
+ near-duplicates. The builder keeps held-out tasks key-disjoint from train, and
6
+ ``PrecedentIndex`` hides the same keys from a train task's own searches so that
7
+ training never rewards looking up an answer evaluation cannot offer.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import json
13
+ from dataclasses import dataclass
14
+ from pathlib import Path
15
+ from typing import Any, Iterable
16
+
17
+ from .chemistry import canonicalize_smiles, scaffold_group_key
18
+ from .models import RetroTask
19
+ from .reactions import free_key
20
+
21
+ Key = tuple[str, str]
22
+
23
+
24
+ @dataclass(frozen=True)
25
+ class LeakageRules:
26
+ generic_scaffolds: frozenset[str] = frozenset()
27
+ near_duplicate_threshold: float = 0.90
28
+
29
+ @classmethod
30
+ def from_manifest(cls, manifest: dict[str, Any] | str | Path | None) -> "LeakageRules":
31
+ if manifest is None:
32
+ return cls()
33
+ if not isinstance(manifest, dict):
34
+ path = Path(manifest)
35
+ if not path.exists():
36
+ return cls()
37
+ manifest = json.loads(path.read_text())
38
+ leakage = manifest.get("leakage", {})
39
+ return cls(
40
+ generic_scaffolds=frozenset(leakage.get("generic_scaffolds", ())),
41
+ near_duplicate_threshold=float(leakage.get("near_duplicate_threshold", 0.90)),
42
+ )
43
+
44
+ def scaffold(self, smiles: str) -> str:
45
+ return scaffold_group_key(smiles, exact_single_ring=True, generic=self.generic_scaffolds)
46
+
47
+
48
+ def molecule_keys(molecules: Iterable[str], rules: LeakageRules) -> set[Key]:
49
+ keys: set[Key] = set()
50
+ for smiles in molecules:
51
+ keys.add(("molecule", smiles))
52
+ keys.add(("scaffold", rules.scaffold(smiles)))
53
+ return keys
54
+
55
+
56
+ def reaction_key(product: str, reactants: Iterable[str]) -> Key:
57
+ product_key, reactant_key = free_key(product, reactants)
58
+ return ("reaction", f"{product_key}>>{'.'.join(reactant_key)}")
59
+
60
+
61
+ def task_molecules(task: RetroTask) -> set[str]:
62
+ """The target and every known-route intermediate (leaves are building blocks, not keys)."""
63
+ molecules = {canonicalize_smiles(task.target_smiles)}
64
+ for route in task.reference_routes:
65
+ molecules.update(canonicalize_smiles(step.product) for step in route.steps)
66
+ return molecules
67
+
68
+
69
+ def task_keys(task: RetroTask, rules: LeakageRules) -> set[Key]:
70
+ """Patents count only for the target's own patent routes; a witness route's reactions come
71
+ from filings about other targets, whose chemistry the molecule and reaction keys already cover."""
72
+ keys = molecule_keys(task_molecules(task), rules)
73
+ for route in task.reference_routes:
74
+ if route.kind == "patent":
75
+ keys.update(("patent", str(source["patent"])) for source in route.source if source.get("patent"))
76
+ keys.update(reaction_key(step.product, step.reactants) for step in route.steps)
77
+ return keys
core/retroenv/models.py ADDED
@@ -0,0 +1,189 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Dependency-light domain models shared by the pipeline and environment."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass, field
6
+ from typing import Any
7
+
8
+ TASK_SCHEMA = "retro-task-v2"
9
+ VARIANTS = ("standard", "max_depth", "restricted_stock", "forbidden_class", "diversity")
10
+ ROUTE_KINDS = ("patent", "witness")
11
+
12
+
13
+ @dataclass(frozen=True)
14
+ class ReactionStep:
15
+ product: str
16
+ reactants: tuple[str, ...]
17
+ reaction_class: str | None = None
18
+ reaction_id: str | None = None
19
+ conditions: tuple[dict[str, Any], ...] = ()
20
+ literature: tuple[dict[str, Any], ...] = ()
21
+
22
+ @classmethod
23
+ def from_dict(cls, value: dict[str, Any]) -> "ReactionStep":
24
+ if not isinstance(value, dict):
25
+ raise TypeError("each route step must be an object")
26
+ reactants = value.get("reactants")
27
+ if isinstance(reactants, str):
28
+ reactants = [part for part in reactants.split(".") if part]
29
+ if not isinstance(reactants, (list, tuple)):
30
+ raise TypeError("step.reactants must be a list or dot-separated string")
31
+ return cls(
32
+ product=str(value.get("product", "")).strip(),
33
+ reactants=tuple(str(item).strip() for item in reactants if str(item).strip()),
34
+ reaction_class=_optional_text(value.get("reaction_class")),
35
+ reaction_id=_optional_text(value.get("reaction_id")),
36
+ conditions=tuple(item for item in (value.get("conditions") or ()) if isinstance(item, dict)),
37
+ literature=tuple(item for item in (value.get("literature") or ()) if isinstance(item, dict)),
38
+ )
39
+
40
+ def to_dict(self, *, include_evidence: bool = True) -> dict[str, Any]:
41
+ value: dict[str, Any] = {"product": self.product, "reactants": list(self.reactants)}
42
+ if self.reaction_class:
43
+ value["reaction_class"] = self.reaction_class
44
+ if include_evidence:
45
+ if self.reaction_id:
46
+ value["reaction_id"] = self.reaction_id
47
+ value["conditions"] = list(self.conditions)
48
+ value["literature"] = list(self.literature)
49
+ return value
50
+
51
+
52
+ @dataclass(frozen=True)
53
+ class ReferenceRoute:
54
+ """A hidden known route: ``patent`` routes come from one filing, ``witness`` routes are
55
+ stock-closed recombinations of corpus reactions that prove a constrained task is solvable."""
56
+
57
+ route_id: str
58
+ steps: tuple[ReactionStep, ...]
59
+ kind: str = "patent"
60
+ source: tuple[dict[str, Any], ...] = ()
61
+
62
+ @classmethod
63
+ def from_dict(cls, value: dict[str, Any]) -> "ReferenceRoute":
64
+ kind = str(value.get("kind", "patent"))
65
+ if kind not in ROUTE_KINDS:
66
+ raise ValueError(f"unknown reference route kind {kind!r}")
67
+ return cls(
68
+ route_id=str(value.get("route_id", "reference")),
69
+ steps=tuple(ReactionStep.from_dict(step) for step in value.get("steps", [])),
70
+ kind=kind,
71
+ source=tuple(value.get("source") or ()),
72
+ )
73
+
74
+ def to_dict(self) -> dict[str, Any]:
75
+ return {
76
+ "route_id": self.route_id,
77
+ "kind": self.kind,
78
+ "steps": [step.to_dict() for step in self.steps],
79
+ "source": list(self.source),
80
+ }
81
+
82
+
83
+ @dataclass(frozen=True)
84
+ class TaskConstraints:
85
+ forbidden_classes: tuple[str, ...] = ()
86
+ excluded_stock: tuple[str, ...] = ()
87
+
88
+ @classmethod
89
+ def from_dict(cls, value: dict[str, Any] | None) -> "TaskConstraints":
90
+ value = value or {}
91
+ return cls(
92
+ forbidden_classes=tuple(str(item) for item in value.get("forbidden_classes") or ()),
93
+ excluded_stock=tuple(str(item) for item in value.get("excluded_stock") or ()),
94
+ )
95
+
96
+ def to_dict(self) -> dict[str, Any]:
97
+ return {"forbidden_classes": list(self.forbidden_classes), "excluded_stock": list(self.excluded_stock)}
98
+
99
+
100
+ @dataclass(frozen=True)
101
+ class RetroTask:
102
+ task_id: str
103
+ target_smiles: str
104
+ stock_id: str
105
+ split: str
106
+ max_depth: int
107
+ reference_routes: tuple[ReferenceRoute, ...]
108
+ parent_id: str = ""
109
+ variant: str = "standard"
110
+ min_routes: int = 1
111
+ max_routes: int = 5
112
+ constraints: TaskConstraints = field(default_factory=TaskConstraints)
113
+ difficulty: dict[str, Any] = field(default_factory=dict)
114
+ schema_version: str = TASK_SCHEMA
115
+
116
+ @classmethod
117
+ def from_dict(cls, value: dict[str, Any]) -> "RetroTask":
118
+ task = cls(
119
+ task_id=str(value["task_id"]),
120
+ parent_id=str(value.get("parent_id") or value["task_id"]),
121
+ variant=str(value.get("variant", "standard")),
122
+ target_smiles=str(value["target_smiles"]),
123
+ stock_id=str(value["stock_id"]),
124
+ split=str(value.get("split", "train")),
125
+ max_depth=int(value["max_depth"]),
126
+ min_routes=int(value.get("min_routes", 1)),
127
+ max_routes=int(value.get("max_routes", 5)),
128
+ constraints=TaskConstraints.from_dict(value.get("constraints")),
129
+ reference_routes=tuple(ReferenceRoute.from_dict(route) for route in value.get("reference_routes", [])),
130
+ difficulty=dict(value.get("difficulty") or {}),
131
+ schema_version=str(value.get("schema_version", TASK_SCHEMA)),
132
+ )
133
+ if task.variant not in VARIANTS:
134
+ raise ValueError(f"unknown task variant {task.variant!r}")
135
+ if task.max_depth < 1:
136
+ raise ValueError("max_depth must be positive")
137
+ if not 1 <= task.min_routes <= task.max_routes <= 5:
138
+ raise ValueError("route count bounds must satisfy 1 <= min_routes <= max_routes <= 5")
139
+ if not task.reference_routes:
140
+ raise ValueError(f"task {task.task_id!r} has no private reference routes")
141
+ return task
142
+
143
+ def to_dict(self, *, include_hidden: bool = True) -> dict[str, Any]:
144
+ value: dict[str, Any] = {
145
+ "schema_version": self.schema_version,
146
+ "task_id": self.task_id,
147
+ "parent_id": self.parent_id,
148
+ "variant": self.variant,
149
+ "split": self.split,
150
+ "target_smiles": self.target_smiles,
151
+ "stock_id": self.stock_id,
152
+ "max_depth": self.max_depth,
153
+ "min_routes": self.min_routes,
154
+ "max_routes": self.max_routes,
155
+ "constraints": self.constraints.to_dict(),
156
+ }
157
+ if include_hidden:
158
+ value["difficulty"] = self.difficulty
159
+ value["reference_routes"] = [route.to_dict() for route in self.reference_routes]
160
+ return value
161
+
162
+
163
+ @dataclass(frozen=True)
164
+ class ScoreResult:
165
+ reward: float
166
+ valid: bool
167
+ verification_tier: str
168
+ hard_failures: tuple[str, ...]
169
+ components: dict[str, float]
170
+ metrics: dict[str, Any]
171
+ step_results: tuple[dict[str, Any], ...]
172
+
173
+ def to_dict(self) -> dict[str, Any]:
174
+ return {
175
+ "reward": self.reward,
176
+ "valid": self.valid,
177
+ "verification_tier": self.verification_tier,
178
+ "hard_failures": list(self.hard_failures),
179
+ "components": self.components,
180
+ "metrics": self.metrics,
181
+ "step_results": list(self.step_results),
182
+ }
183
+
184
+
185
+ def _optional_text(value: Any) -> str | None:
186
+ if value is None:
187
+ return None
188
+ text = str(value).strip()
189
+ return text or None
core/retroenv/reactions.py ADDED
@@ -0,0 +1,274 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Reference-free single-step support: a frozen reaction corpus plus rdchiral retro-templates.
2
+
3
+ A step ``product <- reactants`` is supported when it is a known corpus reaction
4
+ (stereo-free canonical key, optionally padded with common reagents) or when a
5
+ radius-1 retro-template seen at least ``min_count`` times in the corpus turns the
6
+ product into a subset of the proposed reactants whose extras are common reagents.
7
+ Comparison is stereo-free; whether stereo also agrees is reported separately.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import gzip
13
+ import io
14
+ import itertools
15
+ import json
16
+ import threading
17
+ from collections import OrderedDict
18
+ from contextlib import redirect_stdout
19
+ from dataclasses import asdict, dataclass
20
+ from pathlib import Path
21
+ from typing import Any, Iterable, Iterator
22
+
23
+ import numpy as np
24
+ from rdchiral.main import rdchiralReactants, rdchiralReaction, rdchiralRun
25
+ from rdkit import Chem, DataStructs, RDLogger
26
+
27
+ from .chemistry import ChemistryError, canonicalize_components, canonicalize_smiles
28
+
29
+ RDLogger.DisableLog("rdApp.*")
30
+
31
+ DEFAULT_MIN_COUNT = 5
32
+ FP_SIZE = 2048
33
+ CACHE_SIZE = 50_000
34
+
35
+ StepKey = tuple[str, tuple[str, ...]]
36
+
37
+
38
+ @dataclass(frozen=True)
39
+ class StepSupport:
40
+ """``kind`` is ``corpus``, ``template``, ``none`` or ``invalid``."""
41
+
42
+ kind: str
43
+ product: str
44
+ reactants: tuple[str, ...]
45
+ template_count: int = 0
46
+ stereo_match: bool | None = None
47
+ error: str | None = None
48
+
49
+ @property
50
+ def supported(self) -> bool:
51
+ return self.kind in {"corpus", "template"}
52
+
53
+ def to_dict(self) -> dict[str, Any]:
54
+ return asdict(self)
55
+
56
+
57
+ def free_key(product: str, reactants: Iterable[str]) -> StepKey:
58
+ """Stereo-free canonical (product, sorted reactant components) key."""
59
+ return canonicalize_smiles(product, isomeric=False), canonicalize_components(reactants, isomeric=False)
60
+
61
+
62
+ def _query(smarts: str) -> Chem.Mol:
63
+ mol = Chem.MolFromSmarts(smarts)
64
+ mol.UpdatePropertyCache(strict=False)
65
+ Chem.FastFindRings(mol)
66
+ return mol
67
+
68
+
69
+ def _pattern_fp(mol: Chem.Mol) -> np.ndarray:
70
+ bits = np.zeros(FP_SIZE, dtype=np.uint8)
71
+ DataStructs.ConvertToNumpyArray(Chem.PatternFingerprint(mol, fpSize=FP_SIZE), bits)
72
+ return np.packbits(bits).view(np.uint64)
73
+
74
+
75
+ def run_template(reaction: rdchiralReaction, product: rdchiralReactants) -> list[str]:
76
+ try:
77
+ with redirect_stdout(io.StringIO()):
78
+ return rdchiralRun(reaction, product)
79
+ except Exception:
80
+ return []
81
+
82
+
83
+ class TemplateIndex:
84
+ """Retro-templates screened by product-side pattern fingerprints, then substructure."""
85
+
86
+ def __init__(self, template_counts: dict[str, int]):
87
+ ordered = sorted(template_counts.items(), key=lambda item: (-item[1], item[0]))
88
+ self.smarts = [smarts for smarts, _ in ordered]
89
+ self.counts = np.array([count for _, count in ordered], dtype=np.int64)
90
+ product_sides = [smarts.split(">>")[0] for smarts in self.smarts]
91
+ unique_sides = sorted(set(product_sides))
92
+ side_id = {side: i for i, side in enumerate(unique_sides)}
93
+ self._pattern_of = np.array([side_id[side] for side in product_sides], dtype=np.int64)
94
+ self._patterns = [_query(side) for side in unique_sides]
95
+ # Pattern-fingerprint screening is only safe for product-side queries.
96
+ self._pattern_fps = (
97
+ np.stack([_pattern_fp(pattern) for pattern in self._patterns])
98
+ if self._patterns
99
+ else np.zeros((0, FP_SIZE // 64), dtype=np.uint64)
100
+ )
101
+ fragment_lists = [smarts.split(">>")[1].split(".") for smarts in self.smarts]
102
+ unique_fragments = sorted({fragment for fragments in fragment_lists for fragment in fragments})
103
+ fragment_id = {fragment: i for i, fragment in enumerate(unique_fragments)}
104
+ self._fragments = [_query(fragment) for fragment in unique_fragments]
105
+ self._template_fragments = [tuple(fragment_id[f] for f in fragments) for fragments in fragment_lists]
106
+ self._reactions: dict[int, rdchiralReaction] = {}
107
+
108
+ def __len__(self) -> int:
109
+ return len(self.smarts)
110
+
111
+ def _reaction(self, template_id: int) -> rdchiralReaction:
112
+ if template_id not in self._reactions:
113
+ self._reactions[template_id] = rdchiralReaction(self.smarts[template_id])
114
+ return self._reactions[template_id]
115
+
116
+ def matching(self, product: Chem.Mol) -> np.ndarray:
117
+ if not len(self._patterns):
118
+ return np.zeros(0, dtype=np.int64)
119
+ fp = _pattern_fp(product)
120
+ screened = np.flatnonzero(~np.any(self._pattern_fps & ~fp, axis=1))
121
+ matched = np.zeros(len(self._patterns), dtype=bool)
122
+ matched[[p for p in screened if product.HasSubstructMatch(self._patterns[p])]] = True
123
+ return np.flatnonzero(matched[self._pattern_of])
124
+
125
+ def proposals(self, product_smiles: str, limit: int = 50) -> list[tuple[tuple[str, ...], int]]:
126
+ """Stereo-free reactant sets the templates propose for ``product``, most frequent template first."""
127
+ product = rdchiralReactants(canonicalize_smiles(product_smiles))
128
+ seen: dict[tuple[str, ...], int] = {}
129
+ for template_id in self.matching(product.reactants_achiral):
130
+ for outcome in run_template(self._reaction(int(template_id)), product):
131
+ try:
132
+ reactants = canonicalize_components(outcome, isomeric=False)
133
+ except ChemistryError:
134
+ continue
135
+ seen.setdefault(reactants, int(self.counts[template_id]))
136
+ if len(seen) >= limit:
137
+ break
138
+ return list(seen.items())[:limit]
139
+
140
+ def first_support(
141
+ self, product_smiles: str, reactants: tuple[str, ...], extras: frozenset[str]
142
+ ) -> tuple[int, str] | None:
143
+ product = rdchiralReactants(canonicalize_smiles(product_smiles))
144
+ reactant_mols = [Chem.MolFromSmiles(smiles) for smiles in reactants]
145
+ proposed = set(reactants)
146
+ present: dict[int, bool] = {}
147
+ for template_id in self.matching(product.reactants_achiral):
148
+ if not self._fragments_present(int(template_id), reactant_mols, present):
149
+ continue
150
+ for outcome in run_template(self._reaction(int(template_id)), product):
151
+ try:
152
+ produced = set(canonicalize_components(outcome, isomeric=False))
153
+ except ChemistryError:
154
+ continue
155
+ if produced and produced <= proposed and proposed - produced <= extras:
156
+ return int(template_id), outcome
157
+ return None
158
+
159
+ def _fragments_present(self, template_id: int, reactant_mols: list[Chem.Mol], present: dict[int, bool]) -> bool:
160
+ for fragment in self._template_fragments[template_id]:
161
+ if fragment not in present:
162
+ pattern = self._fragments[fragment]
163
+ present[fragment] = any(mol is not None and mol.HasSubstructMatch(pattern) for mol in reactant_mols)
164
+ if not present[fragment]:
165
+ return False
166
+ return True
167
+
168
+
169
+ class ReactionLibrary:
170
+ """Judge arbitrary single steps without consulting any task's hidden route."""
171
+
172
+ def __init__(
173
+ self,
174
+ corpus: Iterable[StepKey],
175
+ templates: dict[str, int],
176
+ reagents: Iterable[str],
177
+ *,
178
+ min_count: int = DEFAULT_MIN_COUNT,
179
+ ):
180
+ self.min_count = min_count
181
+ self.corpus = frozenset(corpus)
182
+ self.reagents = frozenset(reagents)
183
+ self.index = TemplateIndex({smarts: n for smarts, n in templates.items() if n >= min_count})
184
+ self._cache: OrderedDict[tuple[StepKey, frozenset[StepKey]], StepSupport] = OrderedDict()
185
+ self._lock = threading.Lock() # servers call tools from worker threads
186
+
187
+ def support(
188
+ self,
189
+ product: str,
190
+ reactants: Iterable[str],
191
+ *,
192
+ exclude: frozenset[StepKey] = frozenset(),
193
+ ) -> StepSupport:
194
+ """Support for ``product <- reactants``; ``exclude`` hides corpus keys (never templates)."""
195
+ reactant_list = [str(item) for item in reactants]
196
+ try:
197
+ key = free_key(product, reactant_list)
198
+ stereo_reactants = canonicalize_components(reactant_list)
199
+ except ChemistryError as exc:
200
+ return StepSupport("invalid", "", (), error=str(exc))
201
+ product_key, reactant_key = key
202
+ if not reactant_key:
203
+ return StepSupport("invalid", product_key, (), error="a step needs at least one reactant")
204
+ if product_key in reactant_key:
205
+ return StepSupport("invalid", product_key, reactant_key, error="product appears unchanged among reactants")
206
+ cache_key = (key, exclude)
207
+ with self._lock:
208
+ cached = self._cache.get(cache_key)
209
+ if cached is not None:
210
+ self._cache.move_to_end(cache_key)
211
+ return cached
212
+ result = self._support(product, key, stereo_reactants, exclude)
213
+ with self._lock:
214
+ self._cache[cache_key] = result
215
+ if len(self._cache) > CACHE_SIZE:
216
+ self._cache.popitem(last=False)
217
+ return result
218
+
219
+ def _support(
220
+ self, product: str, key: StepKey, stereo_reactants: tuple[str, ...], exclude: frozenset[StepKey]
221
+ ) -> StepSupport:
222
+ product_key, reactant_key = key
223
+ if self._in_corpus(key, exclude):
224
+ return StepSupport("corpus", product_key, reactant_key)
225
+ extras = frozenset(smiles for smiles in reactant_key if smiles in self.reagents)
226
+ try:
227
+ found = self.index.first_support(product, reactant_key, extras)
228
+ except Exception as exc: # rdchiral can fail on exotic valences
229
+ return StepSupport("none", product_key, reactant_key, error=f"template engine: {exc}")
230
+ if found is None:
231
+ return StepSupport("none", product_key, reactant_key)
232
+ template_id, outcome = found
233
+ try:
234
+ stereo_match = set(canonicalize_components(outcome)) <= set(stereo_reactants)
235
+ except ChemistryError:
236
+ stereo_match = None
237
+ return StepSupport("template", product_key, reactant_key, int(self.index.counts[template_id]), stereo_match)
238
+
239
+ def _in_corpus(self, key: StepKey, exclude: frozenset[StepKey]) -> bool:
240
+ product, reactants = key
241
+ padding = [smiles for smiles in reactants if smiles in self.reagents]
242
+ for size in range(len(padding) + 1):
243
+ for dropped in itertools.combinations(padding, size):
244
+ core = tuple(smiles for smiles in reactants if smiles not in dropped)
245
+ if core and (product, core) in self.corpus and (product, core) not in exclude:
246
+ return True
247
+ return False
248
+
249
+ @classmethod
250
+ def load(
251
+ cls,
252
+ directory: str | Path,
253
+ *,
254
+ templates: str = "templates.json",
255
+ visible_only: bool = False,
256
+ min_count: int = DEFAULT_MIN_COUNT,
257
+ ) -> "ReactionLibrary":
258
+ root = Path(directory)
259
+ corpus = (
260
+ (record["product"], tuple(record["reactants"]))
261
+ for record in iter_reactions(root / "reactions.jsonl.gz")
262
+ if record["visible"] or not visible_only
263
+ )
264
+ counts = json.loads((root / templates).read_text())
265
+ reagents = json.loads((root / "reagents.json").read_text())
266
+ return cls(corpus, counts, reagents, min_count=min_count)
267
+
268
+
269
+ def iter_reactions(path: str | Path) -> Iterator[dict[str, Any]]:
270
+ """Rows of the library's reaction table (stereo-free keys plus provenance)."""
271
+ with gzip.open(path, "rt") as handle:
272
+ for line in handle:
273
+ if line.strip():
274
+ yield json.loads(line)
core/retroenv/retrieval.py ADDED
@@ -0,0 +1,330 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Bounded, deterministic retrieval indexes used by the agent tools."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import threading
6
+ from dataclasses import dataclass
7
+ from functools import lru_cache
8
+ from typing import Any, Iterable
9
+
10
+ import numpy as np
11
+ from rdkit import Chem, DataStructs
12
+ from rdkit.Chem import Descriptors, rdFingerprintGenerator, rdMolDescriptors
13
+
14
+ from .chemistry import canonicalize_smiles
15
+ from .leakage import Key, LeakageRules, molecule_keys, reaction_key, task_keys, task_molecules
16
+ from .models import RetroTask
17
+
18
+ CLASS_SMARTS = {
19
+ "alcohol": "[OX2H][CX4]",
20
+ "amine": "[NX3;H1,H2;!$(NC=O)]",
21
+ "carboxylic_acid": "C(=O)[OX2H1]",
22
+ "aldehyde": "[CX3H1](=O)[#6]",
23
+ "ketone": "[#6][CX3](=O)[#6]",
24
+ "aryl_halide": "[c][F,Cl,Br,I]",
25
+ "boronic_acid": "B(O)O",
26
+ "ester": "C(=O)O[#6]",
27
+ "alkene": "[CX3]=[CX3]",
28
+ "alkyne": "[CX2]#[CX2]",
29
+ }
30
+
31
+
32
+ @dataclass(frozen=True)
33
+ class Precedent:
34
+ product: str
35
+ reactants: tuple[str, ...]
36
+ reaction_class: str
37
+ reagents: tuple[str, ...]
38
+ patents: tuple[str, ...]
39
+ keys: frozenset[Key]
40
+
41
+
42
+ class PrecedentIndex:
43
+ """Search train-visible corpus reactions without exposing held-out answers.
44
+
45
+ The builder marks a library reaction visible only when it shares no leakage
46
+ key with any held-out task, so held-out tasks see the whole visible corpus.
47
+ Given a train ``task``, ``search`` also hides that task's own keys and
48
+ near-duplicates, so a policy cannot learn to look up answers that held-out
49
+ evaluation never offers.
50
+ """
51
+
52
+ def __init__(self, reactions: Iterable[dict[str, Any]], rules: LeakageRules | None = None):
53
+ self.rules = rules or LeakageRules()
54
+ records = []
55
+ for row in reactions:
56
+ if not row.get("visible", True):
57
+ continue
58
+ product = row["product_smiles"]
59
+ reactants = tuple(row["reactant_smiles"])
60
+ keys = molecule_keys([product], self.rules) | {reaction_key(product, reactants)}
61
+ keys |= {("patent", patent) for patent in row.get("patents", ())}
62
+ records.append(
63
+ Precedent(
64
+ product=product,
65
+ reactants=reactants,
66
+ reaction_class=row.get("reaction_class", "other"),
67
+ reagents=tuple(row.get("reagents", ())),
68
+ patents=tuple(row.get("patents", ())),
69
+ keys=frozenset(keys),
70
+ )
71
+ )
72
+ generator = rdFingerprintGenerator.GetMorganGenerator(radius=2, fpSize=2048)
73
+ self._finish(tuple(records), [generator.GetFingerprint(Chem.MolFromSmiles(r.product)) for r in records])
74
+
75
+ @classmethod
76
+ def from_records(
77
+ cls, records: Iterable[Precedent], fingerprints: Iterable[Any], rules: LeakageRules | None = None
78
+ ) -> "PrecedentIndex":
79
+ """Rebuild from a serving index: the records and fingerprints ``__init__`` would compute."""
80
+ index = cls.__new__(cls)
81
+ index.rules = rules or LeakageRules()
82
+ index._finish(tuple(records), list(fingerprints))
83
+ return index
84
+
85
+ def _finish(self, records: tuple[Precedent, ...], fingerprints: list[Any]) -> None:
86
+ if len(records) != len(fingerprints):
87
+ raise ValueError(f"{len(records)} precedents but {len(fingerprints)} fingerprints")
88
+ self.records = records
89
+ self._generator = rdFingerprintGenerator.GetMorganGenerator(radius=2, fpSize=2048)
90
+ self._fingerprints = fingerprints
91
+ self._classes = np.array([_normalize_class(r.reaction_class) for r in self.records])
92
+ self._key_index: dict[Key, list[int]] = {}
93
+ for index, record in enumerate(self.records):
94
+ for key in record.keys:
95
+ self._key_index.setdefault(key, []).append(index)
96
+ self._hidden: dict[tuple[str, str], np.ndarray] = {}
97
+
98
+ def fingerprints(self) -> list[Any]:
99
+ """Product fingerprints in record order, for writing a serving index."""
100
+ return list(self._fingerprints)
101
+
102
+ def hidden(self, task: RetroTask) -> np.ndarray:
103
+ """Boolean mask of records sharing a leakage key with ``task`` or near-duplicating one of its molecules."""
104
+ cached = self._hidden.get((task.task_id, task.split))
105
+ if cached is not None:
106
+ return cached
107
+ mask = np.zeros(len(self.records), dtype=bool)
108
+ if task.split == "train" and self.records:
109
+ for key in task_keys(task, self.rules):
110
+ mask[self._key_index.get(key, [])] = True
111
+ for smiles in task_molecules(task):
112
+ fingerprint = self._generator.GetFingerprint(Chem.MolFromSmiles(smiles))
113
+ similarity = np.array(DataStructs.BulkTanimotoSimilarity(fingerprint, self._fingerprints))
114
+ mask |= similarity >= self.rules.near_duplicate_threshold
115
+ self._hidden[(task.task_id, task.split)] = mask
116
+ return mask
117
+
118
+ def search(
119
+ self,
120
+ *,
121
+ task: RetroTask | None = None,
122
+ product_smiles: str | None = None,
123
+ reaction_class: str | None = None,
124
+ limit: int = 10,
125
+ ) -> dict[str, Any]:
126
+ limit = max(1, min(int(limit), 20))
127
+ canonical_product = canonicalize_smiles(product_smiles) if product_smiles else None
128
+ if not self.records:
129
+ similarity = np.zeros(0)
130
+ elif canonical_product:
131
+ fingerprint = self._generator.GetFingerprint(Chem.MolFromSmiles(canonical_product))
132
+ similarity = np.array(DataStructs.BulkTanimotoSimilarity(fingerprint, self._fingerprints))
133
+ else:
134
+ similarity = np.zeros(len(self.records))
135
+ allowed = ~self.hidden(task) if task is not None else np.ones(len(self.records), dtype=bool)
136
+ normalized_class = _normalize_class(reaction_class)
137
+ if normalized_class:
138
+ allowed &= self._classes == normalized_class
139
+ candidates = np.flatnonzero(allowed)
140
+ order = candidates[np.lexsort((candidates, -similarity[candidates]))]
141
+ results = [
142
+ {
143
+ "product_smiles": self.records[i].product,
144
+ "reactants": list(self.records[i].reactants),
145
+ "reaction_class": self.records[i].reaction_class,
146
+ "similarity": round(float(similarity[i]), 6),
147
+ "reagents": list(self.records[i].reagents[:8]),
148
+ "patents": list(self.records[i].patents[:3]),
149
+ }
150
+ for i in order[:limit]
151
+ ]
152
+ return {
153
+ "query": {"product_smiles": canonical_product, "reaction_class": reaction_class},
154
+ "results": results,
155
+ "returned": len(results),
156
+ "truncated": len(order) > limit,
157
+ "visibility": "train-visible corpus reactions only",
158
+ }
159
+
160
+
161
+ class StockIndex:
162
+ """The only stock surface: exact, InChIKey, class, SMARTS, or similarity."""
163
+
164
+ def __init__(self, stock: Iterable[str]):
165
+ smiles = tuple(sorted({canonicalize_smiles(item) for item in stock}))
166
+ molecules = tuple(Chem.MolFromSmiles(item) for item in smiles)
167
+ generator = rdFingerprintGenerator.GetMorganGenerator(radius=2, fpSize=2048)
168
+ self._finish(smiles, tuple(generator.GetFingerprint(molecule) for molecule in molecules), molecules)
169
+
170
+ @classmethod
171
+ def from_canonical(cls, smiles: Iterable[str], fingerprints: Iterable[Any]) -> "StockIndex":
172
+ """Rebuild from a serving index: sorted canonical SMILES and their fingerprints.
173
+
174
+ Molecules are parsed only when a class or substructure query first needs them;
175
+ exact, InChIKey and similarity search never do, and parsing them all costs about a
176
+ gigabyte for this stock.
177
+ """
178
+ index = cls.__new__(cls)
179
+ index._finish(tuple(smiles), tuple(fingerprints), None)
180
+ if list(index.smiles) != sorted(index.smiles):
181
+ raise ValueError("stock SMILES must be sorted, as StockIndex orders them")
182
+ return index
183
+
184
+ def _finish(self, smiles: tuple[str, ...], fingerprints: tuple[Any, ...], molecules: tuple | None) -> None:
185
+ if len(smiles) != len(fingerprints):
186
+ raise ValueError(f"{len(smiles)} stock molecules but {len(fingerprints)} fingerprints")
187
+ self.smiles = smiles
188
+ self._molecules = molecules
189
+ self._molecules_lock = threading.Lock()
190
+ self._known = frozenset(self.smiles)
191
+ self._by_inchikey: dict[str, str] | None = None # built on the first InChIKey query; InChI is slow
192
+ self._generator = rdFingerprintGenerator.GetMorganGenerator(radius=2, fpSize=2048)
193
+ self._fingerprints = fingerprints
194
+
195
+ @property
196
+ def known(self) -> frozenset[str]:
197
+ """The stock as one shared set; sessions reuse it instead of rebuilding it per episode."""
198
+ return self._known
199
+
200
+ @property
201
+ def molecules(self) -> tuple:
202
+ if self._molecules is None:
203
+ with self._molecules_lock:
204
+ if self._molecules is None:
205
+ self._molecules = tuple(Chem.MolFromSmiles(item) for item in self.smiles)
206
+ return self._molecules
207
+
208
+ def fingerprints(self) -> tuple[Any, ...]:
209
+ """Fingerprints in SMILES order, for writing a serving index."""
210
+ return self._fingerprints
211
+
212
+ @staticmethod
213
+ @lru_cache(maxsize=100_000)
214
+ def inchikey(smiles: str) -> str:
215
+ return Chem.MolToInchiKey(Chem.MolFromSmiles(smiles))
216
+
217
+ def retrieve(
218
+ self, query: str, *, mode: str = "auto", limit: int = 10, excluded: frozenset[str] = frozenset()
219
+ ) -> dict[str, Any]:
220
+ """``excluded`` molecules are treated as absent from the stock (restricted-stock tasks)."""
221
+ limit = max(1, min(int(limit), 20))
222
+ query = str(query or "").strip()
223
+ if not query:
224
+ return {"mode": mode, "query": query, "results": [], "error": "query is empty"}
225
+ if mode == "auto" and ":" in query:
226
+ prefix, value = query.split(":", 1)
227
+ if prefix in {"exact", "inchikey", "class", "substructure", "similarity"}:
228
+ mode, query = prefix, value.strip()
229
+ if mode == "auto":
230
+ mode = "inchikey" if len(query) == 27 and query.count("-") == 2 else "exact"
231
+
232
+ matches: list[tuple[float, str]] = []
233
+ try:
234
+ if mode == "exact":
235
+ canonical = canonicalize_smiles(query)
236
+ if canonical in self._known:
237
+ matches = [(1.0, canonical)]
238
+ elif mode == "inchikey":
239
+ if self._by_inchikey is None:
240
+ self._by_inchikey = {self.inchikey(smiles): smiles for smiles in self.smiles}
241
+ smiles = self._by_inchikey.get(query.upper())
242
+ if smiles:
243
+ matches = [(1.0, smiles)]
244
+ elif mode in {"class", "substructure"}:
245
+ smarts = CLASS_SMARTS.get(query.lower().replace(" ", "_")) if mode == "class" else query
246
+ if not smarts:
247
+ raise ValueError(f"unknown class {query!r}; available: {sorted(CLASS_SMARTS)}")
248
+ pattern = Chem.MolFromSmarts(smarts)
249
+ if pattern is None:
250
+ raise ValueError("invalid SMARTS query")
251
+ matches = [
252
+ (1.0, s) for s, molecule in zip(self.smiles, self.molecules) if molecule.HasSubstructMatch(pattern)
253
+ ]
254
+ elif mode == "similarity":
255
+ query_fp = self._generator.GetFingerprint(Chem.MolFromSmiles(canonicalize_smiles(query)))
256
+ values = DataStructs.BulkTanimotoSimilarity(query_fp, self._fingerprints)
257
+ matches = sorted(zip(values, self.smiles), key=lambda item: (-item[0], item[1]))
258
+ else:
259
+ raise ValueError("mode must be auto, exact, inchikey, class, substructure, or similarity")
260
+ except Exception as exc:
261
+ return {"mode": mode, "query": query, "results": [], "error": str(exc)}
262
+ if excluded:
263
+ matches = [match for match in matches if match[1] not in excluded]
264
+ rendered = [
265
+ {"smiles": smiles, "inchikey": self.inchikey(smiles), "similarity": round(score, 6)}
266
+ for score, smiles in matches[:limit]
267
+ ]
268
+ return {
269
+ "mode": mode,
270
+ "query": query,
271
+ "results": rendered,
272
+ "returned": len(rendered),
273
+ "truncated": len(matches) > limit,
274
+ }
275
+
276
+
277
+ _PRELOADED_STOCKS: dict[frozenset[str], StockIndex] = {}
278
+
279
+
280
+ def register_stock_index(index: StockIndex) -> frozenset[str]:
281
+ """Make a prebuilt index (from a serving index) the one ``cached_stock_index`` returns for its stock."""
282
+ _PRELOADED_STOCKS[index.known] = index
283
+ return index.known
284
+
285
+
286
+ @lru_cache(maxsize=8)
287
+ def cached_stock_index(stock: frozenset[str]) -> StockIndex:
288
+ """Build fingerprints once for an immutable serving stock snapshot."""
289
+ return _PRELOADED_STOCKS.get(stock) or StockIndex(stock)
290
+
291
+
292
+ def molecule_lookup(query: str, cache: dict[str, dict[str, Any]] | None = None) -> dict[str, Any]:
293
+ """Resolve a SMILES locally; names/CAS require the pre-hydrated PubChem cache."""
294
+
295
+ normalized_query = str(query or "").strip()
296
+ cached = (cache or {}).get(normalized_query.casefold())
297
+ if cached:
298
+ try:
299
+ smiles = canonicalize_smiles(str(cached["canonical_smiles"]))
300
+ except Exception as exc:
301
+ return {"found": False, "query": query, "error": f"bad cache row: {exc}"}
302
+ return {
303
+ "found": True,
304
+ "query": query,
305
+ **cached,
306
+ "canonical_smiles": smiles,
307
+ "source": "frozen_pubchem_cache",
308
+ }
309
+ try:
310
+ smiles = canonicalize_smiles(normalized_query)
311
+ except Exception:
312
+ return {
313
+ "found": False,
314
+ "query": query,
315
+ "error": "name/CAS not in the local PubChem cache; prefetch it before rollouts",
316
+ }
317
+ molecule = Chem.MolFromSmiles(smiles)
318
+ return {
319
+ "found": True,
320
+ "query": query,
321
+ "canonical_smiles": smiles,
322
+ "inchikey": Chem.MolToInchiKey(molecule),
323
+ "formula": rdMolDescriptors.CalcMolFormula(molecule),
324
+ "molecular_weight": round(Descriptors.MolWt(molecule), 6),
325
+ "source": "local_rdkit_canonicalization",
326
+ }
327
+
328
+
329
+ def _normalize_class(value: str | None) -> str:
330
+ return "".join(character for character in (value or "").lower() if character.isalnum())
core/retroenv/serving.py ADDED
@@ -0,0 +1,387 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """A serving index for one release, built once so that a server starts in seconds.
2
+
3
+ The release (``LiteFold/RetroEnv``) stays the source of truth. The index holds what every
4
+ server process would otherwise derive from it at startup: the task rows (about 160 MB of
5
+ JSON), the stock's canonical SMILES and fingerprints, and the train-visible precedents with
6
+ their leakage keys and fingerprints. Deriving those took about 65 seconds and a gigabyte of
7
+ parsed molecules per process; reading them back takes a few seconds.
8
+
9
+ Fingerprints, canonical SMILES and scaffold keys depend on the RDKit version, so the index
10
+ records the version that built it. A server running another version rebuilds those parts
11
+ from the release instead of trusting them. Task rows do not depend on RDKit: they are the
12
+ release's own JSON lines, compressed and stored verbatim.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import hashlib
18
+ import json
19
+ import sqlite3
20
+ import threading
21
+ import zlib
22
+ from collections.abc import Sequence
23
+ from functools import lru_cache
24
+ from pathlib import Path
25
+ from typing import Any, Iterable, Iterator
26
+
27
+ import rdkit
28
+ from rdkit import DataStructs
29
+
30
+ from .leakage import LeakageRules
31
+ from .models import RetroTask
32
+ from .reactions import iter_reactions
33
+ from .retrieval import Precedent, PrecedentIndex, StockIndex, register_stock_index
34
+ from .store import load_stock
35
+
36
+ INDEX_VERSION = 1
37
+ INDEX_FILE = "serving.sqlite"
38
+ TASK_CACHE = 4096
39
+
40
+ _SCHEMA = """
41
+ CREATE TABLE meta (key TEXT PRIMARY KEY, value TEXT NOT NULL);
42
+ CREATE TABLE tasks (
43
+ split TEXT NOT NULL,
44
+ position INTEGER NOT NULL,
45
+ task_id TEXT NOT NULL,
46
+ parent_id TEXT NOT NULL,
47
+ stock_id TEXT NOT NULL,
48
+ variant TEXT NOT NULL,
49
+ tier TEXT,
50
+ min_depth INTEGER,
51
+ record BLOB NOT NULL,
52
+ PRIMARY KEY (split, position)
53
+ );
54
+ CREATE INDEX tasks_by_id ON tasks (task_id);
55
+ CREATE TABLE stock (
56
+ stock_id TEXT NOT NULL,
57
+ position INTEGER NOT NULL,
58
+ smiles TEXT NOT NULL,
59
+ fingerprint BLOB NOT NULL,
60
+ PRIMARY KEY (stock_id, position)
61
+ );
62
+ CREATE TABLE precedents (
63
+ position INTEGER PRIMARY KEY,
64
+ product TEXT NOT NULL,
65
+ reactants TEXT NOT NULL,
66
+ reaction_class TEXT NOT NULL,
67
+ reagents TEXT NOT NULL,
68
+ patents TEXT NOT NULL,
69
+ keys TEXT NOT NULL,
70
+ fingerprint BLOB NOT NULL
71
+ );
72
+ """
73
+
74
+
75
+ def sha256_file(path: str | Path) -> str:
76
+ digest = hashlib.sha256()
77
+ with Path(path).open("rb") as handle:
78
+ for block in iter(lambda: handle.read(1 << 20), b""):
79
+ digest.update(block)
80
+ return digest.hexdigest()
81
+
82
+
83
+ def build_index(release: str | Path, output: str | Path) -> dict[str, Any]:
84
+ """Write ``output/serving.sqlite`` from a release directory and describe what it holds.
85
+
86
+ Stock and precedents go through ``StockIndex`` and ``PrecedentIndex`` themselves, so the
87
+ stored values are exactly what a server computing them at startup would hold.
88
+ """
89
+ release, output = Path(release), Path(output)
90
+ output.mkdir(parents=True, exist_ok=True)
91
+ target = output / INDEX_FILE
92
+ partial = target.with_suffix(".partial")
93
+ partial.unlink(missing_ok=True)
94
+ manifest = json.loads((release / "manifest.json").read_text())
95
+ rules = LeakageRules.from_manifest(manifest)
96
+
97
+ db = sqlite3.connect(partial)
98
+ try:
99
+ db.executescript("PRAGMA journal_mode=OFF; PRAGMA synchronous=OFF;" + _SCHEMA)
100
+ splits = _write_tasks(db, release / "tasks-private")
101
+ stocks = _write_stocks(db, release / "stocks")
102
+ precedents = _write_precedents(db, release / "library" / "reactions.jsonl.gz", rules)
103
+ meta = {
104
+ "index_version": str(INDEX_VERSION),
105
+ "rdkit_version": rdkit.__version__,
106
+ "release_manifest_sha256": sha256_file(release / "manifest.json"),
107
+ "release_checksums_sha256": sha256_file(release / "checksums.json"),
108
+ }
109
+ db.executemany("INSERT INTO meta VALUES (?, ?)", sorted(meta.items()))
110
+ db.commit()
111
+ db.execute("VACUUM")
112
+ finally:
113
+ db.close()
114
+ partial.replace(target)
115
+ described = describe_index(target)
116
+ if (described["splits"], described["stocks"], described["precedents"]) != (splits, stocks, precedents):
117
+ raise RuntimeError(f"{target} does not read back what was written")
118
+ return described
119
+
120
+
121
+ def describe_index(path: str | Path) -> dict[str, Any]:
122
+ """Size, digest, versions and contents of an existing serving index."""
123
+ path = Path(path)
124
+ index = ServingIndex(path)
125
+ db = index._db()
126
+ splits: dict[str, dict[str, Any]] = {}
127
+ for split, tier, count in db.execute("SELECT split, tier, COUNT(*) FROM tasks GROUP BY split, tier"):
128
+ entry = splits.setdefault(split, {"tasks": 0, "tiers": {}})
129
+ entry["tasks"] += count
130
+ entry["tiers"][str(tier)] = count
131
+ for entry in splits.values():
132
+ entry["tiers"] = dict(sorted(entry["tiers"].items()))
133
+ return {
134
+ "path": INDEX_FILE,
135
+ "size": path.stat().st_size,
136
+ "sha256": sha256_file(path),
137
+ "index_version": int(index.meta["index_version"]),
138
+ "rdkit_version": index.meta["rdkit_version"],
139
+ "release_checksums_sha256": index.meta["release_checksums_sha256"],
140
+ "splits": dict(sorted(splits.items())),
141
+ "stocks": dict(db.execute("SELECT stock_id, COUNT(*) FROM stock GROUP BY stock_id ORDER BY stock_id")),
142
+ "precedents": db.execute("SELECT COUNT(*) FROM precedents").fetchone()[0],
143
+ }
144
+
145
+
146
+ def _write_tasks(db: sqlite3.Connection, tasks_dir: Path) -> dict[str, dict[str, Any]]:
147
+ splits: dict[str, dict[str, Any]] = {}
148
+ for path in sorted(tasks_dir.glob("*.jsonl")):
149
+ split, seen, tiers, rows = path.stem, set(), {}, []
150
+ with path.open("r", encoding="utf-8") as handle:
151
+ for line_number, line in enumerate(handle, 1):
152
+ if not line.strip():
153
+ continue
154
+ task = RetroTask.from_dict(json.loads(line)) # the same validation TaskStore applies
155
+ if task.split != split:
156
+ raise ValueError(f"{path}:{line_number}: task split {task.split!r} != {split!r}")
157
+ if task.task_id in seen:
158
+ raise ValueError(f"duplicate task_id in {path}: {task.task_id}")
159
+ seen.add(task.task_id)
160
+ tier = task.difficulty.get("tier")
161
+ tiers[tier] = tiers.get(tier, 0) + 1
162
+ rows.append(
163
+ (
164
+ split,
165
+ len(rows),
166
+ task.task_id,
167
+ task.parent_id,
168
+ task.stock_id,
169
+ task.variant,
170
+ tier,
171
+ task.difficulty.get("min_depth"),
172
+ zlib.compress(line.strip().encode("utf-8"), 6),
173
+ )
174
+ )
175
+ db.executemany("INSERT INTO tasks VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)", rows)
176
+ splits[split] = {"tasks": len(rows), "tiers": dict(sorted((str(k), v) for k, v in tiers.items()))}
177
+ if not splits:
178
+ raise ValueError(f"no task splits in {tasks_dir}")
179
+ return splits
180
+
181
+
182
+ def _write_stocks(db: sqlite3.Connection, stocks_dir: Path) -> dict[str, int]:
183
+ stocks: dict[str, int] = {}
184
+ for path in sorted(stocks_dir.glob("*.smi")):
185
+ index = StockIndex(load_stock(path))
186
+ db.executemany(
187
+ "INSERT INTO stock VALUES (?, ?, ?, ?)",
188
+ (
189
+ (path.stem, position, smiles, fingerprint.ToBinary())
190
+ for position, (smiles, fingerprint) in enumerate(zip(index.smiles, index.fingerprints()))
191
+ ),
192
+ )
193
+ stocks[path.stem] = len(index.smiles)
194
+ if not stocks:
195
+ raise ValueError(f"no stocks in {stocks_dir}")
196
+ return stocks
197
+
198
+
199
+ def _write_precedents(db: sqlite3.Connection, reactions: Path, rules: LeakageRules) -> int:
200
+ index = PrecedentIndex(iter_reactions(reactions), rules)
201
+ db.executemany(
202
+ "INSERT INTO precedents VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
203
+ (
204
+ (
205
+ position,
206
+ record.product,
207
+ json.dumps(list(record.reactants)),
208
+ record.reaction_class,
209
+ json.dumps(list(record.reagents)),
210
+ json.dumps(list(record.patents)),
211
+ json.dumps(sorted([list(key) for key in record.keys])),
212
+ fingerprint.ToBinary(),
213
+ )
214
+ for position, (record, fingerprint) in enumerate(zip(index.records, index.fingerprints()))
215
+ ),
216
+ )
217
+ return len(index.records)
218
+
219
+
220
+ class ServingIndex:
221
+ """Read-only access to ``serving.sqlite``; one connection per thread."""
222
+
223
+ def __init__(self, path: str | Path):
224
+ self.path = Path(path)
225
+ if not self.path.exists():
226
+ raise FileNotFoundError(f"serving index not found: {self.path}")
227
+ self._local = threading.local()
228
+ self.meta = dict(self._db().execute("SELECT key, value FROM meta"))
229
+ if int(self.meta.get("index_version", 0)) != INDEX_VERSION:
230
+ raise ValueError(f"{self.path} is index version {self.meta.get('index_version')}, expected {INDEX_VERSION}")
231
+
232
+ def _db(self) -> sqlite3.Connection:
233
+ db = getattr(self._local, "db", None)
234
+ if db is None:
235
+ # immutable=1: the file never changes under a running server, so SQLite skips locking.
236
+ db = sqlite3.connect(f"file:{self.path}?mode=ro&immutable=1", uri=True)
237
+ self._local.db = db
238
+ return db
239
+
240
+ @property
241
+ def rdkit_matches(self) -> bool:
242
+ """Whether this process can trust the stored fingerprints, canonical SMILES and keys."""
243
+ return self.meta.get("rdkit_version") == rdkit.__version__
244
+
245
+ def stock_smiles(self, stock_id: str) -> list[str]:
246
+ rows = self._db().execute("SELECT smiles FROM stock WHERE stock_id = ? ORDER BY position", (stock_id,))
247
+ return [smiles for (smiles,) in rows]
248
+
249
+ def stock_index(self, stock_id: str) -> StockIndex:
250
+ """The stock's index: stored fingerprints when RDKit matches, otherwise recomputed."""
251
+ if not self.rdkit_matches:
252
+ return StockIndex(self.stock_smiles(stock_id))
253
+ rows = (
254
+ self._db()
255
+ .execute("SELECT smiles, fingerprint FROM stock WHERE stock_id = ? ORDER BY position", (stock_id,))
256
+ .fetchall()
257
+ )
258
+ if not rows:
259
+ raise FileNotFoundError(f"stock {stock_id!r} is not in {self.path}")
260
+ return StockIndex.from_canonical(
261
+ (smiles for smiles, _ in rows), (DataStructs.ExplicitBitVect(blob) for _, blob in rows)
262
+ )
263
+
264
+ def precedents(self, rules: LeakageRules, reactions: Path | None = None) -> PrecedentIndex:
265
+ """Stored precedents, or a rebuild from the release's reactions when RDKit differs."""
266
+ if not self.rdkit_matches:
267
+ if reactions is None:
268
+ raise ValueError("RDKit differs from the index; pass the release's reactions to rebuild precedents")
269
+ return PrecedentIndex(iter_reactions(reactions), rules)
270
+ records, fingerprints = [], []
271
+ for product, reactants, reaction_class, reagents, patents, keys, blob in self._db().execute(
272
+ "SELECT product, reactants, reaction_class, reagents, patents, keys, fingerprint "
273
+ "FROM precedents ORDER BY position"
274
+ ):
275
+ records.append(
276
+ Precedent(
277
+ product=product,
278
+ reactants=tuple(json.loads(reactants)),
279
+ reaction_class=reaction_class,
280
+ reagents=tuple(json.loads(reagents)),
281
+ patents=tuple(json.loads(patents)),
282
+ keys=frozenset((kind, value) for kind, value in json.loads(keys)),
283
+ )
284
+ )
285
+ fingerprints.append(DataStructs.ExplicitBitVect(blob))
286
+ return PrecedentIndex.from_records(records, fingerprints, rules)
287
+
288
+ def task_store(self) -> "SqliteTaskStore":
289
+ return SqliteTaskStore(self)
290
+
291
+
292
+ class TaskList(Sequence):
293
+ """One split's tasks, read from the index on demand; behaves like the tuple ``TaskStore`` returns."""
294
+
295
+ def __init__(self, store: "SqliteTaskStore", split: str, count: int):
296
+ self._store, self._split, self._count = store, split, count
297
+
298
+ def __len__(self) -> int:
299
+ return self._count
300
+
301
+ def __getitem__(self, index): # type: ignore[override]
302
+ if isinstance(index, slice):
303
+ return [self[i] for i in range(*index.indices(self._count))]
304
+ index = int(index)
305
+ if index < 0:
306
+ index += self._count
307
+ if not 0 <= index < self._count:
308
+ raise IndexError(f"task index {index} is out of range for split {self._split!r}")
309
+ return self._store._task(self._split, index)
310
+
311
+ def __iter__(self) -> Iterator[RetroTask]:
312
+ rows = self._store.index._db().execute(
313
+ "SELECT record FROM tasks WHERE split = ? ORDER BY position", (self._split,)
314
+ )
315
+ for (record,) in rows:
316
+ yield _decode(record)
317
+
318
+
319
+ def _decode(record: bytes) -> RetroTask:
320
+ return RetroTask.from_dict(json.loads(zlib.decompress(record)))
321
+
322
+
323
+ class SqliteTaskStore:
324
+ """``TaskStore``'s interface over a serving index, without loading every task up front."""
325
+
326
+ def __init__(self, index: ServingIndex):
327
+ self.index = index
328
+ db = index._db()
329
+ self._counts = dict(db.execute("SELECT split, COUNT(*) FROM tasks GROUP BY split ORDER BY split"))
330
+ self._stock_ids = [stock_id for (stock_id,) in db.execute("SELECT DISTINCT stock_id FROM stock")]
331
+ self._stocks: dict[str, frozenset[str]] = {}
332
+ self._stock_lock = threading.Lock()
333
+ self._task = lru_cache(maxsize=TASK_CACHE)(self._load_task)
334
+
335
+ def splits(self) -> list[str]:
336
+ return sorted(self._counts)
337
+
338
+ def tasks(self, split: str) -> TaskList:
339
+ if split not in self._counts:
340
+ raise KeyError(f"unknown split {split!r}; available: {self.splits()}")
341
+ return TaskList(self, split, self._counts[split])
342
+
343
+ def task(self, split: str, index: int) -> RetroTask:
344
+ return self.tasks(split)[index]
345
+
346
+ def _load_task(self, split: str, position: int) -> RetroTask:
347
+ row = (
348
+ self.index._db()
349
+ .execute("SELECT record FROM tasks WHERE split = ? AND position = ?", (split, position))
350
+ .fetchone()
351
+ )
352
+ if row is None:
353
+ raise IndexError(f"task index {position} is out of range for split {split!r}")
354
+ return _decode(row[0])
355
+
356
+ def position(self, split: str, task_id: str) -> int | None:
357
+ row = (
358
+ self.index._db()
359
+ .execute("SELECT position FROM tasks WHERE split = ? AND task_id = ?", (split, task_id))
360
+ .fetchone()
361
+ )
362
+ return None if row is None else int(row[0])
363
+
364
+ def find(self, task_id: str) -> RetroTask | None:
365
+ row = (
366
+ self.index._db()
367
+ .execute("SELECT split, position FROM tasks WHERE task_id = ? ORDER BY split LIMIT 1", (task_id,))
368
+ .fetchone()
369
+ )
370
+ return None if row is None else self._task(row[0], int(row[1]))
371
+
372
+ def stock_ids(self) -> list[str]:
373
+ return sorted(self._stock_ids)
374
+
375
+ def stock(self, stock_id: str) -> frozenset[str]:
376
+ """The stock as one shared set, its index registered so sessions never rebuild it."""
377
+ with self._stock_lock:
378
+ if stock_id not in self._stocks:
379
+ self._stocks[stock_id] = register_stock_index(self.index.stock_index(stock_id))
380
+ return self._stocks[stock_id]
381
+
382
+ def public_task(self, split: str, index: int) -> dict:
383
+ return self.task(split, index).to_dict(include_hidden=False)
384
+
385
+ def iter_all(self) -> Iterable[RetroTask]:
386
+ for split in self.splits():
387
+ yield from self.tasks(split)
core/retroenv/store.py ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Task and building-block storage with canonicalized, hidden references."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from pathlib import Path
7
+ from typing import Iterable
8
+
9
+ from .chemistry import canonicalize_smiles
10
+ from .models import RetroTask
11
+
12
+
13
+ def load_stock(path: Path) -> frozenset[str]:
14
+ values: set[str] = set()
15
+ with path.open("r", encoding="utf-8") as handle:
16
+ for line_number, line in enumerate(handle, 1):
17
+ text = line.strip()
18
+ if not text or text.startswith("#"):
19
+ continue
20
+ # Conventional .smi files put an optional identifier after whitespace.
21
+ smiles = text.split(maxsplit=1)[0]
22
+ try:
23
+ values.add(canonicalize_smiles(smiles))
24
+ except Exception as exc:
25
+ raise ValueError(f"{path}:{line_number}: invalid stock SMILES: {exc}") from exc
26
+ if not values:
27
+ raise ValueError(f"stock file contains no molecules: {path}")
28
+ return frozenset(values)
29
+
30
+
31
+ class TaskStore:
32
+ """Load split JSONL files and stocks without exposing private references."""
33
+
34
+ def __init__(self, tasks_dir: str | Path, stocks_dir: str | Path):
35
+ self.tasks_dir = Path(tasks_dir)
36
+ self.stocks_dir = Path(stocks_dir)
37
+ self._tasks: dict[str, tuple[RetroTask, ...]] = {}
38
+ self._stocks: dict[str, frozenset[str]] = {}
39
+
40
+ def splits(self) -> list[str]:
41
+ return sorted(path.stem for path in self.tasks_dir.glob("*.jsonl"))
42
+
43
+ def tasks(self, split: str) -> tuple[RetroTask, ...]:
44
+ if split not in self._tasks:
45
+ path = self.tasks_dir / f"{split}.jsonl"
46
+ if not path.exists():
47
+ raise KeyError(f"unknown split {split!r}; available: {self.splits()}")
48
+ loaded: list[RetroTask] = []
49
+ seen: set[str] = set()
50
+ with path.open("r", encoding="utf-8") as handle:
51
+ for line_number, line in enumerate(handle, 1):
52
+ if not line.strip():
53
+ continue
54
+ try:
55
+ task = RetroTask.from_dict(json.loads(line))
56
+ except Exception as exc:
57
+ raise ValueError(f"{path}:{line_number}: {exc}") from exc
58
+ if task.split != split:
59
+ raise ValueError(f"{path}:{line_number}: task split {task.split!r} != {split!r}")
60
+ if task.task_id in seen:
61
+ raise ValueError(f"duplicate task_id in {path}: {task.task_id}")
62
+ seen.add(task.task_id)
63
+ loaded.append(task)
64
+ self._tasks[split] = tuple(loaded)
65
+ return self._tasks[split]
66
+
67
+ def task(self, split: str, index: int) -> RetroTask:
68
+ return self.tasks(split)[index]
69
+
70
+ def stock(self, stock_id: str) -> frozenset[str]:
71
+ if stock_id not in self._stocks:
72
+ path = self.stocks_dir / f"{stock_id}.smi"
73
+ if not path.exists():
74
+ raise FileNotFoundError(f"stock {stock_id!r} not found at {path}")
75
+ self._stocks[stock_id] = load_stock(path)
76
+ return self._stocks[stock_id]
77
+
78
+ def public_task(self, split: str, index: int) -> dict:
79
+ return self.task(split, index).to_dict(include_hidden=False)
80
+
81
+ def iter_all(self) -> Iterable[RetroTask]:
82
+ for split in self.splits():
83
+ yield from self.tasks(split)
84
+
85
+ def position(self, split: str, task_id: str) -> int | None:
86
+ for index, task in enumerate(self.tasks(split)):
87
+ if task.task_id == task_id:
88
+ return index
89
+ return None
90
+
91
+ def find(self, task_id: str) -> RetroTask | None:
92
+ for task in self.iter_all():
93
+ if task.task_id == task_id:
94
+ return task
95
+ return None
96
+
97
+ def stock_ids(self) -> list[str]:
98
+ return sorted(path.stem for path in self.stocks_dir.glob("*.smi"))
core/retroenv/tools.py ADDED
@@ -0,0 +1,219 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tool names, descriptions and JSON schemas shared by every RetroEnv front-end.
2
+
3
+ The OpenEnv server advertises these schemas over MCP, the v1 runner sends them
4
+ to OpenAI-compatible endpoints, and a Harbor CLI can document them, so one
5
+ definition keeps the action surface identical everywhere. Validation stays in
6
+ ``RetroRouteSession`` and the verifier: a malformed submission is scored, not
7
+ rejected at the schema boundary, because parse and graph validity are part of
8
+ the dense reward.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import copy
14
+ from typing import Any
15
+
16
+
17
+ def _function(
18
+ name: str,
19
+ description: str,
20
+ properties: dict,
21
+ required: list[str] | None = None,
22
+ defs: dict[str, Any] | None = None,
23
+ ) -> dict:
24
+ parameters: dict[str, Any] = {
25
+ "type": "object",
26
+ "properties": properties,
27
+ "required": required or [],
28
+ "additionalProperties": False,
29
+ }
30
+ if defs:
31
+ parameters["$defs"] = defs
32
+ return {
33
+ "type": "function",
34
+ "function": {
35
+ "name": name,
36
+ "description": description,
37
+ "parameters": parameters,
38
+ },
39
+ }
40
+
41
+
42
+ SMILES = {"type": "string", "description": "A SMILES string."}
43
+ REACTANTS = {"type": "array", "items": SMILES, "minItems": 1}
44
+ ROUTE_GRAPH_DEFS: dict[str, Any] = {
45
+ "metadata": {
46
+ "type": "object",
47
+ "description": "Evidence and confidence for this disconnection.",
48
+ "properties": {
49
+ "source": {"type": "string"},
50
+ "explanation": {"type": "string"},
51
+ "reaction_class": {"type": "string"},
52
+ "classification": {"type": "string"},
53
+ "confidence": {"type": "number", "minimum": 0, "maximum": 1},
54
+ "policy_probability": {"type": "number", "minimum": 0, "maximum": 1},
55
+ "literature": {"type": "array", "items": {"type": "object"}},
56
+ "conditions": {"type": "array", "items": {"type": "object"}},
57
+ "precursor_roles": {
58
+ "type": "object",
59
+ "additionalProperties": {"type": "string"},
60
+ },
61
+ },
62
+ "required": [
63
+ "explanation",
64
+ "reaction_class",
65
+ "confidence",
66
+ "literature",
67
+ "precursor_roles",
68
+ ],
69
+ "additionalProperties": True,
70
+ },
71
+ "reaction": {
72
+ "type": "object",
73
+ "description": "A reaction whose children are its precursor molecules.",
74
+ "properties": {
75
+ "type": {"const": "reaction"},
76
+ "is_reaction": {"const": True},
77
+ "metadata": {"$ref": "#/$defs/metadata"},
78
+ "children": {
79
+ "type": "array",
80
+ "minItems": 1,
81
+ "items": {"$ref": "#/$defs/mol"},
82
+ },
83
+ },
84
+ "required": ["type", "is_reaction", "metadata", "children"],
85
+ "additionalProperties": False,
86
+ },
87
+ "mol": {
88
+ "type": "object",
89
+ "description": "A molecule node. Expanded nodes have one reaction child and in_stock=false; leaves have no children.",
90
+ "properties": {
91
+ "type": {"const": "mol"},
92
+ "smiles": {"type": "string", "minLength": 1},
93
+ "in_stock": {"type": "boolean"},
94
+ "children": {
95
+ "type": "array",
96
+ "maxItems": 1,
97
+ "items": {"$ref": "#/$defs/reaction"},
98
+ },
99
+ },
100
+ "required": ["type", "smiles", "in_stock", "children"],
101
+ "additionalProperties": False,
102
+ },
103
+ }
104
+
105
+ TOOLS = [
106
+ _function("inspect_molecule", "Inspect a molecule with RDKit.", {"smiles": SMILES}, ["smiles"]),
107
+ _function(
108
+ "pubchem_lookup",
109
+ "Canonicalize a SMILES or query the frozen molecule cache.",
110
+ {"query": {"type": "string"}},
111
+ ["query"],
112
+ ),
113
+ _function(
114
+ "stock_retrieve",
115
+ "The only stock access. Search exact SMILES/InChIKey, class, SMARTS, or similarity; at most 20 results.",
116
+ {
117
+ "query": {"type": "string"},
118
+ "mode": {
119
+ "type": "string",
120
+ "enum": ["auto", "exact", "inchikey", "class", "substructure", "similarity"],
121
+ "default": "auto",
122
+ },
123
+ "limit": {"type": "integer", "minimum": 1, "maximum": 20, "default": 10},
124
+ },
125
+ ["query"],
126
+ ),
127
+ _function(
128
+ "reaction_precedent_search",
129
+ "Find similar reactions in the train-visible corpus, ranked by product similarity.",
130
+ {
131
+ "product_smiles": SMILES,
132
+ "reaction_class": {"type": "string"},
133
+ "limit": {"type": "integer", "minimum": 1, "maximum": 20, "default": 10},
134
+ },
135
+ ),
136
+ _function(
137
+ "validate_disconnection",
138
+ "Check whether train-visible reactions or frequent templates support a proposed product-to-reactants cut.",
139
+ {"product_smiles": SMILES, "reactants": REACTANTS},
140
+ ["product_smiles", "reactants"],
141
+ ),
142
+ _function(
143
+ "reaction_class_lookup",
144
+ "Name the reaction class of any proposed cut with the verifier's own labeller.",
145
+ {"product_smiles": SMILES, "reactants": REACTANTS},
146
+ ["product_smiles", "reactants"],
147
+ ),
148
+ _function(
149
+ "reaction_conditions_search",
150
+ "Reagent sets reported for train-visible analogues of a cut or product.",
151
+ {
152
+ "product_smiles": SMILES,
153
+ "reactants": REACTANTS,
154
+ "reaction_class": {"type": "string"},
155
+ "limit": {"type": "integer", "minimum": 1, "maximum": 20, "default": 5},
156
+ },
157
+ ),
158
+ _function(
159
+ "search_literature",
160
+ "Patent identifiers attached to train-visible analogue reactions.",
161
+ {
162
+ "product_smiles": SMILES,
163
+ "reaction_class": {"type": "string"},
164
+ "limit": {"type": "integer", "minimum": 1, "maximum": 20, "default": 5},
165
+ },
166
+ ),
167
+ _function(
168
+ "emit_routes",
169
+ "Terminal call. Emit the required renderable molecule/reaction trees.",
170
+ {
171
+ "submission": {
172
+ "type": "object",
173
+ "properties": {
174
+ "schema_version": {"type": "string"},
175
+ "routes": {
176
+ "type": "array",
177
+ "description": "Root molecule nodes directly; do not wrap them in route/root/tree objects.",
178
+ "items": {"$ref": "#/$defs/mol"},
179
+ "minItems": 1,
180
+ "maxItems": 5,
181
+ },
182
+ },
183
+ "required": ["routes"],
184
+ }
185
+ },
186
+ ["submission"],
187
+ defs=ROUTE_GRAPH_DEFS,
188
+ ),
189
+ ]
190
+ EMIT_TOOL = next(tool for tool in TOOLS if tool["function"]["name"] == "emit_routes")
191
+
192
+ ALL_TOOL_NAMES = tuple(tool["function"]["name"] for tool in TOOLS)
193
+ # No tool reads a task's hidden routes. "unaided" is an ablation without the step checker.
194
+ ASSIST_TOOLS = ("validate_disconnection",)
195
+ TOOLSETS: dict[str, tuple[str, ...]] = {
196
+ "full": ALL_TOOL_NAMES,
197
+ "unaided": tuple(name for name in ALL_TOOL_NAMES if name not in ASSIST_TOOLS),
198
+ }
199
+
200
+
201
+ def tool_names(toolset: str = "full") -> tuple[str, ...]:
202
+ try:
203
+ return TOOLSETS[toolset]
204
+ except KeyError:
205
+ raise ValueError(f"unknown toolset {toolset!r}; choose one of {sorted(TOOLSETS)}") from None
206
+
207
+
208
+ def openai_tools(toolset: str = "full") -> list[dict[str, Any]]:
209
+ """OpenAI function-calling definitions for the tools in ``toolset``."""
210
+ names = set(tool_names(toolset))
211
+ return [copy.deepcopy(tool) for tool in TOOLS if tool["function"]["name"] in names]
212
+
213
+
214
+ def tool_spec(name: str) -> dict[str, Any]:
215
+ """The ``{"name", "description", "parameters"}`` block of one tool."""
216
+ for tool in TOOLS:
217
+ if tool["function"]["name"] == name:
218
+ return copy.deepcopy(tool["function"])
219
+ raise KeyError(f"unknown tool {name!r}")
core/retroenv/training.py ADDED
@@ -0,0 +1,146 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """TRL ``environment_factory`` adapter over the same RetroRoute core."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import os
7
+ import threading
8
+ from pathlib import Path
9
+ from typing import Any
10
+
11
+ from .benchmark import load_benchmark
12
+
13
+ _TRACE_LOCK = threading.Lock()
14
+
15
+
16
+ class RetroRouteTrainingEnv:
17
+ """Text-only multi-tool environment compatible with TRL GRPOTrainer.
18
+
19
+ Public methods other than ``reset`` and ``get_reward`` are agent tools.
20
+ The adapter owns no chemistry logic; it delegates to ``RetroRouteSession``,
21
+ the same core used by the OpenEnv/MCP server.
22
+ """
23
+
24
+ def __init__(
25
+ self,
26
+ benchmark_dir: str | Path | None = None,
27
+ *,
28
+ max_tool_calls: int | None = None,
29
+ trace_path: str | Path | None = None,
30
+ ):
31
+ root = benchmark_dir or os.getenv("RETROENV_BENCHMARK_DIR")
32
+ if not root:
33
+ raise ValueError("pass benchmark_dir or set RETROENV_BENCHMARK_DIR to a built release directory")
34
+ benchmark = load_benchmark(str(Path(root).resolve()))
35
+ self.store = benchmark.store
36
+ self.session = benchmark.session(
37
+ max_tool_calls=max_tool_calls or int(os.getenv("RETROENV_MAX_TOOL_CALLS", "32")),
38
+ )
39
+ self.trace_path = (
40
+ Path(trace_path or os.getenv("RETROENV_TRACE_PATH", ""))
41
+ if (trace_path or os.getenv("RETROENV_TRACE_PATH"))
42
+ else None
43
+ )
44
+ self._task: dict[str, Any] = {}
45
+ self._trace: list[dict[str, Any]] = []
46
+
47
+ def reset(self, split: str = "train", index: int = 0, **_: Any) -> list[dict[str, str]]:
48
+ """Start one deterministic indexed task and return its private-free prompt."""
49
+ task = self.store.task(split, int(index))
50
+ opening = self.session.reset(task, self.store.stock(task.stock_id))
51
+ self._task = {"split": split, "index": int(index), "task_id": task.task_id}
52
+ self._trace = []
53
+ return self._blocks(opening)
54
+
55
+ def get_reward(self) -> float:
56
+ """Return environment-owned terminal reward and optionally persist a trace."""
57
+ reward = float((self.session.final_score or {}).get("reward", 0.0))
58
+ if self.trace_path and self._task:
59
+ row = {
60
+ "task": self._task,
61
+ "reward": reward,
62
+ "score": self.session.final_score,
63
+ "turns": self._trace,
64
+ }
65
+ self.trace_path.parent.mkdir(parents=True, exist_ok=True)
66
+ with _TRACE_LOCK, self.trace_path.open("a", encoding="utf-8") as handle:
67
+ handle.write(json.dumps(row, sort_keys=True) + "\n")
68
+ return reward
69
+
70
+ def inspect_molecule(self, smiles: str) -> list[dict[str, str]]:
71
+ """Inspect formula, scaffold, rings, charge, and stereochemistry."""
72
+ return self._call("inspect_molecule", smiles=smiles)
73
+
74
+ def pubchem_lookup(self, query: str) -> list[dict[str, str]]:
75
+ """Canonicalize SMILES using the deterministic local molecule resolver."""
76
+ return self._call("pubchem_lookup", query=query)
77
+
78
+ def stock_retrieve(self, query: str, mode: str = "auto", limit: int = 10) -> list[dict[str, str]]:
79
+ """Search the selected stock, returning at most 20 candidates."""
80
+ return self._call("stock_retrieve", query=query, mode=mode, limit=limit)
81
+
82
+ def reaction_precedent_search(
83
+ self, product_smiles: str = "", reaction_class: str = "", limit: int = 10
84
+ ) -> list[dict[str, str]]:
85
+ """Search capped training-visible reaction precedents."""
86
+ return self._call(
87
+ "reaction_precedent_search",
88
+ product_smiles=product_smiles,
89
+ reaction_class=reaction_class,
90
+ limit=limit,
91
+ )
92
+
93
+ def validate_disconnection(self, product_smiles: str, reactants: list[str]) -> list[dict[str, str]]:
94
+ """Check one proposed cut against train-visible reactions and frequent templates."""
95
+ return self._call("validate_disconnection", product_smiles=product_smiles, reactants=reactants)
96
+
97
+ def reaction_class_lookup(self, product_smiles: str, reactants: list[str]) -> list[dict[str, str]]:
98
+ """Name the reaction class of a proposed cut with the verifier's labeller."""
99
+ return self._call(
100
+ "reaction_class_lookup",
101
+ product_smiles=product_smiles,
102
+ reactants=reactants,
103
+ )
104
+
105
+ def reaction_conditions_search(
106
+ self,
107
+ product_smiles: str = "",
108
+ reactants: list[str] | None = None,
109
+ reaction_class: str = "",
110
+ limit: int = 5,
111
+ ) -> list[dict[str, str]]:
112
+ """Return reagent sets reported for train-visible analogues."""
113
+ return self._call(
114
+ "reaction_conditions_search",
115
+ product_smiles=product_smiles,
116
+ reactants=reactants or [],
117
+ reaction_class=reaction_class,
118
+ limit=limit,
119
+ )
120
+
121
+ def search_literature(
122
+ self, product_smiles: str = "", reaction_class: str = "", limit: int = 5
123
+ ) -> list[dict[str, str]]:
124
+ """Search frozen patent/citation metadata, never live web."""
125
+ return self._call(
126
+ "search_literature",
127
+ product_smiles=product_smiles,
128
+ reaction_class=reaction_class,
129
+ limit=limit,
130
+ )
131
+
132
+ def emit_routes(self, submission: dict[str, Any]) -> list[dict[str, str]]:
133
+ """Emit the final renderable route trees and terminate scoring."""
134
+ return self._call("emit_routes", submission=submission)
135
+
136
+ def _call(self, name: str, **arguments: Any) -> list[dict[str, str]]:
137
+ if self.session.done:
138
+ result = {"done": True, "error": "episode is already complete"}
139
+ else:
140
+ result = getattr(self.session, name)(**arguments)
141
+ self._trace.append({"tool": name, "arguments": arguments, "result": result})
142
+ return self._blocks(result)
143
+
144
+ @staticmethod
145
+ def _blocks(value: dict[str, Any]) -> list[dict[str, str]]:
146
+ return [{"type": "text", "text": json.dumps(value, sort_keys=True)}]
core/retroenv/verifier.py ADDED
@@ -0,0 +1,405 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Chemistry-first scoring of a submitted route set.
2
+
3
+ A route is valid when it starts at the target, is a well-formed tree within the
4
+ depth budget, every step is supported by the frozen reaction library (corpus
5
+ reaction or frequent retro-template; never the task's hidden route), every
6
+ leaf is in the task's effective stock, no leaf falsely claims stock, and the
7
+ task constraints hold. Known routes are evidence for a bonus, not the
8
+ definition of correctness.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ from dataclasses import dataclass, field
14
+ from functools import lru_cache
15
+ from typing import Any, Iterable
16
+
17
+ from .chemistry import ChemistryError, canonicalize_smiles
18
+ from .classes import classify_step
19
+ from .graph import ParsedTree, parse_submission, routes_to_submission
20
+ from .models import ReferenceRoute, RetroTask, ScoreResult
21
+ from .reactions import ReactionLibrary, StepKey, free_key
22
+
23
+ WEIGHTS = {
24
+ "parse": 0.02,
25
+ "structure": 0.08,
26
+ "steps": 0.35,
27
+ "stock": 0.15,
28
+ "constraints": 0.10,
29
+ "efficiency": 0.10,
30
+ "diversity": 0.05,
31
+ "reference_similarity": 0.10,
32
+ "reference_match": 0.05,
33
+ }
34
+ # A false in-stock claim or a submission that never addresses the target cannot score highly.
35
+ FALSE_STOCK_CAP = 0.40
36
+ OFF_TARGET_CAP = 0.10
37
+
38
+
39
+ @dataclass
40
+ class RouteEvaluation:
41
+ index: int
42
+ root_ok: bool
43
+ signature: frozenset[StepKey] = frozenset()
44
+ first_cut: tuple[str, ...] = ()
45
+ depth: int = 0
46
+ duplicate: bool = False
47
+ step_results: list[dict[str, Any]] = field(default_factory=list)
48
+ leaves_in_stock: int = 0
49
+ leaves_claimed_correctly: int = 0
50
+ leaf_count: int = 0
51
+ false_claims: list[str] = field(default_factory=list)
52
+ missing_stock: list[str] = field(default_factory=list)
53
+ violations: list[str] = field(default_factory=list)
54
+ errors: list[str] = field(default_factory=list)
55
+ warnings: list[str] = field(default_factory=list)
56
+ molecule_validity: float = 0.0
57
+
58
+ @property
59
+ def supported_fraction(self) -> float:
60
+ if not self.step_results:
61
+ return 0.0
62
+ return sum(result["supported"] for result in self.step_results) / len(self.step_results)
63
+
64
+ @property
65
+ def valid(self) -> bool:
66
+ return (
67
+ self.root_ok
68
+ and not self.duplicate
69
+ and not self.errors
70
+ and bool(self.step_results)
71
+ and self.supported_fraction == 1.0
72
+ and self.leaf_count > 0
73
+ and self.leaves_in_stock == self.leaf_count
74
+ and not self.false_claims
75
+ and not self.violations
76
+ )
77
+
78
+ def to_dict(self) -> dict[str, Any]:
79
+ return {
80
+ "index": self.index,
81
+ "valid": self.valid,
82
+ "root_matches_target": self.root_ok,
83
+ "duplicate_of_earlier_route": self.duplicate,
84
+ "depth": self.depth,
85
+ "steps": len(self.step_results),
86
+ "supported_steps": sum(result["supported"] for result in self.step_results),
87
+ "leaves": self.leaf_count,
88
+ "leaves_in_stock": self.leaves_in_stock,
89
+ "false_stock_claims": self.false_claims,
90
+ "missing_stock": self.missing_stock,
91
+ "constraint_violations": self.violations,
92
+ "first_cut": list(self.first_cut),
93
+ "errors": self.errors,
94
+ "warnings": self.warnings[:10],
95
+ }
96
+
97
+
98
+ class RouteVerifier:
99
+ """Score submissions with a reaction library; hidden routes only inform the bonus."""
100
+
101
+ def __init__(self, library: ReactionLibrary):
102
+ self.library = library
103
+
104
+ def score_submission(self, task: RetroTask, submission: Any, stock: Iterable[str]) -> ScoreResult:
105
+ parsed = parse_submission(submission)
106
+ if not parsed.parse_valid:
107
+ return _rejected(parsed.errors)
108
+ stock_set = _canonical_stock(stock)
109
+ excluded = _canonical_stock(task.constraints.excluded_stock)
110
+ effective_stock = stock_set - excluded
111
+ target = canonicalize_smiles(task.target_smiles)
112
+ forbidden = frozenset(task.constraints.forbidden_classes)
113
+
114
+ routes: list[RouteEvaluation] = []
115
+ seen: set[frozenset[StepKey]] = set()
116
+ for index, tree in enumerate(parsed.trees):
117
+ route = self._evaluate_tree(index, tree, target, task, effective_stock, excluded, forbidden)
118
+ if route.signature and route.signature in seen:
119
+ route.duplicate = True
120
+ seen.add(route.signature)
121
+ routes.append(route)
122
+
123
+ references = compliant_references(task, effective_stock, forbidden)
124
+ min_depth = min((route_depth(task.target_smiles, ref.steps) for ref in references), default=None)
125
+ if min_depth is None:
126
+ min_depth = int(task.difficulty.get("min_depth") or task.max_depth)
127
+ reference_signatures = [(ref, signature(ref.steps)) for ref in references]
128
+
129
+ slots = max(len(routes), task.min_routes)
130
+ structure = steps = stock_score = constraints = efficiency = 0.0
131
+ for route in routes:
132
+ if route.duplicate:
133
+ continue
134
+ route_structure = [
135
+ route.root_ok,
136
+ not route.errors,
137
+ bool(route.step_results),
138
+ route.molecule_validity == 1.0,
139
+ not route.warnings,
140
+ ]
141
+ structure += sum(route_structure) / len(route_structure)
142
+ if not route.root_ok:
143
+ continue
144
+ steps += route.supported_fraction
145
+ if route.leaf_count:
146
+ stock_score += (route.leaves_in_stock + route.leaves_claimed_correctly) / (2 * route.leaf_count)
147
+ constraints += float(not route.violations)
148
+ if route.valid:
149
+ efficiency += min(1.0, min_depth / max(route.depth, 1))
150
+
151
+ valid_routes = [route for route in routes if route.valid]
152
+ distinct_cuts = {route.first_cut for route in valid_routes}
153
+ similarity = max(
154
+ (
155
+ _jaccard(route.signature, ref_signature)
156
+ for route in valid_routes
157
+ for _, ref_signature in reference_signatures
158
+ ),
159
+ default=0.0,
160
+ )
161
+ exact = any(
162
+ route.signature == ref_signature for route in valid_routes for _, ref_signature in reference_signatures
163
+ )
164
+ components = {
165
+ "parse": 1.0 if routes else 0.0,
166
+ "structure": structure / slots,
167
+ "steps": steps / slots,
168
+ "stock": stock_score / slots,
169
+ "constraints": constraints / slots,
170
+ "efficiency": efficiency / slots,
171
+ "diversity": min(1.0, len(distinct_cuts) / task.min_routes),
172
+ "reference_similarity": similarity,
173
+ "reference_match": float(exact),
174
+ }
175
+ reward = sum(WEIGHTS[name] * value for name, value in components.items())
176
+ failures = list(parsed.errors)
177
+ if routes and not any(route.root_ok for route in routes):
178
+ reward = min(reward, OFF_TARGET_CAP)
179
+ failures.append("no submitted route starts at the target")
180
+ if any(route.false_claims for route in routes):
181
+ reward = min(reward, FALSE_STOCK_CAP)
182
+ failures.append("a leaf claims in_stock=true but is not in the task's stock")
183
+ if len(routes) > task.max_routes:
184
+ failures.append(f"submitted {len(routes)} routes; at most {task.max_routes} allowed")
185
+ if len(distinct_cuts) < task.min_routes:
186
+ failures.append(
187
+ f"{len(distinct_cuts)} valid route(s) with distinct first disconnections; need {task.min_routes}"
188
+ )
189
+ for route in routes:
190
+ failures.extend(f"route {route.index + 1}: {problem}" for problem in _route_problems(route))
191
+ solved = len(distinct_cuts) >= task.min_routes and len(routes) <= task.max_routes
192
+ supports = [result["support"] for route in valid_routes for result in route.step_results]
193
+ tier = "rejected" if not solved else ("template_supported" if "template" in supports else "corpus_supported")
194
+ all_steps = [result for route in routes for result in route.step_results]
195
+ claimed = [route for route in routes if route.root_ok]
196
+ metrics = {
197
+ "route_count": len(routes),
198
+ "valid_routes": len(valid_routes),
199
+ "distinct_valid_first_cuts": len(distinct_cuts),
200
+ "step_validity": round(sum(r["supported"] for r in all_steps) / len(all_steps), 6) if all_steps else 0.0,
201
+ "stock_precision": _stock_precision(claimed),
202
+ "constraint_compliance": round(constraints / slots, 6),
203
+ "min_known_depth": min_depth,
204
+ "best_valid_depth": min((route.depth for route in valid_routes), default=None),
205
+ "reference_similarity": round(similarity, 6),
206
+ "reference_match": exact,
207
+ "routes": [route.to_dict() for route in routes],
208
+ }
209
+ return ScoreResult(
210
+ reward=round(min(1.0, max(0.0, reward)), 6),
211
+ valid=solved,
212
+ verification_tier=tier,
213
+ hard_failures=tuple(dict.fromkeys(failures)),
214
+ components={name: round(value, 6) for name, value in components.items()},
215
+ metrics=metrics,
216
+ step_results=tuple(all_steps),
217
+ )
218
+
219
+ def _evaluate_tree(
220
+ self,
221
+ index: int,
222
+ tree: ParsedTree,
223
+ target: str,
224
+ task: RetroTask,
225
+ stock: frozenset[str],
226
+ excluded: frozenset[str],
227
+ forbidden: frozenset[str],
228
+ ) -> RouteEvaluation:
229
+ route = RouteEvaluation(
230
+ index=index,
231
+ root_ok=tree.root_smiles == target and bool(tree.steps),
232
+ depth=tree.depth,
233
+ errors=list(tree.errors),
234
+ warnings=list(tree.warnings),
235
+ molecule_validity=tree.molecule_validity,
236
+ )
237
+ keys: set[StepKey] = set()
238
+ for step in tree.steps:
239
+ support = self.library.support(step.product, step.reactants)
240
+ reaction_class = classify_step(step.product, step.reactants)
241
+ route.step_results.append(
242
+ {
243
+ "product": step.product,
244
+ "reactants": list(step.reactants),
245
+ "supported": support.supported,
246
+ "support": support.kind,
247
+ "template_count": support.template_count,
248
+ "stereo_match": support.stereo_match,
249
+ "reaction_class": reaction_class.name,
250
+ **({"error": support.error} if support.error else {}),
251
+ }
252
+ )
253
+ if support.product:
254
+ keys.add((support.product, support.reactants))
255
+ if reaction_class.name in forbidden:
256
+ route.violations.append(f"uses forbidden class {reaction_class.name!r}")
257
+ route.signature = frozenset(keys)
258
+ root_step = next((step for step in tree.steps if step.product == tree.root_smiles), None)
259
+ if root_step is not None:
260
+ try:
261
+ route.first_cut = free_key(root_step.product, root_step.reactants)[1]
262
+ except ChemistryError:
263
+ route.first_cut = ()
264
+ if tree.depth > task.max_depth:
265
+ route.violations.append(f"depth {tree.depth} exceeds max_depth {task.max_depth}")
266
+ for smiles, claim in tree.terminal_claims:
267
+ route.leaf_count += 1
268
+ available = smiles in stock
269
+ route.leaves_in_stock += available
270
+ route.leaves_claimed_correctly += available and claim
271
+ if claim and not available:
272
+ route.false_claims.append(smiles)
273
+ if not available:
274
+ route.missing_stock.append(smiles)
275
+ if smiles in excluded:
276
+ route.violations.append(f"uses excluded building block {smiles}")
277
+ return route
278
+
279
+
280
+ def signature(steps: Iterable[Any]) -> frozenset[StepKey]:
281
+ keys = set()
282
+ for step in steps:
283
+ try:
284
+ keys.add(free_key(step.product, step.reactants))
285
+ except ChemistryError:
286
+ continue
287
+ return frozenset(keys)
288
+
289
+
290
+ def route_depth(target: str, steps: Iterable[Any]) -> int:
291
+ """Longest linear sequence of a flat route rooted at ``target``."""
292
+ by_product = {canonicalize_smiles(step.product): step for step in steps}
293
+
294
+ def depth(smiles: str, ancestry: frozenset[str]) -> int:
295
+ step = by_product.get(smiles)
296
+ if step is None or smiles in ancestry:
297
+ return 0
298
+ inner = ancestry | {smiles}
299
+ return 1 + max((depth(canonicalize_smiles(r), inner) for r in step.reactants), default=0)
300
+
301
+ return depth(canonicalize_smiles(target), frozenset())
302
+
303
+
304
+ def route_leaves(target: str, steps: Iterable[Any]) -> set[str]:
305
+ by_product = {canonicalize_smiles(step.product): step for step in steps}
306
+ leaves: set[str] = set()
307
+
308
+ def walk(smiles: str, ancestry: frozenset[str]) -> None:
309
+ step = by_product.get(smiles)
310
+ if step is None or smiles in ancestry:
311
+ leaves.add(smiles)
312
+ return
313
+ for reactant in step.reactants:
314
+ walk(canonicalize_smiles(reactant), ancestry | {smiles})
315
+
316
+ walk(canonicalize_smiles(target), frozenset())
317
+ return leaves
318
+
319
+
320
+ def compliant_references(task: RetroTask, stock: frozenset[str], forbidden: frozenset[str]) -> list[ReferenceRoute]:
321
+ """Known routes that satisfy this task's depth, stock and class constraints."""
322
+ compliant = []
323
+ for route in task.reference_routes:
324
+ if route_depth(task.target_smiles, route.steps) > task.max_depth:
325
+ continue
326
+ if not route_leaves(task.target_smiles, route.steps) <= stock:
327
+ continue
328
+ if forbidden and any(classify_step(step.product, step.reactants).name in forbidden for step in route.steps):
329
+ continue
330
+ compliant.append(route)
331
+ return compliant
332
+
333
+
334
+ def known_routes_submission(task: RetroTask, stock: frozenset[str]) -> dict[str, Any]:
335
+ """The shortest compliant known routes with distinct first cuts, as many as the task needs."""
336
+ available = _canonical_stock(stock) - _canonical_stock(task.constraints.excluded_stock)
337
+ references = sorted(
338
+ compliant_references(task, available, frozenset(task.constraints.forbidden_classes)),
339
+ key=lambda route: route_depth(task.target_smiles, route.steps),
340
+ )
341
+ target = canonicalize_smiles(task.target_smiles)
342
+ chosen, cuts = [], set()
343
+ for route in references:
344
+ root = next((step for step in route.steps if canonicalize_smiles(step.product) == target), None)
345
+ cut = free_key(root.product, root.reactants)[1] if root else ()
346
+ if cut and cut not in cuts:
347
+ cuts.add(cut)
348
+ chosen.append(route)
349
+ return routes_to_submission(task.target_smiles, chosen[: task.min_routes], available)
350
+
351
+
352
+ def _route_problems(route: RouteEvaluation) -> list[str]:
353
+ problems = []
354
+ if route.duplicate:
355
+ problems.append("duplicates an earlier route")
356
+ if not route.root_ok:
357
+ problems.append("does not start with a reaction producing the target")
358
+ problems.extend(route.errors[:5])
359
+ unsupported = [r for r in route.step_results if not r["supported"]]
360
+ if unsupported:
361
+ problems.append(f"{len(unsupported)} step(s) not supported by the reaction library")
362
+ if route.missing_stock:
363
+ problems.append(f"leaves not in stock: {route.missing_stock[:5]}")
364
+ problems.extend(route.violations)
365
+ return problems
366
+
367
+
368
+ def _stock_precision(routes: list[RouteEvaluation]) -> float | None:
369
+ claimed = sum(route.leaves_claimed_correctly + len(route.false_claims) for route in routes)
370
+ if not claimed:
371
+ return None
372
+ return round(sum(route.leaves_claimed_correctly for route in routes) / claimed, 6)
373
+
374
+
375
+ def _jaccard(left: frozenset, right: frozenset) -> float:
376
+ union = left | right
377
+ return len(left & right) / len(union) if union else 0.0
378
+
379
+
380
+ def _rejected(errors: list[str]) -> ScoreResult:
381
+ return ScoreResult(
382
+ reward=0.0,
383
+ valid=False,
384
+ verification_tier="rejected",
385
+ hard_failures=tuple(errors) or ("submission could not be parsed",),
386
+ components={name: 0.0 for name in WEIGHTS},
387
+ metrics={"route_count": 0, "valid_routes": 0},
388
+ step_results=(),
389
+ )
390
+
391
+
392
+ def prepare_stock(stock: frozenset[str]) -> frozenset[str]:
393
+ """Canonicalize a serving stock ahead of the first episode scored against it (cached per stock)."""
394
+ return _canonical_stock(stock)
395
+
396
+
397
+ def _canonical_stock(stock: Iterable[str]) -> frozenset[str]:
398
+ if isinstance(stock, frozenset):
399
+ return _canonicalize_frozen(stock)
400
+ return frozenset(canonicalize_smiles(item) for item in stock)
401
+
402
+
403
+ @lru_cache(maxsize=8)
404
+ def _canonicalize_frozen(stock: frozenset[str]) -> frozenset[str]:
405
+ return frozenset(canonicalize_smiles(item) for item in stock)
openenv/Dockerfile ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Build context: envs/retro_route (core/ and openenv/ side by side), which is
2
+ # also the layout deploy.py uploads to a Space.
3
+ # docker build -f openenv/Dockerfile -t retroenv .
4
+ FROM python:3.12-slim
5
+ # The serving index stores RDKit fingerprints and canonical SMILES; the same RDKit lets the
6
+ # server use them as built. Another version still works, but recomputes them at startup.
7
+ ARG RDKIT_VERSION=2026.3.6
8
+ ENV PYTHONUNBUFFERED=1 PIP_NO_CACHE_DIR=1 HOME=/home/user \
9
+ PORT=8000 ENABLE_WEB_INTERFACE=true MAX_CONCURRENT_ENVS=64 \
10
+ RETROENV_CORPUS_MANIFEST=/app/openenv/corpus-manifest.json \
11
+ RETROENV_BUCKET_ROOT=/data \
12
+ RETROENV_PREPARED_DIR=/home/user/prepared
13
+ # RDKit's molecule drawing (the playground) links against X11 render libraries.
14
+ RUN apt-get update && apt-get install -y --no-install-recommends \
15
+ libxrender1 libxext6 libexpat1 libfreetype6 libfontconfig1 \
16
+ && rm -rf /var/lib/apt/lists/*
17
+ WORKDIR /app
18
+ COPY core /app/core
19
+ COPY openenv /app/openenv
20
+ RUN pip install "rdkit==${RDKIT_VERSION}" /app/core /app/openenv \
21
+ && useradd --create-home --uid 1000 user \
22
+ && chown -R user:user /app
23
+ USER user
24
+ EXPOSE 8000
25
+ HEALTHCHECK --interval=30s --timeout=5s --start-period=120s \
26
+ CMD python -c "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8000/health')"
27
+ # The image holds code and the pinned corpus-manifest.json only. At startup prepare.py takes
28
+ # the snapshot from the bucket mounted at /data, or downloads it when nothing is mounted.
29
+ CMD ["bash", "/app/openenv/start.sh"]
openenv/README.md ADDED
@@ -0,0 +1,126 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: RetroEnv
3
+ emoji: ⚗️
4
+ colorFrom: gray
5
+ colorTo: green
6
+ sdk: docker
7
+ app_port: 8000
8
+ base_path: /web
9
+ pinned: false
10
+ tags: [openenv, chemistry, retrosynthesis, tool-use]
11
+ short_description: Plan retrosynthesis routes with verifier-backed rewards.
12
+ ---
13
+
14
+ # RetroEnv: OpenEnv server
15
+
16
+ An agent gets a target molecule and works back to purchasable starting materials. It uses tools to inspect molecules, search a fixed stock and training precedents, and check disconnections. It ends the episode by submitting molecule/reaction trees with `emit_routes`, and the verifier judges every step against a frozen reaction library; matching the patent route only adds a bonus.
17
+
18
+ The same server is used for training, evaluation and the browser playground at `/web`.
19
+
20
+ ## Read the code
21
+
22
+ - [`retroenv_openenv/environment.py`](retroenv_openenv/environment.py): the MCP tools, the Task API, `reset`, and the terminal reward.
23
+ - [`retroenv_openenv/client.py`](retroenv_openenv/client.py): `RetroEnvClient` for one episode per WebSocket session, and `RemoteRetroRouteEnv` for TRL's `environment_factory`.
24
+ - [`retroenv_openenv/agent.py`](retroenv_openenv/agent.py), [`agent_anthropic.py`](retroenv_openenv/agent_anthropic.py), [`agent_responses.py`](retroenv_openenv/agent_responses.py): model loops for OpenAI-compatible chat, the Claude Messages API and the OpenAI Responses API.
25
+ - [`retroenv_openenv/ui.py`](retroenv_openenv/ui.py): the playground.
26
+ - [`../core/retroenv`](../core/retroenv): chemistry, stock search, tasks and the verifier. Every front-end shares it.
27
+
28
+ ## The episode
29
+
30
+ | Step | What happens |
31
+ |---|---|
32
+ | `reset(split, index)` | Returns the prompt, target, depth budget, route count, constraints and tool names. It never returns known routes, patents or the stock list. |
33
+ | tool calls | MCP `call_tool`. Up to 32 calls per episode (`RETROENV_MAX_TOOL_CALLS`); `emit_routes` always stays available. |
34
+ | `emit_routes(submission)` | Scores the trees. That step returns `done=True` with the dense reward, once. |
35
+
36
+ | Tool | Answers from |
37
+ |---|---|
38
+ | `inspect_molecule`, `pubchem_lookup` | RDKit on the given SMILES |
39
+ | `stock_retrieve` | The task's stock (excluded building blocks absent): exact, InChIKey, class, SMARTS or similarity search, capped at 20 results |
40
+ | `reaction_precedent_search`, `search_literature`, `reaction_conditions_search` | Train-visible corpus reactions only |
41
+ | `validate_disconnection` | Train-visible reactions and frequent templates, never this task's hidden routes. Removed by `RETROENV_TOOLSET=unaided`. |
42
+ | `reaction_class_lookup` | The verifier's own reaction classifier |
43
+ | `emit_routes` | The verifier |
44
+
45
+ The Task API lists splits and public task rows without references: `GET /retro_route/splits`, and `POST /retro_route/task`, `/tasks`, `/task_range` and `/num_tasks`. The API docs are at `/docs`.
46
+
47
+ ## Data and splits
48
+
49
+ The server serves a pinned snapshot of [LiteFold/RetroEnv](https://huggingface.co/datasets/LiteFold/RetroEnv)
50
+ from the public bucket [FineEnvs/retroenv-bucket](https://huggingface.co/buckets/FineEnvs/retroenv-bucket).
51
+ `corpus-manifest.json`, beside the server code, pins it: the release revision, the serving index and the
52
+ SHA-256 of every file a server reads.
53
+
54
+ | Split | Tasks | Use |
55
+ |---|---:|---|
56
+ | `train` | 75,224 | RL rollouts |
57
+ | `dev` | 1,079 | checkpoint selection |
58
+ | `test_id` | 1,083 | unseen targets, training distribution |
59
+ | `test_hard` | 1,119 | longer, novel or rarer chemistry |
60
+ | `final_eval` | 50 | 17 easy, 17 medium, 16 hard from the two test splits (`dataset/build_final_eval.py`) |
61
+
62
+ `final_eval` names tasks of the test splits, so they score exactly as there.
63
+
64
+ ## Run locally
65
+
66
+ From the project folder (`09-retroenv`):
67
+
68
+ ```bash
69
+ uv sync --extra dev --extra eval
70
+ uv run bash envs/retro_route/openenv/start.sh
71
+ ```
72
+
73
+ `start.sh` runs `prepare.py`, which downloads the pinned snapshot from the bucket (about 115 MB,
74
+ once), checks every file's SHA-256, and starts the server; a restart reuses the checked files.
75
+ Startup then takes about 10 s. To serve a local release directory without an index instead:
76
+
77
+ ```bash
78
+ RETROENV_BENCHMARK_DIR=data/release/RetroEnv-RL uv run uvicorn retroenv_openenv.server:app --port 8000
79
+ ```
80
+
81
+ Open <http://localhost:8000/web/> for the playground. Its Plan tab works the way the task does: pick
82
+ the molecule still to make, take a cut the rule library proposes (or type one), check it and its
83
+ pieces with the real tools, and add it to a route drawn as it grows; "Fill from the plan" turns that
84
+ route into the `emit_routes` submission. Each molecule is drawn in 2D and, from an RDKit conformer,
85
+ in 3D (vendored [3Dmol.js](https://3dmol.csb.pitt.edu/), so it works offline). To run one model
86
+ episode against the server:
87
+
88
+ ```bash
89
+ uv run python envs/retro_route/openenv/rollout.py --server http://127.0.0.1:8000 \
90
+ --split final_eval --index 0 --provider anthropic --model claude-opus-5-5
91
+ ```
92
+
93
+ ## Docker and Spaces
94
+
95
+ The image holds code and `corpus-manifest.json` only. On a Space the bucket is mounted read-only at
96
+ `/data` and `prepare.py` copies the snapshot from there; with nothing mounted it downloads it.
97
+
98
+ ```bash
99
+ python deploy.py --stage-only --stage-dir /tmp/retroenv-space
100
+ docker build -t retroenv /tmp/retroenv-space
101
+ docker run --rm -p 8000:8000 retroenv # downloads the pinned snapshot
102
+ ```
103
+
104
+ [FineEnvs/retroenv](https://huggingface.co/spaces/FineEnvs/retroenv) is deployed with:
105
+
106
+ ```bash
107
+ python deploy.py --repo FineEnvs/retroenv --public
108
+ ```
109
+
110
+ `deploy.py` refuses to deploy unless every file the manifest names is already in the bucket, mounts
111
+ the bucket, and sets the variables below. A new snapshot comes from `dataset/publish_bucket.py`,
112
+ which also rewrites `corpus-manifest.json`.
113
+
114
+ | Variable | Default | Meaning |
115
+ |---|---|---|
116
+ | `RETROENV_CORPUS_MANIFEST` | `corpus-manifest.json` here | The serving snapshot to fetch and check |
117
+ | `RETROENV_BUCKET_ROOT` | `/data` in the image | A mounted copy of the bucket; files missing there are downloaded |
118
+ | `RETROENV_BUCKET_ID` | the manifest's | The bucket to download from, if it was renamed |
119
+ | `RETROENV_PREPARED_DIR` | `prepared` | Where the checked snapshot is kept between restarts |
120
+ | `RETROENV_BENCHMARK_DIR` | none | A local release or prepared directory, used as is |
121
+ | `RETROENV_TASKS_REPO` | none | A release dataset `org/name[@revision]`, served without an index |
122
+ | `RETROENV_TOOLSET` | `full` | `unaided` removes `validate_disconnection` (an ablation) |
123
+ | `RETROENV_MAX_TOOL_CALLS` | `32` | Tool budget per episode |
124
+ | `RETROENV_DEFAULT_SPLIT` | `train` | Split used by a reset that names none |
125
+ | `MAX_CONCURRENT_ENVS` | `64` | WebSocket sessions per process |
126
+ | `ENABLE_WEB_INTERFACE` | `true` | Mount the playground at `/web` |
openenv/corpus-manifest.json ADDED
@@ -0,0 +1,115 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "status": "ready",
3
+ "storage": "bucket-sqlite",
4
+ "index_version": 1,
5
+ "snapshot_id": "350672d1218e1bdb4dfce497a41490d0482fe7118ad41102a0d373724bca7ae9",
6
+ "bucket_id": "FineEnvs/retroenv-bucket",
7
+ "source": {
8
+ "repo": "LiteFold/RetroEnv",
9
+ "revision": "7ca4c3ad54ce6223435fd6b77c79018641c8606b",
10
+ "license": "CC-BY-4.0",
11
+ "checksums_sha256": "d496eb913602e6c23ed3821e183a496e52b8948916198f440337e909a6308a22"
12
+ },
13
+ "rdkit_version": "2026.03.6",
14
+ "files": [
15
+ {
16
+ "path": "checksums.json",
17
+ "local": "checksums.json",
18
+ "size": 1405,
19
+ "sha256": "d496eb913602e6c23ed3821e183a496e52b8948916198f440337e909a6308a22"
20
+ },
21
+ {
22
+ "path": "library/reactions.jsonl.gz",
23
+ "local": "library/reactions.jsonl.gz",
24
+ "size": 20082440,
25
+ "sha256": "28c02ab233027892b4161d98b7f3e00c11fee5b104ebe0c3ce88273f1959b956"
26
+ },
27
+ {
28
+ "path": "library/reagents.json",
29
+ "local": "library/reagents.json",
30
+ "size": 10504,
31
+ "sha256": "c9cf7cb30bda7dad0e69718b375b4ab07a5f1ed6e95fc7b7034130525ca2bfbc"
32
+ },
33
+ {
34
+ "path": "library/templates-visible.json",
35
+ "local": "library/templates-visible.json",
36
+ "size": 3642156,
37
+ "sha256": "3c64d9caa44bed8fe02575da65d7dbf35c2046954528969f29a7def40d6f6c81"
38
+ },
39
+ {
40
+ "path": "library/templates.json",
41
+ "local": "library/templates.json",
42
+ "size": 5133935,
43
+ "sha256": "34abc0aeca88d7f6049fc1d9286b9886c4b286d124a94eb654e9093760a77182"
44
+ },
45
+ {
46
+ "path": "manifest.json",
47
+ "local": "manifest.json",
48
+ "size": 8127,
49
+ "sha256": "762bdd85448092c306367142053c63d7f7f0667767df7deb28ffec16b5e36633"
50
+ },
51
+ {
52
+ "path": "stocks/paroutes-archive-leaves.smi",
53
+ "local": "stocks/paroutes-archive-leaves.smi",
54
+ "size": 3469648,
55
+ "sha256": "fef3c876efa32c2584b171bfd95d3f8d40ec7195d379b2b782d667423d84b1c7"
56
+ },
57
+ {
58
+ "path": "openenv/indexes/350672d1218e1bdb4dfce497a41490d0482fe7118ad41102a0d373724bca7ae9/serving.sqlite.gz",
59
+ "local": "serving/serving.sqlite",
60
+ "size": 82295324,
61
+ "sha256": "62369299aedef8b471e5821744a45bc4342369ecb574b1196b6b41efce55b532",
62
+ "unpacked": {
63
+ "size": 196542464,
64
+ "sha256": "45d37b32c4260a477aed76fe67923395b8e21eea2517c4606fba945c09be1634"
65
+ }
66
+ }
67
+ ],
68
+ "evalsets": {
69
+ "final_eval": {
70
+ "path": "openenv/evalsets/final_eval.json",
71
+ "local": "evalsets/final_eval.json",
72
+ "size": 16167,
73
+ "sha256": "4ce62c2416f40e95addd4cc7b7a557ecb9e94a2625cf1d55a43fc141b53e7d65",
74
+ "evalset_id": "6b5112f1fcf6ee374b0ba5a199c7406dc4e0555d7a7c75ce2e2235c310ebf92a",
75
+ "tasks": 50
76
+ }
77
+ },
78
+ "splits": {
79
+ "dev": {
80
+ "tasks": 1079,
81
+ "tiers": {
82
+ "easy": 425,
83
+ "hard": 94,
84
+ "medium": 560
85
+ }
86
+ },
87
+ "test_hard": {
88
+ "tasks": 1119,
89
+ "tiers": {
90
+ "hard": 754,
91
+ "medium": 365
92
+ }
93
+ },
94
+ "test_id": {
95
+ "tasks": 1083,
96
+ "tiers": {
97
+ "easy": 440,
98
+ "hard": 83,
99
+ "medium": 560
100
+ }
101
+ },
102
+ "train": {
103
+ "tasks": 75224,
104
+ "tiers": {
105
+ "easy": 47196,
106
+ "hard": 1662,
107
+ "medium": 26366
108
+ }
109
+ }
110
+ },
111
+ "stocks": {
112
+ "paroutes-archive-leaves": 102915
113
+ },
114
+ "precedents": 177822
115
+ }
openenv/deploy.py ADDED
@@ -0,0 +1,135 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Stage this folder with ../core into a Docker Space layout, and optionally publish it.
3
+
4
+ python deploy.py --stage-only --stage-dir /tmp/retroenv-space # build locally
5
+ docker build -t retroenv /tmp/retroenv-space
6
+ python deploy.py --repo FineEnvs/retroenv --public # the FineEnvs Space
7
+
8
+ The Space runs the same code as a local checkout and serves the same pinned snapshot: the
9
+ image carries code and corpus-manifest.json only. The serving bucket named in the manifest
10
+ is mounted read-only at /data, and prepare.py copies and checks the snapshot from there at
11
+ startup. Every file the manifest names must already be in the bucket, so a Space never
12
+ starts against a half-published snapshot.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import argparse
18
+ import json
19
+ import shutil
20
+ import tempfile
21
+ from pathlib import Path
22
+
23
+ HERE = Path(__file__).resolve().parent
24
+ ENV_ROOT = HERE.parent
25
+ MANIFEST = HERE / "corpus-manifest.json"
26
+ MOUNT = "/data"
27
+ IGNORE = shutil.ignore_patterns("__pycache__", "*.egg-info", ".pytest_cache", ".venv", ".env", "prepared", "tests")
28
+
29
+
30
+ def stage(target: Path) -> Path:
31
+ if target.exists():
32
+ shutil.rmtree(target)
33
+ target.mkdir(parents=True)
34
+ shutil.copytree(ENV_ROOT / "core", target / "core", ignore=IGNORE)
35
+ shutil.copytree(HERE, target / "openenv", ignore=IGNORE)
36
+ shutil.copy2(HERE / "Dockerfile", target / "Dockerfile")
37
+ shutil.copy2(HERE / "README.md", target / "README.md")
38
+ shutil.copy2(ENV_ROOT / ".dockerignore", target / ".dockerignore")
39
+ return target
40
+
41
+
42
+ def live_bucket(api, bucket_id: str) -> str:
43
+ """The bucket's current name. An organization rename keeps HTTP reads working through a
44
+ redirect but breaks a Space's volume mount, so the mount uses the live name."""
45
+ return api.bucket_info(bucket_id).id
46
+
47
+
48
+ def check_bucket(api, bucket: str, manifest: dict) -> None:
49
+ entries = [*manifest["files"], *manifest.get("evalsets", {}).values()]
50
+ expected = {entry["path"]: entry["size"] for entry in entries}
51
+ found = {f.path: f.size for f in api.get_bucket_paths_info(bucket, list(expected))}
52
+ missing = sorted(path for path, size in expected.items() if found.get(path) != size)
53
+ if missing:
54
+ raise SystemExit(f"{bucket} lacks or has wrong sizes for {missing[:10]}; publish the snapshot first")
55
+ print(f"verified {len(expected)} snapshot files in {bucket}")
56
+
57
+
58
+ def main() -> int:
59
+ parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
60
+ parser.add_argument("--repo", help="Space id, e.g. FineEnvs/retroenv")
61
+ parser.add_argument("--public", action="store_true", help="create the Space public (default private)")
62
+ parser.add_argument("--concurrency", type=int, default=64, help="WebSocket sessions per process")
63
+ parser.add_argument("--toolset", choices=("full", "unaided"), default="full")
64
+ parser.add_argument("--hardware", help="Space hardware flavor, e.g. cpu-upgrade (default: leave as is)")
65
+ parser.add_argument("--stage-dir", type=Path)
66
+ parser.add_argument("--stage-only", action="store_true")
67
+ args = parser.parse_args()
68
+
69
+ manifest = json.loads(MANIFEST.read_text())
70
+ if manifest.get("status") != "ready":
71
+ raise SystemExit(f"{MANIFEST} is not a finished snapshot; run dataset/publish_bucket.py")
72
+ staged = stage(args.stage_dir or Path(tempfile.mkdtemp(prefix="retroenv-space-")))
73
+ print(f"staged {staged}")
74
+ if args.stage_only:
75
+ return 0
76
+ if not args.repo:
77
+ parser.error("--repo is required to publish")
78
+
79
+ from huggingface_hub import HfApi, Volume
80
+
81
+ api = HfApi()
82
+ bucket = live_bucket(api, manifest["bucket_id"])
83
+ check_bucket(api, bucket, manifest)
84
+ api.create_repo(args.repo, repo_type="space", space_sdk="docker", private=not args.public, exist_ok=True)
85
+ commit = api.upload_folder(
86
+ repo_id=args.repo,
87
+ repo_type="space",
88
+ folder_path=staged,
89
+ commit_message=f"Serve RetroEnv snapshot {manifest['snapshot_id'][:12]}",
90
+ )
91
+
92
+ runtime = api.space_info(args.repo).runtime
93
+ current = list(runtime.volumes or []) if runtime else []
94
+ volumes = [v for v in current if v.mount_path != MOUNT]
95
+ volumes.append(Volume(type="bucket", source=bucket, mount_path=MOUNT, read_only=True))
96
+ if [v.to_dict() for v in volumes] != [v.to_dict() for v in current]:
97
+ api.set_space_volumes(args.repo, volumes=volumes)
98
+
99
+ settings = {
100
+ "MAX_CONCURRENT_ENVS": str(args.concurrency),
101
+ "ENABLE_WEB_INTERFACE": "true",
102
+ "RETROENV_TOOLSET": args.toolset,
103
+ "RETROENV_BUCKET_ROOT": MOUNT,
104
+ }
105
+ existing = api.get_space_variables(args.repo)
106
+ for key, value in settings.items():
107
+ if key not in existing or existing[key].value != value:
108
+ api.add_space_variable(args.repo, key, value)
109
+ # Either of these would take precedence over the snapshot and serve something else.
110
+ for stale in ("RETROENV_TASKS_REPO", "RETROENV_BENCHMARK_DIR"):
111
+ if stale in existing:
112
+ api.delete_space_variable(args.repo, stale)
113
+ print(f"removed the stale {stale} variable")
114
+ if args.hardware:
115
+ api.request_space_hardware(args.repo, args.hardware)
116
+
117
+ print(
118
+ json.dumps(
119
+ {
120
+ "space": f"https://huggingface.co/spaces/{args.repo}",
121
+ "commit": commit.oid,
122
+ "snapshot_id": manifest["snapshot_id"],
123
+ "bucket": bucket,
124
+ "splits": {name: info["tasks"] for name, info in manifest["splits"].items()}
125
+ | {name: info["tasks"] for name, info in manifest["evalsets"].items()},
126
+ "sessions": args.concurrency,
127
+ },
128
+ indent=2,
129
+ )
130
+ )
131
+ return 0
132
+
133
+
134
+ if __name__ == "__main__":
135
+ raise SystemExit(main())
openenv/openenv.yaml ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ spec_version: 1
2
+ name: retro_route
3
+ type: space
4
+ runtime: fastapi
5
+ app: retroenv_openenv.server:app
6
+ port: 8000
7
+
8
+ variables:
9
+ RETROENV_CORPUS_MANIFEST: "" # the serving snapshot (default: corpus-manifest.json here), or
10
+ RETROENV_BENCHMARK_DIR: "" # a local release or prepared directory, or
11
+ RETROENV_TASKS_REPO: "" # a release dataset (org/name or org/name@revision)
12
+ RETROENV_BUCKET_ROOT: "" # a mounted copy of the serving bucket (/data on the Space)
13
+ RETROENV_DEFAULT_SPLIT: train # splits: train, dev, test_id, test_hard, final_eval
14
+ RETROENV_MAX_TOOL_CALLS: "32"
15
+ RETROENV_TOOLSET: full # full | unaided (no validate_disconnection)
16
+ MAX_CONCURRENT_ENVS: "64"
openenv/prepare.py ADDED
@@ -0,0 +1,203 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Make the data a server reads available before it starts, and check every byte of it.
3
+
4
+ Three sources, tried in this order:
5
+
6
+ * ``RETROENV_BENCHMARK_DIR``: a local release or prepared directory, used as it is.
7
+ * ``RETROENV_CORPUS_MANIFEST``: a pinned serving snapshot in the FineEnvs bucket. This is the
8
+ default (``corpus-manifest.json`` beside this file) when nothing else is set, and what the
9
+ Docker image serves. Each file the manifest names comes from ``RETROENV_BUCKET_ROOT`` when
10
+ that directory holds it (a Space mounts the bucket there), and otherwise over HTTP from the
11
+ public bucket (``RETROENV_BUCKET_ID`` overrides its name). Every file is checked against its
12
+ SHA-256, and files already in ``RETROENV_PREPARED_DIR`` with the right digest are kept, so a
13
+ restart fetches nothing.
14
+ * ``RETROENV_TASKS_REPO=org/name[@revision]``: download a release dataset such as
15
+ ``LiteFold/RetroEnv``, check it against its checksums.json, and serve it without an index
16
+ (``RETROENV_TASKS_SUBDIR`` selects a subdirectory of the repo).
17
+
18
+ The last line printed is the directory to serve; ``start.sh`` passes it to the server.
19
+ """
20
+
21
+ from __future__ import annotations
22
+
23
+ import gzip
24
+ import hashlib
25
+ import json
26
+ import os
27
+ import shutil
28
+ import sys
29
+ from pathlib import Path
30
+
31
+ HERE = Path(__file__).resolve().parent
32
+ DEFAULT_MANIFEST = HERE / "corpus-manifest.json"
33
+ RELEASE_FILES = ("checksums.json", "manifest.json")
34
+
35
+
36
+ def sha256_file(path: Path) -> str:
37
+ digest = hashlib.sha256()
38
+ with path.open("rb") as handle:
39
+ for block in iter(lambda: handle.read(1 << 20), b""):
40
+ digest.update(block)
41
+ return digest.hexdigest()
42
+
43
+
44
+ def verify(root: Path) -> None:
45
+ """Check a directory against the snapshot it was prepared from, or a release's checksums."""
46
+ pinned = root / "corpus-manifest.json"
47
+ if pinned.exists():
48
+ manifest = json.loads(pinned.read_text())
49
+ bad = [e["local"] for e in _entries(manifest) if not _matches(root / e["local"], _unpacked(e))]
50
+ if bad:
51
+ raise SystemExit(f"prepare: {root} does not match its corpus manifest: {bad[:5]}")
52
+ print(f"prepare: verified {len(_entries(manifest))} file(s) in {root}", file=sys.stderr)
53
+ return
54
+ if not all((root / name).is_dir() for name in ("tasks-private", "stocks", "library")):
55
+ raise SystemExit(f"{root} needs tasks-private/, stocks/ and library/")
56
+ manifest = root / "checksums.json"
57
+ if not manifest.exists():
58
+ print(f"prepare: {root} has no checksums.json; skipping verification", file=sys.stderr)
59
+ return
60
+ expected = json.loads(manifest.read_text())["sha256"]
61
+ # The tasks, the stock and the reaction library all decide rewards, so a
62
+ # missing or altered file is a startup failure, not something to skip.
63
+ required = {name for name in expected if name.startswith(("tasks-private/", "stocks/", "library/"))}
64
+ for name in sorted(required):
65
+ path = root / name
66
+ if not path.exists():
67
+ raise SystemExit(f"prepare: {path} is listed in checksums.json but missing")
68
+ if hashlib.sha256(path.read_bytes()).hexdigest() != expected[name]:
69
+ raise SystemExit(f"prepare: checksum mismatch for {path}")
70
+ print(f"prepare: verified {len(required)} file(s) in {root}", file=sys.stderr)
71
+
72
+
73
+ def _entries(manifest: dict) -> list[dict]:
74
+ return [*manifest["files"], *manifest.get("evalsets", {}).values()]
75
+
76
+
77
+ def _unpacked(entry: dict) -> dict:
78
+ """What the prepared file must match: the entry itself, or what its gzip expands to."""
79
+ return entry.get("unpacked") or entry
80
+
81
+
82
+ def _matches(path: Path, expected: dict) -> bool:
83
+ return path.exists() and path.stat().st_size == expected["size"] and sha256_file(path) == expected["sha256"]
84
+
85
+
86
+ def _fetched(prepared: Path, entry: dict) -> Path:
87
+ """Where a file lands before it is checked: still gzipped if the bucket stores it packed."""
88
+ target = prepared / entry["local"]
89
+ return target.with_name(target.name + (".gz.partial" if entry.get("unpacked") else ".partial"))
90
+
91
+
92
+ def _settle(prepared: Path, entry: dict) -> bool:
93
+ """Check a fetched file, unpack it if needed, and move it into place; False if it is bad."""
94
+ target, fetched = prepared / entry["local"], _fetched(prepared, entry)
95
+ if not _matches(fetched, entry):
96
+ fetched.unlink()
97
+ return False
98
+ if entry.get("unpacked"):
99
+ unpacked = target.with_name(target.name + ".partial")
100
+ with gzip.open(fetched, "rb") as source, unpacked.open("wb") as sink:
101
+ shutil.copyfileobj(source, sink, 1 << 20)
102
+ fetched.unlink()
103
+ if not _matches(unpacked, entry["unpacked"]):
104
+ unpacked.unlink()
105
+ return False
106
+ fetched = unpacked
107
+ fetched.replace(target)
108
+ return True
109
+
110
+
111
+ def from_bucket(manifest_path: Path, prepared: Path) -> Path:
112
+ """Fetch and check a pinned serving snapshot into ``prepared``."""
113
+ manifest = json.loads(manifest_path.read_text())
114
+ if manifest.get("status") != "ready" or manifest.get("storage") != "bucket-sqlite":
115
+ raise SystemExit(f"prepare: {manifest_path} is not a finished serving snapshot")
116
+ bucket = os.getenv("RETROENV_BUCKET_ID") or manifest["bucket_id"]
117
+ mount = Path(os.environ["RETROENV_BUCKET_ROOT"]) if os.getenv("RETROENV_BUCKET_ROOT") else None
118
+ prepared.mkdir(parents=True, exist_ok=True)
119
+ pending, copied, kept = [], 0, 0
120
+ for entry in _entries(manifest):
121
+ target = prepared / entry["local"]
122
+ target.parent.mkdir(parents=True, exist_ok=True)
123
+ if _matches(target, _unpacked(entry)):
124
+ kept += 1
125
+ continue
126
+ mounted = mount / entry["path"] if mount else None
127
+ if mounted is not None and mounted.exists() and mounted.stat().st_size == entry["size"]:
128
+ shutil.copyfile(mounted, _fetched(prepared, entry))
129
+ copied += 1
130
+ else:
131
+ pending.append(entry)
132
+ if pending:
133
+ from huggingface_hub import HfApi
134
+
135
+ HfApi().download_bucket_files(
136
+ bucket,
137
+ [(e["path"], str(_fetched(prepared, e))) for e in pending],
138
+ raise_on_missing_files=True,
139
+ token=os.getenv("HF_TOKEN") or None,
140
+ )
141
+ # Settle every fetched file before failing: good ones are kept for the next attempt.
142
+ bad = [e["path"] for e in _entries(manifest) if _fetched(prepared, e).exists() and not _settle(prepared, e)]
143
+ if bad:
144
+ raise SystemExit(f"prepare: {bad} from {bucket} does not match its manifest digest")
145
+ # An evaluation set from an earlier snapshot would otherwise still be served.
146
+ listed = {Path(e["local"]).name for e in manifest.get("evalsets", {}).values()}
147
+ for stale in (prepared / "evalsets").glob("*.json"):
148
+ if stale.name not in listed:
149
+ stale.unlink()
150
+ shutil.copyfile(manifest_path, prepared / "corpus-manifest.json")
151
+ print(
152
+ f"prepare: snapshot {manifest['snapshot_id'][:12]} from {bucket}: "
153
+ f"{kept} kept, {copied} copied from {mount}, {len(pending)} downloaded",
154
+ file=sys.stderr,
155
+ )
156
+ verify(prepared)
157
+ return prepared
158
+
159
+
160
+ def from_repo(repo: str, prepared: Path) -> Path:
161
+ from huggingface_hub import snapshot_download
162
+
163
+ repo_id, _, revision = repo.partition("@")
164
+ subdir = os.getenv("RETROENV_TASKS_SUBDIR", "").strip("/")
165
+ prefix = f"{subdir}/" if subdir else ""
166
+ snapshot_download(
167
+ repo_id,
168
+ repo_type="dataset",
169
+ revision=revision or None,
170
+ local_dir=prepared,
171
+ allow_patterns=[f"{prefix}{name}" for name in ("tasks-private/*", "stocks/*", "library/*", *RELEASE_FILES)],
172
+ token=os.getenv("HF_TOKEN") or None,
173
+ )
174
+ target = prepared / subdir if subdir else prepared
175
+ verify(target)
176
+ return target
177
+
178
+
179
+ def main() -> int:
180
+ local = os.getenv("RETROENV_BENCHMARK_DIR")
181
+ if local:
182
+ verify(Path(local))
183
+ print(local)
184
+ return 0
185
+ prepared = Path(os.getenv("RETROENV_PREPARED_DIR", "prepared"))
186
+ manifest = os.getenv("RETROENV_CORPUS_MANIFEST")
187
+ repo = os.getenv("RETROENV_TASKS_REPO")
188
+ if manifest or (not repo and DEFAULT_MANIFEST.exists()):
189
+ target = from_bucket(Path(manifest) if manifest else DEFAULT_MANIFEST, prepared)
190
+ elif repo:
191
+ target = from_repo(repo, prepared)
192
+ else:
193
+ raise SystemExit(
194
+ "Set RETROENV_BENCHMARK_DIR, RETROENV_CORPUS_MANIFEST (a serving snapshot), "
195
+ "or RETROENV_TASKS_REPO to a released task dataset on the Hub."
196
+ )
197
+ # start.sh serves whatever this prints last.
198
+ print(target)
199
+ return 0
200
+
201
+
202
+ if __name__ == "__main__":
203
+ raise SystemExit(main())
openenv/pyproject.toml ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [build-system]
2
+ requires = ["setuptools>=69", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "retroenv-openenv"
7
+ version = "0.2.0"
8
+ description = "OpenEnv MCP server, client, agent loop and browser playground for RetroEnv"
9
+ requires-python = ">=3.11"
10
+ dependencies = [
11
+ "retroenv-core",
12
+ "openenv==0.4.2",
13
+ "fastmcp>=3,<4",
14
+ "gradio>=5",
15
+ "uvicorn[standard]>=0.30",
16
+ "huggingface-hub>=0.25",
17
+ "openai>=1.55",
18
+ "json-repair>=0.30",
19
+ ]
20
+
21
+ [project.optional-dependencies]
22
+ anthropic = ["anthropic>=1.0"]
23
+
24
+ [tool.uv.sources]
25
+ retroenv-core = { path = "../core", editable = true }
26
+
27
+ [tool.setuptools.packages.find]
28
+ include = ["retroenv_openenv*"]
29
+
30
+ [tool.setuptools.package-data]
31
+ # The vendored 3Dmol.js (BSD-3-Clause) that draws molecules in 3D in the playground.
32
+ retroenv_openenv = ["static/*"]
openenv/retroenv_openenv/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ """OpenEnv front-end for RetroEnv: MCP server, client, agent loop and playground."""
openenv/retroenv_openenv/agent.py ADDED
@@ -0,0 +1,287 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """OpenAI-compatible tool-calling agent loop against a RetroEnv server.
2
+
3
+ The final model turn exposes only emit_routes, two empty turns force that
4
+ terminal turn, and each tool result carries the turns left. Tools are
5
+ discovered from the server and every call goes through it, so the reward is
6
+ the server's. An episode that ends without emit_routes is closed by
7
+ submitting an empty route set, which scores the verifier's floor.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import json
13
+ import random
14
+ import time
15
+ from dataclasses import dataclass, field
16
+ from typing import Any
17
+
18
+ import json_repair
19
+
20
+ from .client import RetroEnvClient
21
+
22
+ SYSTEM_PROMPT = (
23
+ "You are a retrosynthesis planning agent. Plan with the tools: inspect molecules, search "
24
+ "precedents, check each disconnection with validate_disconnection, and confirm every leaf "
25
+ "with an exact stock_retrieve lookup before claiming in_stock=true. Respect the depth "
26
+ "budget and any constraint in the task. Finish only with emit_routes. You have at most "
27
+ "{max_turns} model turns and must reserve the final turn for emit_routes even if the routes "
28
+ "are incomplete. Pass emit_routes.submission as a JSON object, not as a string. Do not "
29
+ "reveal chain-of-thought; put short evidence-based explanations in reaction metadata."
30
+ )
31
+
32
+
33
+ # Shown on the last turn when the endpoint cannot force a tool call.
34
+ FINAL_TURN = (
35
+ "This is your final turn. Call emit_routes now with the best route trees you have; no other tool is available."
36
+ )
37
+
38
+
39
+ def normalize_arguments(name: str, arguments: dict[str, Any]) -> tuple[dict[str, Any], bool]:
40
+ """Undo one provider-side encoding slip: a route submission sent as a JSON string.
41
+
42
+ Some models serialize a deeply nested argument into a string and then break
43
+ its escaping or brackets. The harness repairs that string before the call
44
+ (and flags it) so the score measures the routes, not the transport. Anything
45
+ that does not repair into a route-set object is passed through for the
46
+ verifier to judge.
47
+ """
48
+ value = arguments.get("submission")
49
+ if name != "emit_routes" or not isinstance(value, str):
50
+ return arguments, False
51
+ decoded = json_repair.loads(value)
52
+ if not isinstance(decoded, dict) or "routes" not in decoded:
53
+ return arguments, False
54
+ return {**arguments, "submission": decoded}, True
55
+
56
+
57
+ @dataclass
58
+ class AgentConfig:
59
+ model: str
60
+ max_turns: int = 16
61
+ max_tokens: int = 4096
62
+ # None omits the parameter (reasoning models reject explicit temperatures).
63
+ temperature: float | None = 0.0
64
+ tool_choice: str = "required"
65
+ max_empty_turns: int = 2
66
+ # "max_tokens" for most endpoints; OpenAI reasoning models want "max_completion_tokens".
67
+ token_param: str = "max_tokens"
68
+ parallel_tool_calls: bool | None = False
69
+ reasoning_effort: str | None = None
70
+ extra_body: dict[str, Any] = field(default_factory=dict)
71
+
72
+
73
+ RETRY_DELAYS = (5, 15, 30, 60, 90, 120)
74
+ TRANSIENT = ("RateLimitError", "APITimeoutError", "APIConnectionError", "InternalServerError")
75
+ # InternLM reports rate limits as HTTP 400 with this error code.
76
+ RATE_LIMIT_CODES = ("-20048",)
77
+
78
+
79
+ def _is_transient(exc: Exception) -> bool:
80
+ return type(exc).__name__ in TRANSIENT or getattr(exc, "code", None) in RATE_LIMIT_CODES
81
+
82
+
83
+ def _request_with_retry(client: Any, config: AgentConfig, messages: list, tools: list) -> Any:
84
+ """Retry rate limits, timeouts, 5xx and empty responses; other errors surface at once."""
85
+ for delay in (*RETRY_DELAYS, None):
86
+ try:
87
+ response = _request(client, config, messages, tools)
88
+ except Exception as exc:
89
+ if delay is None or not _is_transient(exc):
90
+ raise
91
+ else:
92
+ if response.choices or delay is None:
93
+ return response
94
+ time.sleep(delay + random.uniform(0, delay / 4))
95
+ raise RuntimeError("unreachable")
96
+
97
+
98
+ def _request(client: Any, config: AgentConfig, messages: list, tools: list) -> Any:
99
+ kwargs: dict[str, Any] = {
100
+ "model": config.model,
101
+ "messages": messages,
102
+ "tools": tools,
103
+ "tool_choice": config.tool_choice,
104
+ config.token_param: config.max_tokens,
105
+ }
106
+ if config.temperature is not None:
107
+ kwargs["temperature"] = config.temperature
108
+ if config.parallel_tool_calls is not None:
109
+ kwargs["parallel_tool_calls"] = config.parallel_tool_calls
110
+ if config.reasoning_effort:
111
+ kwargs["reasoning_effort"] = config.reasoning_effort
112
+ if config.extra_body:
113
+ kwargs["extra_body"] = config.extra_body
114
+ return client.chat.completions.create(**kwargs)
115
+
116
+
117
+ def recorded(entry: dict[str, Any], message: Any) -> dict[str, Any]:
118
+ """The transcript form of an assistant turn: the entry sent back to the model, plus its thinking.
119
+
120
+ Providers return thinking beside the reply, as ``reasoning`` (OpenRouter) or ``reasoning_content``
121
+ (vLLM-style servers). It is kept out of the history the model is sent, which stays unchanged.
122
+ """
123
+ thinking = getattr(message, "reasoning", None) or getattr(message, "reasoning_content", None)
124
+ return {**entry, "reasoning": str(thinking)} if thinking else entry
125
+
126
+
127
+ def close_episode(env: RetroEnvClient) -> tuple[dict[str, Any], Any]:
128
+ """Score an episode the model never closed, and return (score, submission).
129
+
130
+ An emit_routes call that failed in transport may still have been scored by
131
+ the server. Submitting an empty route set then returns that earlier score
132
+ with an "error" saying the episode is already complete, so the recorded
133
+ reward is the one the routes actually earned; ``submission`` is None in
134
+ that case, because the empty set was not what was scored.
135
+ """
136
+ outcome = env.call("emit_routes", {"submission": {"routes": []}})
137
+ result = outcome.result if isinstance(outcome.result, dict) else {}
138
+ score = dict(result.get("score") or {})
139
+ already_complete = "error" in result
140
+ if outcome.reward is not None:
141
+ score["reward"] = float(outcome.reward)
142
+ score.setdefault("reward", 0.0)
143
+ if already_complete:
144
+ score["recovered_after_transport_error"] = True
145
+ return score, None if already_complete else {"routes": []}
146
+
147
+
148
+ def run_episode(llm: Any, env: RetroEnvClient, opening: dict[str, Any], config: AgentConfig) -> dict[str, Any]:
149
+ tools = env.openai_tools()
150
+ emit_tool = [tool for tool in tools if tool["function"]["name"] == "emit_routes"]
151
+ allowed = {tool["function"]["name"] for tool in tools}
152
+ messages: list[dict[str, Any]] = [
153
+ {"role": "system", "content": SYSTEM_PROMPT.format(max_turns=config.max_turns)},
154
+ {"role": "user", "content": opening["prompt"]},
155
+ ]
156
+ transcript: list[dict[str, Any]] = []
157
+ errors: list[str] = []
158
+ usage = {"prompt_tokens": 0, "completion_tokens": 0, "reported_cost_usd": 0.0}
159
+ resolved_models: set[str] = set()
160
+ submission: Any = None
161
+ final: dict[str, Any] | None = None
162
+ tool_calls = 0
163
+ empty_turns = 0
164
+ force_terminal = False
165
+ coerced = False
166
+ turns = 0
167
+ started = time.perf_counter()
168
+
169
+ for turn_index in range(config.max_turns):
170
+ terminal_turn = force_terminal or turn_index == config.max_turns - 1
171
+ # force_terminal already told the model this in the nudge below.
172
+ if terminal_turn and not force_terminal and config.tool_choice != "required":
173
+ final_turn = {"role": "user", "content": FINAL_TURN}
174
+ messages.append(final_turn)
175
+ transcript.append(final_turn)
176
+ try:
177
+ response = _request_with_retry(llm, config, messages, emit_tool if terminal_turn else tools)
178
+ except Exception as exc: # provider errors end the episode; it is still scored
179
+ errors.append(f"API error: {type(exc).__name__}: {str(exc)[:500]}")
180
+ break
181
+ turns += 1
182
+ if response.usage:
183
+ usage["prompt_tokens"] += int(response.usage.prompt_tokens or 0)
184
+ usage["completion_tokens"] += int(response.usage.completion_tokens or 0)
185
+ extra = getattr(response.usage, "model_extra", None) or {}
186
+ usage["reported_cost_usd"] += float(extra.get("cost") or 0.0)
187
+ if getattr(response, "model", None):
188
+ resolved_models.add(str(response.model))
189
+ if not response.choices:
190
+ errors.append("API returned no choices")
191
+ break
192
+ message = response.choices[0].message
193
+ calls = message.tool_calls or []
194
+ if not calls:
195
+ empty_turns += 1
196
+ errors.append(f"no tool call on turn {turn_index + 1}: {(message.content or '')[:200]}")
197
+ assistant = {"role": "assistant", "content": message.content or ""}
198
+ messages.append(assistant)
199
+ transcript.append(recorded(assistant, message))
200
+ if terminal_turn:
201
+ break
202
+ force_terminal = empty_turns >= config.max_empty_turns
203
+ nudge = {
204
+ "role": "user",
205
+ "content": (
206
+ "The empty-turn limit was reached. On the next turn call emit_routes with the "
207
+ "best route trees available; no other tool will be exposed."
208
+ if force_terminal
209
+ else "No tool call was emitted. Continue by calling one of the available tools "
210
+ "now; on your final turn you must call emit_routes."
211
+ ),
212
+ }
213
+ messages.append(nudge)
214
+ transcript.append(nudge)
215
+ continue
216
+
217
+ assistant = {
218
+ "role": "assistant",
219
+ "content": message.content or "",
220
+ "tool_calls": [call.model_dump(exclude_none=True) for call in calls],
221
+ }
222
+ messages.append(assistant)
223
+ transcript.append(recorded(assistant, message))
224
+ for call in calls:
225
+ name = call.function.name
226
+ try:
227
+ arguments = json.loads(call.function.arguments or "{}")
228
+ if not isinstance(arguments, dict):
229
+ raise ValueError("arguments must be a JSON object")
230
+ except ValueError as exc:
231
+ result: Any = {"error": f"invalid tool arguments: {exc}"}
232
+ errors.append(result["error"])
233
+ else:
234
+ arguments, was_coerced = normalize_arguments(name, arguments)
235
+ coerced = coerced or was_coerced
236
+ if name not in allowed:
237
+ result = {"error": f"unknown tool {name!r}"}
238
+ else:
239
+ outcome = env.call(name, arguments)
240
+ tool_calls += 1
241
+ result = outcome.result if outcome.error is None else {"error": outcome.error}
242
+ if name == "emit_routes":
243
+ submission = arguments.get("submission")
244
+ if outcome.done and outcome.reward is not None:
245
+ score = result.get("score") if isinstance(result, dict) else None
246
+ final = {**(score or {}), "reward": float(outcome.reward)}
247
+ content = result if isinstance(result, dict) else {"result": result}
248
+ tool_message = {
249
+ "role": "tool",
250
+ "tool_call_id": call.id,
251
+ "name": name,
252
+ "content": json.dumps({**content, "model_turns_remaining": config.max_turns - turns}, sort_keys=True),
253
+ }
254
+ messages.append(tool_message)
255
+ transcript.append(tool_message)
256
+ if final is not None:
257
+ break
258
+
259
+ auto_emitted = False
260
+ if final is None:
261
+ final, fallback = close_episode(env)
262
+ auto_emitted = True
263
+ if fallback is not None:
264
+ submission = fallback
265
+
266
+ return {
267
+ "reward": final.get("reward", 0.0),
268
+ "valid": bool(final.get("valid", False)),
269
+ "exact_match": bool((final.get("metrics") or {}).get("reference_match", False)),
270
+ "components": final.get("components", {}),
271
+ "hard_failures": final.get("hard_failures", []),
272
+ "verification_tier": final.get("verification_tier"),
273
+ "route_count": (final.get("metrics") or {}).get("route_count", 0),
274
+ "submission": submission,
275
+ "auto_emitted": auto_emitted,
276
+ "submission_coerced": coerced,
277
+ "tool_calls": tool_calls,
278
+ "turns": turns,
279
+ "errors": errors,
280
+ "usage": {
281
+ **usage,
282
+ "reported_cost_usd": round(usage["reported_cost_usd"], 8),
283
+ "latency_seconds": round(time.perf_counter() - started, 3),
284
+ },
285
+ "resolved_models": sorted(resolved_models),
286
+ "transcript": transcript,
287
+ }
openenv/retroenv_openenv/agent_anthropic.py ADDED
@@ -0,0 +1,208 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Claude agent loop against a RetroEnv server, on the Anthropic Messages API.
2
+
3
+ Same protocol as ``agent.run_episode`` (turn budget, a final emit_routes turn,
4
+ empty-turn recovery, turns-left in every tool result) and the same result
5
+ shape. Two Claude-specific choices:
6
+
7
+ * Current models reject a forced ``tool_choice``, so the final turn exposes
8
+ only emit_routes with ``tool_choice=auto`` and says so in the user turn.
9
+ * The history is append-only (assistant content is sent back unchanged, so
10
+ thinking blocks stay valid), and top-level ``cache_control`` caches it.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import json
16
+ import sys
17
+ import time
18
+ from dataclasses import dataclass
19
+ from typing import Any
20
+
21
+ import anthropic
22
+
23
+ from .agent import FINAL_TURN, SYSTEM_PROMPT, close_episode, normalize_arguments
24
+ from .client import RetroEnvClient
25
+
26
+ # USD per million tokens: input, output, cache read. Cache writes bill 1.25x input.
27
+ PRICES = {
28
+ "claude-opus-5-5": (4.00, 20.00, 0.20),
29
+ "claude-opus-5": (5.00, 25.00, 0.50),
30
+ "claude-opus-4-8": (5.00, 25.00, 0.50),
31
+ "claude-sonnet-5-5": (2.00, 10.00, 0.20),
32
+ "claude-sonnet-5": (2.00, 10.00, 0.20),
33
+ "claude-sonnet-4-6": (3.00, 15.00, 0.30),
34
+ "claude-haiku-4-5": (1.00, 5.00, 0.10),
35
+ "claude-fable-5-1": (10.00, 50.00, 0.25),
36
+ "claude-fable-5": (10.00, 50.00, 1.00),
37
+ }
38
+
39
+
40
+ @dataclass
41
+ class ClaudeConfig:
42
+ model: str = "claude-opus-5-5"
43
+ max_turns: int = 16
44
+ max_tokens: int = 16000
45
+ # None keeps the model default (medium on Claude Opus 5.5, high on Sonnet 5.5).
46
+ effort: str | None = None
47
+ max_empty_turns: int = 2
48
+ parallel_tool_calls: bool = False
49
+
50
+
51
+ def _cost(model: str, usage: dict[str, int]) -> float | None:
52
+ price = PRICES.get(model)
53
+ if price is None:
54
+ # Better a visible gap in the board than a confident wrong total.
55
+ print(f"warning: no price for {model!r}; cost will be reported as null", file=sys.stderr)
56
+ return None
57
+ input_price, output_price, cache_read_price = price
58
+ return (
59
+ usage["input_tokens"] * input_price
60
+ + usage["cache_creation_input_tokens"] * input_price * 1.25
61
+ + usage["cache_read_input_tokens"] * cache_read_price
62
+ + usage["output_tokens"] * output_price
63
+ ) / 1_000_000
64
+
65
+
66
+ def _block(block: Any) -> dict[str, Any]:
67
+ value = block.model_dump(exclude_none=True)
68
+ value.pop("signature", None) # opaque; not useful in a stored transcript
69
+ return value
70
+
71
+
72
+ def run_episode(
73
+ llm: anthropic.Anthropic, env: RetroEnvClient, opening: dict[str, Any], config: ClaudeConfig
74
+ ) -> dict[str, Any]:
75
+ tools = [
76
+ {
77
+ "name": tool["function"]["name"],
78
+ "description": tool["function"]["description"],
79
+ "input_schema": tool["function"]["parameters"],
80
+ }
81
+ for tool in env.openai_tools()
82
+ ]
83
+ emit_tool = [tool for tool in tools if tool["name"] == "emit_routes"]
84
+ allowed = {tool["name"] for tool in tools}
85
+ system = SYSTEM_PROMPT.format(max_turns=config.max_turns)
86
+ messages: list[dict[str, Any]] = [{"role": "user", "content": [{"type": "text", "text": opening["prompt"]}]}]
87
+ transcript: list[dict[str, Any]] = [{"role": "user", "content": opening["prompt"]}]
88
+ errors: list[str] = []
89
+ usage = {"input_tokens": 0, "output_tokens": 0, "cache_read_input_tokens": 0, "cache_creation_input_tokens": 0}
90
+ submission: Any = None
91
+ final: dict[str, Any] | None = None
92
+ tool_calls = 0
93
+ empty_turns = 0
94
+ force_terminal = False
95
+ coerced = False
96
+ turns = 0
97
+ started = time.perf_counter()
98
+
99
+ for turn_index in range(config.max_turns):
100
+ terminal_turn = force_terminal or turn_index == config.max_turns - 1
101
+ if terminal_turn:
102
+ messages[-1]["content"].append({"type": "text", "text": FINAL_TURN})
103
+ request: dict[str, Any] = {
104
+ "model": config.model,
105
+ "max_tokens": config.max_tokens,
106
+ "system": system,
107
+ "messages": messages,
108
+ "tools": emit_tool if terminal_turn else tools,
109
+ "tool_choice": {"type": "auto", "disable_parallel_tool_use": not config.parallel_tool_calls},
110
+ "cache_control": {"type": "ephemeral"},
111
+ }
112
+ if config.effort:
113
+ request["output_config"] = {"effort": config.effort}
114
+ try:
115
+ response = llm.messages.create(**request)
116
+ except anthropic.APIStatusError as exc:
117
+ errors.append(f"API error {exc.status_code}: {str(exc.message)[:500]}")
118
+ break
119
+ except anthropic.APIConnectionError as exc:
120
+ errors.append(f"API connection error: {exc}")
121
+ break
122
+ turns += 1
123
+ for key in usage:
124
+ usage[key] += int(getattr(response.usage, key, 0) or 0)
125
+ messages.append({"role": "assistant", "content": response.content})
126
+ transcript.append(
127
+ {"role": "assistant", "content": [_block(b) for b in response.content], "stop_reason": response.stop_reason}
128
+ )
129
+ if response.stop_reason == "refusal":
130
+ details = getattr(response, "stop_details", None)
131
+ errors.append(f"refusal: {getattr(details, 'category', None)}")
132
+ break
133
+
134
+ calls = [block for block in response.content if block.type == "tool_use"]
135
+ if not calls:
136
+ empty_turns += 1
137
+ text = " ".join(b.text for b in response.content if b.type == "text")
138
+ errors.append(f"no tool call on turn {turn_index + 1} ({response.stop_reason}): {text[:200]}")
139
+ if terminal_turn:
140
+ break
141
+ force_terminal = empty_turns >= config.max_empty_turns
142
+ nudge = (
143
+ "No tool call was made. Call one of the available tools now; on your final "
144
+ "turn you must call emit_routes."
145
+ )
146
+ messages.append({"role": "user", "content": [{"type": "text", "text": nudge}]})
147
+ transcript.append({"role": "user", "content": nudge})
148
+ continue
149
+
150
+ results = []
151
+ for call in calls:
152
+ arguments, was_coerced = normalize_arguments(call.name, call.input if isinstance(call.input, dict) else {})
153
+ coerced = coerced or was_coerced
154
+ if call.name not in allowed:
155
+ content: Any = {"error": f"unknown tool {call.name!r}"}
156
+ is_error = True
157
+ else:
158
+ outcome = env.call(call.name, arguments)
159
+ tool_calls += 1
160
+ is_error = outcome.error is not None
161
+ content = outcome.result if not is_error else {"error": outcome.error}
162
+ if call.name == "emit_routes":
163
+ submission = arguments.get("submission")
164
+ if outcome.done and outcome.reward is not None:
165
+ score = content.get("score") if isinstance(content, dict) else None
166
+ final = {**(score or {}), "reward": float(outcome.reward)}
167
+ payload = content if isinstance(content, dict) else {"result": content}
168
+ text = json.dumps({**payload, "model_turns_remaining": config.max_turns - turns}, sort_keys=True)
169
+ results.append({"type": "tool_result", "tool_use_id": call.id, "content": text, "is_error": is_error})
170
+ messages.append({"role": "user", "content": results})
171
+ transcript.append({"role": "user", "content": results})
172
+ if final is not None:
173
+ break
174
+
175
+ auto_emitted = False
176
+ if final is None:
177
+ final, fallback = close_episode(env)
178
+ auto_emitted = True
179
+ if fallback is not None:
180
+ submission = fallback
181
+
182
+ cost = _cost(config.model, usage)
183
+ return {
184
+ "reward": final.get("reward", 0.0),
185
+ "valid": bool(final.get("valid", False)),
186
+ "exact_match": bool((final.get("metrics") or {}).get("reference_match", False)),
187
+ "components": final.get("components", {}),
188
+ "hard_failures": final.get("hard_failures", []),
189
+ "verification_tier": final.get("verification_tier"),
190
+ "route_count": (final.get("metrics") or {}).get("route_count", 0),
191
+ "submission": submission,
192
+ "auto_emitted": auto_emitted,
193
+ "submission_coerced": coerced,
194
+ "tool_calls": tool_calls,
195
+ "turns": turns,
196
+ "errors": errors,
197
+ "usage": {
198
+ "prompt_tokens": usage["input_tokens"]
199
+ + usage["cache_read_input_tokens"]
200
+ + usage["cache_creation_input_tokens"],
201
+ "completion_tokens": usage["output_tokens"],
202
+ **usage,
203
+ "reported_cost_usd": round(cost, 8) if cost is not None else None,
204
+ "latency_seconds": round(time.perf_counter() - started, 3),
205
+ },
206
+ "resolved_models": [config.model],
207
+ "transcript": transcript,
208
+ }
openenv/retroenv_openenv/agent_reference.py ADDED
@@ -0,0 +1,587 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """A scripted chemist that replays a task's reference routes through a RetroEnv server.
2
+
3
+ This generates SFT trajectories. The expert reads the private task, so it knows
4
+ the patent route, but it acts through ``agent.run_episode`` like any model: every
5
+ tool result and the reward come from the server, and the stored episode has the
6
+ same format as an evaluation episode.
7
+
8
+ It plans the way a chemist does:
9
+
10
+ 1. Look before cutting. Most episodes start by inspecting the target and
11
+ searching the training precedents for close analogues.
12
+ 2. Propose disconnections in order. Sometimes the first is a plausible cut the
13
+ patent did not use (``retroenv.disconnections`` ranks them by reliability and
14
+ convergence); ``validate_disconnection`` rejects it, and the expert moves on to
15
+ the next candidate.
16
+ 3. Validate the patent's cut and look up every new piece by exact stock search. A
17
+ piece the stock lacks gets its own disconnection; one the stock holds stays a
18
+ leaf, even where the patent made it.
19
+ 4. Emit the trees, naming each reaction's family, reagent roles and evidence.
20
+
21
+ Text and metadata cite only tool results and chemistry read from the structures.
22
+ A precedent is cited only when its reaction type matches the cut. The task's own
23
+ patent, reaction IDs and reagents are never written: the student cannot observe
24
+ them and would learn to invent them. Choices are seeded by the episode ID, so a
25
+ rerun reproduces an episode and another attempt explores differently.
26
+ """
27
+
28
+ from __future__ import annotations
29
+
30
+ import hashlib
31
+ import json
32
+ from dataclasses import dataclass, field
33
+ from pathlib import Path
34
+ from types import SimpleNamespace
35
+ from typing import Any
36
+
37
+ from retroenv.benchmark import load_benchmark
38
+ from retroenv.chemistry import canonicalize_smiles
39
+ from retroenv.disconnections import (
40
+ UNCERTAIN,
41
+ Disconnection,
42
+ describe,
43
+ reaction_phrase,
44
+ role,
45
+ step_family,
46
+ strategic_disconnections,
47
+ )
48
+ from retroenv.models import RetroTask
49
+ from retroenv.reactions import ReactionLibrary
50
+ from retroenv.verifier import compliant_references
51
+
52
+ from . import agent
53
+ from .client import RetroEnvClient
54
+
55
+ MODEL = "reference-expert"
56
+ # Headroom under the server's 32 tool calls and the loop's 16 turns.
57
+ CALL_BUDGET = 30
58
+ TURN_BUDGET = 14
59
+
60
+
61
+ @dataclass(frozen=True)
62
+ class _Function:
63
+ name: str
64
+ arguments: str
65
+
66
+
67
+ @dataclass(frozen=True)
68
+ class _ToolCall:
69
+ """The parts of an OpenAI tool call that ``agent.run_episode`` reads."""
70
+
71
+ id: str
72
+ function: _Function
73
+
74
+ def model_dump(self, exclude_none: bool = True) -> dict[str, Any]:
75
+ return {
76
+ "id": self.id,
77
+ "type": "function",
78
+ "function": {"name": self.function.name, "arguments": self.function.arguments},
79
+ }
80
+
81
+
82
+ def _routes(task: RetroTask, stock: frozenset[str]) -> list[dict[str, tuple[str, ...]]]:
83
+ """One product -> reactants map per submitted route, one route per distinct first cut.
84
+
85
+ Only known routes that satisfy the task's depth, stock and class constraints are replayed."""
86
+ target = canonicalize_smiles(task.target_smiles)
87
+ routes: list[dict[str, tuple[str, ...]]] = []
88
+ first_cuts: set[tuple[str, ...]] = set()
89
+ available = stock - frozenset(canonicalize_smiles(s) for s in task.constraints.excluded_stock)
90
+ for route in compliant_references(task, available, frozenset(task.constraints.forbidden_classes)):
91
+ steps = {canonicalize_smiles(step.product): tuple(step.reactants) for step in route.steps}
92
+ first = tuple(sorted(steps.get(target, ())))
93
+ if not first or first in first_cuts:
94
+ continue
95
+ first_cuts.add(first)
96
+ routes.append(steps)
97
+ if len(routes) == task.max_routes:
98
+ break
99
+ return routes
100
+
101
+
102
+ @dataclass
103
+ class _Observed:
104
+ """What the conversation so far has shown the expert."""
105
+
106
+ stock: dict[str, bool] = field(default_factory=dict)
107
+ validated: dict[tuple, bool] = field(default_factory=dict)
108
+ inspect: dict[str, Any] | None = None
109
+ precedents: list[dict[str, Any]] | None = None
110
+ researched: bool = False
111
+ last: list[tuple[str, dict[str, Any], dict[str, Any]]] = field(default_factory=list)
112
+
113
+
114
+ def _observe(messages: list[dict[str, Any]]) -> _Observed:
115
+ seen = _Observed()
116
+ calls: dict[str, tuple[str, dict[str, Any]]] = {}
117
+ last_assistant = max((i for i, m in enumerate(messages) if m.get("role") == "assistant"), default=-1)
118
+ for message in messages:
119
+ for call in message.get("tool_calls") or []:
120
+ calls[call["id"]] = (call["function"]["name"], json.loads(call["function"]["arguments"]))
121
+ for index, message in enumerate(messages):
122
+ if message.get("role") != "tool" or message.get("tool_call_id") not in calls:
123
+ continue
124
+ name, arguments = calls[message["tool_call_id"]]
125
+ result = json.loads(message["content"])
126
+ if name == "stock_retrieve":
127
+ seen.stock[canonicalize_smiles(arguments["query"])] = bool(result.get("results"))
128
+ elif name == "validate_disconnection":
129
+ seen.validated[(arguments["product_smiles"], tuple(arguments["reactants"]))] = bool(result.get("supported"))
130
+ elif name == "inspect_molecule":
131
+ seen.inspect, seen.researched = result, True
132
+ elif name == "reaction_precedent_search":
133
+ seen.precedents, seen.researched = result.get("results") or [], True
134
+ if index > last_assistant:
135
+ seen.last.append((name, arguments, result))
136
+ return seen
137
+
138
+
139
+ class ReferenceExpert:
140
+ """OpenAI-compatible stand-in for a model whose next turn is computed from the conversation.
141
+
142
+ ``research`` and ``alternatives`` override the seeded choices (tests use them):
143
+ whether to look before cutting, and how many plausible wrong cuts to try at the target.
144
+ """
145
+
146
+ def __init__(
147
+ self,
148
+ task: RetroTask,
149
+ library: ReactionLibrary,
150
+ stock: frozenset[str],
151
+ seed: str | None = None,
152
+ *,
153
+ research: bool | None = None,
154
+ alternatives: int | None = None,
155
+ ):
156
+ self.task = task
157
+ self.seed = seed or task.task_id
158
+ self.target = canonicalize_smiles(task.target_smiles)
159
+ self.routes = _routes(task, stock)
160
+ self.library = library
161
+ self.research = self._u("research") < 0.75 if research is None else research
162
+ self.inspect = self.research and self._u("inspect") < 0.6
163
+ self.precedent = self.research and (not self.inspect or self._u("precedent") < 0.85)
164
+ self.alternatives = self._plan_alternatives(alternatives)
165
+ self._fit_budget()
166
+ self.chat = SimpleNamespace(completions=SimpleNamespace(create=self.create))
167
+
168
+ # --- planning -------------------------------------------------------------
169
+
170
+ def _u(self, key: str) -> float:
171
+ return int(hashlib.sha256(f"{self.seed}:{key}".encode()).hexdigest()[:12], 16) / 16**12
172
+
173
+ def _pick(self, options: list[str], key: str) -> str:
174
+ return options[int(self._u(key) * len(options))]
175
+
176
+ def _plan_alternatives(self, forced: int | None) -> dict[str, list[Disconnection]]:
177
+ """Plausible cuts the patent did not make, to try first on the first route's products."""
178
+ if not self.routes:
179
+ return {}
180
+ references: dict[str, set[tuple[str, ...]]] = {}
181
+ for steps in self.routes:
182
+ for product, reactants in steps.items():
183
+ references.setdefault(product, set()).add(tuple(sorted(reactants)))
184
+ plan: dict[str, list[Disconnection]] = {}
185
+ for product in self.routes[0]:
186
+ if forced is not None:
187
+ count = forced if product == self.target else 0
188
+ elif product == self.target:
189
+ u = self._u(f"alternatives:{product}")
190
+ count = 2 if u < 0.10 else 1 if u < 0.45 else 0
191
+ else:
192
+ count = 1 if self._u(f"alternatives:{product}") < 0.15 else 0
193
+ if not count:
194
+ continue
195
+ candidates = [
196
+ d
197
+ for d in strategic_disconnections(product)
198
+ if tuple(sorted(d.reactants)) not in references[product]
199
+ # A cut the train-visible library supports would be accepted, so it is no alternative.
200
+ and not self.library.support(product, list(d.reactants)).supported
201
+ ]
202
+ if candidates[:count]:
203
+ plan[product] = candidates[:count]
204
+ return plan
205
+
206
+ def _cost(self) -> tuple[int, int]:
207
+ """Upper bounds on tool calls and turns, as if every intermediate needed its own cut."""
208
+ calls = turns = 1 # the emit turn
209
+ if self.research:
210
+ calls += self.inspect + self.precedent
211
+ turns += 1
212
+ looked: set[str] = set()
213
+ for steps in self.routes:
214
+ for reactants in steps.values():
215
+ new = [r for r in reactants if r not in looked]
216
+ looked.update(new)
217
+ calls += 1 + len(new)
218
+ turns += 1
219
+ for options in self.alternatives.values():
220
+ for option in options:
221
+ calls += 1 + len(option.reactants)
222
+ turns += 1
223
+ return calls, turns
224
+
225
+ def _fit_budget(self) -> None:
226
+ while self._cost()[0] > CALL_BUDGET or self._cost()[1] > TURN_BUDGET:
227
+ if self.alternatives:
228
+ # Drop the deepest product's alternatives first, keep the target's longest.
229
+ product = next(p for p in reversed(list(self.routes[0])) if p in self.alternatives)
230
+ del self.alternatives[product]
231
+ elif self.research:
232
+ self.research = self.inspect = self.precedent = False
233
+ else:
234
+ return
235
+
236
+ # --- the conversation -------------------------------------------------------
237
+
238
+ def _expands(self, smiles: str, steps: dict[str, tuple[str, ...]], stock: dict[str, bool]) -> bool:
239
+ # The target is never in stock (the task builder drops those); anything
240
+ # else is expanded only after a lookup came back empty.
241
+ return smiles in steps and (smiles == self.target or stock.get(smiles) is False)
242
+
243
+ def _next(self, seen: _Observed, validate: bool):
244
+ """The next cut to propose, breadth-first per route: (route index, product, reactants, alternative)."""
245
+ for route_index, steps in enumerate(self.routes):
246
+ queue = [self.target]
247
+ while queue:
248
+ product = queue.pop(0)
249
+ if not self._expands(product, steps, seen.stock):
250
+ continue
251
+ reactants = steps[product]
252
+ if validate:
253
+ for option in self.alternatives.get(product, []) if route_index == 0 else []:
254
+ if (product, option.reactants) not in seen.validated:
255
+ return route_index, product, option.reactants, option
256
+ if (product, reactants) not in seen.validated:
257
+ return route_index, product, reactants, None
258
+ elif not all(r in seen.stock for r in reactants):
259
+ return route_index, product, reactants, None
260
+ queue.extend(reactants)
261
+ return None
262
+
263
+ def _analogue(self, seen: _Observed, family: str, phrase: str) -> dict[str, Any] | None:
264
+ """A precedent made by the same, confidently named reaction, if the search returned one."""
265
+ if phrase in UNCERTAIN:
266
+ return None
267
+ for result in seen.precedents or []:
268
+ theirs = step_family(result["reactants"], result["product_smiles"])
269
+ if theirs == family and reaction_phrase(theirs, result["reactants"], result["product_smiles"]) == phrase:
270
+ return result
271
+ return None
272
+
273
+ def _summary(self, seen: _Observed) -> str:
274
+ """One or two sentences on what the previous turn's tool results showed."""
275
+ parts: list[str] = []
276
+ for name, _, result in seen.last:
277
+ if name == "inspect_molecule" and result.get("valid", True):
278
+ rings, centres = result.get("rings", 0), result.get("chiral_centres", 0)
279
+ stereo = "" if not centres else ", one stereocentre" if centres == 1 else f", {centres} stereocentres"
280
+ parts.append(f"{result.get('formula')}, {rings} ring{'' if rings == 1 else 's'}{stereo}.")
281
+ elif name == "reaction_precedent_search":
282
+ results = result.get("results") or []
283
+ if not results:
284
+ parts.append("No close precedent among the training reactions.")
285
+ continue
286
+ best = results[0]
287
+ family = step_family(best["reactants"], best["product_smiles"])
288
+ phrase = reaction_phrase(family, best["reactants"], best["product_smiles"])
289
+ literature = best.get("literature") or []
290
+ where = f"{literature[0]['identifier']}, " if literature else ""
291
+ made = "" if phrase in UNCERTAIN else f" was made by {phrase}"
292
+ parts.append(f"Closest training precedent ({where}Tanimoto {best['similarity']:.2f}){made}.")
293
+ verdicts = [result for name, _, result in seen.last if name == "validate_disconnection"]
294
+ lookups = [
295
+ (canonicalize_smiles(args["query"]), bool(result.get("results")))
296
+ for name, args, result in seen.last
297
+ if name == "stock_retrieve"
298
+ ]
299
+ missing = [smiles for smiles, found in lookups if not found]
300
+ if verdicts and not verdicts[0].get("supported"):
301
+ parts.append(
302
+ self._pick(
303
+ [
304
+ "No support for that cut.",
305
+ "That cut has no supporting evidence.",
306
+ "The evidence does not support that cut.",
307
+ ],
308
+ f"reject:{len(seen.validated)}",
309
+ )
310
+ )
311
+ if missing:
312
+ parts.append(
313
+ "One of its pieces is not in stock either."
314
+ if len(missing) == 1
315
+ else "Its pieces are not in stock either."
316
+ )
317
+ return " ".join(parts)
318
+ if verdicts:
319
+ parts.append(
320
+ self._pick(["Supported.", "The cut is supported.", "That cut holds."], f"accept:{len(seen.validated)}")
321
+ )
322
+ if lookups:
323
+ if not missing:
324
+ parts.append(
325
+ "Both pieces are in stock."
326
+ if len(lookups) == 2
327
+ else "It is in stock."
328
+ if len(lookups) == 1
329
+ else "All pieces are in stock."
330
+ )
331
+ elif len(missing) == len(lookups):
332
+ parts.append(f"Not in stock: {', '.join(missing)}.")
333
+ else:
334
+ # Name what is in stock by the role it plays in the cut just checked.
335
+ cut = next(
336
+ (
337
+ (args["product_smiles"], args["reactants"])
338
+ for name, args, _ in seen.last
339
+ if name == "validate_disconnection"
340
+ ),
341
+ None,
342
+ )
343
+ family = step_family(cut[1], cut[0]) if cut else None
344
+ found = [f"the {role(smiles, family)}" for smiles, ok in lookups if ok]
345
+ parts.append(f"In stock: {', '.join(found)}. Not in stock: {', '.join(missing)}.")
346
+ return " ".join(parts)
347
+
348
+ def _proposal(
349
+ self,
350
+ seen: _Observed,
351
+ route_index: int,
352
+ product: str,
353
+ reactants: tuple[str, ...],
354
+ option: Disconnection | None,
355
+ validate: bool,
356
+ new: list[str],
357
+ ) -> str:
358
+ family = option.family if option else step_family(reactants, product)
359
+ phrase = reaction_phrase(family, reactants, product)
360
+ what = describe(family, reactants, product)
361
+ tried = [key for key, ok in seen.validated.items() if key[0] == product and not ok]
362
+ key = f"{product}:{len(seen.validated)}"
363
+ previous = (
364
+ next((o for o in self.alternatives.get(product, []) if (product, o.reactants) == tried[-1]), None)
365
+ if tried
366
+ else None
367
+ )
368
+ # Same bond label and a shared fragment: the two proposals cut the same bond.
369
+ if (
370
+ option is not None
371
+ and previous is not None
372
+ and previous.bond == option.bond
373
+ and set(previous.reactants) & set(option.reactants)
374
+ ):
375
+ lead = f"Or make the same bond by {what}."
376
+ elif option is not None and tried:
377
+ lead = f"Another candidate is the {option.bond}: {what}."
378
+ elif option is not None:
379
+ lead = self._pick(
380
+ [
381
+ f"Try the {option.bond} first: {what}.",
382
+ f"One candidate is the {option.bond}: {what}.",
383
+ f"Start with the {option.bond}: {what}.",
384
+ ],
385
+ key,
386
+ )
387
+ elif product == self.target and route_index > 0:
388
+ lead = f"A second route needs a different first cut: {what}."
389
+ elif tried:
390
+ lead = self._pick([f"Next candidate: {what}.", f"Try {what} instead.", f"Fall back to {what}."], key)
391
+ elif product == self.target:
392
+ lead = self._pick(
393
+ [
394
+ f"Disconnect the target by {what}.",
395
+ f"The target reads as the product of {what}.",
396
+ f"The key disconnection is {what}.",
397
+ ],
398
+ key,
399
+ )
400
+ else:
401
+ mentioned = [
402
+ smiles
403
+ for name, args, result in seen.last
404
+ if name == "stock_retrieve"
405
+ for smiles in [canonicalize_smiles(args["query"])]
406
+ if not result.get("results")
407
+ ]
408
+ if mentioned == [product]:
409
+ lead = self._pick([f"It needs its own disconnection: {what}.", f"Disconnect it by {what}."], key)
410
+ else:
411
+ lead = f"Disconnect {product} by {what}."
412
+ if option is None and product == self.target and route_index == 0 and self._analogue(seen, family, phrase):
413
+ lead += " That matches the closest precedent."
414
+ if not validate:
415
+ tail = "Look up the new pieces." if new else ""
416
+ elif new:
417
+ tail = self._pick(
418
+ [
419
+ "Check the cut and look up the new pieces.",
420
+ "Validate it and check the stock.",
421
+ "Check it against the evidence and look up each piece.",
422
+ ],
423
+ f"tail:{key}",
424
+ )
425
+ else:
426
+ tail = "Check the cut; its pieces were already looked up."
427
+ return f"{lead} {tail}".strip()
428
+
429
+ def _tree(self, smiles: str, steps: dict[str, tuple[str, ...]], seen: _Observed) -> dict[str, Any]:
430
+ if not self._expands(smiles, steps, seen.stock):
431
+ return {"type": "mol", "smiles": smiles, "in_stock": seen.stock.get(smiles, False), "children": []}
432
+ reactants = steps[smiles]
433
+ family = step_family(reactants, smiles)
434
+ phrase = reaction_phrase(family, reactants, smiles)
435
+ supported = seen.validated.get((smiles, reactants))
436
+ analogue = self._analogue(seen, family, phrase) if smiles == self.target else None
437
+ what = describe(family, reactants, smiles)
438
+ explanation = f"{what[0].upper()}{what[1:]}."
439
+ if supported:
440
+ explanation += " Supported by validate_disconnection."
441
+ if analogue:
442
+ literature = analogue.get("literature") or []
443
+ where = f" {literature[0]['identifier']}" if literature else ""
444
+ explanation += (
445
+ f" Training precedent{where} (Tanimoto {analogue['similarity']:.2f}) uses the same reaction type."
446
+ )
447
+ metadata = {
448
+ "explanation": explanation,
449
+ "reaction_class": family,
450
+ "confidence": 0.9 if supported and analogue else 0.85 if supported else 0.6,
451
+ "literature": list(analogue.get("literature") or [])[:1] if analogue else [],
452
+ "precursor_roles": {reactant: role(reactant, family) for reactant in reactants},
453
+ }
454
+ return {
455
+ "type": "mol",
456
+ "smiles": smiles,
457
+ "in_stock": False,
458
+ "children": [
459
+ {
460
+ "type": "reaction",
461
+ "is_reaction": True,
462
+ "metadata": metadata,
463
+ "children": [self._tree(reactant, steps, seen) for reactant in reactants],
464
+ }
465
+ ],
466
+ }
467
+
468
+ def _emit(self, seen: _Observed) -> tuple[str, list]:
469
+ routes = [self._tree(self.target, steps, seen) for steps in self.routes]
470
+
471
+ def leaves(node: dict[str, Any]) -> list[dict[str, Any]]:
472
+ if not node["children"]:
473
+ return [node]
474
+ return [leaf for child in node["children"][0]["children"] for leaf in leaves(child)]
475
+
476
+ def forward(node: dict[str, Any]) -> list[str]:
477
+ """Reaction names in the order a chemist would run them: deepest first."""
478
+ if not node["children"]:
479
+ return []
480
+ reaction = node["children"][0]
481
+ earlier = [phrase for child in reaction["children"] for phrase in forward(child)]
482
+ reactants = [child["smiles"] for child in reaction["children"]]
483
+ return earlier + [reaction_phrase(reaction["metadata"]["reaction_class"], reactants, node["smiles"])]
484
+
485
+ missing = sum(not leaf["in_stock"] for route in routes for leaf in leaves(route))
486
+ steps = forward(routes[0])
487
+ if missing:
488
+ lead = f"{missing} leaf molecule(s) are still not in stock; submitting the best route found."
489
+ else:
490
+ lead = self._pick(["The route is complete.", "Every leaf is now bought.", "That closes the route."], "done")
491
+ plan = f" Forward: {' → '.join(steps)}." if len(steps) > 1 else ""
492
+ close = (
493
+ " Submitting both routes."
494
+ if len(routes) == 2
495
+ else f" Submitting {len(routes)} routes."
496
+ if len(routes) > 2
497
+ else ""
498
+ )
499
+ content = " ".join(part for part in (self._summary(seen), f"{lead}{plan}{close}") if part)
500
+ return content, [("emit_routes", {"submission": {"routes": routes}})]
501
+
502
+ def _turn(self, messages: list[dict[str, Any]], exposed: set[str]) -> tuple[str, list]:
503
+ seen = _observe(messages)
504
+ if exposed == {"emit_routes"}:
505
+ return self._emit(seen)
506
+ validate = "validate_disconnection" in exposed
507
+ if self.research and not seen.researched:
508
+ calls: list[tuple[str, dict[str, Any]]] = []
509
+ if self.inspect and "inspect_molecule" in exposed:
510
+ calls.append(("inspect_molecule", {"smiles": self.target}))
511
+ if self.precedent and "reaction_precedent_search" in exposed:
512
+ calls.append(("reaction_precedent_search", {"product_smiles": self.target, "limit": 3}))
513
+ if calls:
514
+ names = {name for name, _ in calls}
515
+ if names == {"inspect_molecule"}:
516
+ text = "Look at the target's structure before choosing a cut."
517
+ elif names == {"reaction_precedent_search"}:
518
+ text = self._pick(
519
+ [
520
+ "Search the training reactions for close analogues first.",
521
+ "First look for precedents with similar products.",
522
+ ],
523
+ "research",
524
+ )
525
+ else:
526
+ text = self._pick(
527
+ [
528
+ "Look at the target and its closest training precedents first.",
529
+ "Start by inspecting the target and searching for analogous reactions.",
530
+ "Before cutting anything, check the structure and look for precedents.",
531
+ ],
532
+ "research",
533
+ )
534
+ return text, calls
535
+ pending = self._next(seen, validate)
536
+ if pending is None:
537
+ return self._emit(seen)
538
+ route_index, product, reactants, option = pending
539
+ new = [reactant for reactant in dict.fromkeys(reactants) if reactant not in seen.stock]
540
+ calls = []
541
+ if validate:
542
+ calls.append(("validate_disconnection", {"product_smiles": product, "reactants": list(reactants)}))
543
+ calls.extend(("stock_retrieve", {"query": reactant, "mode": "exact", "limit": 1}) for reactant in new)
544
+ text = " ".join(
545
+ part
546
+ for part in (
547
+ self._summary(seen),
548
+ self._proposal(seen, route_index, product, reactants, option, validate, new),
549
+ )
550
+ if part
551
+ )
552
+ return text, calls
553
+
554
+ def create(self, *, messages: list[dict[str, Any]], tools: list[dict[str, Any]], **_: Any) -> Any:
555
+ exposed = {tool["function"]["name"] for tool in tools}
556
+ content, calls = self._turn(messages, exposed)
557
+ turn = sum(message["role"] == "assistant" for message in messages) + 1
558
+ tool_calls = [
559
+ _ToolCall(f"call_{turn}_{k}", _Function(name, json.dumps(arguments)))
560
+ for k, (name, arguments) in enumerate(calls)
561
+ ]
562
+ message = SimpleNamespace(content=content, tool_calls=tool_calls)
563
+ usage = SimpleNamespace(prompt_tokens=0, completion_tokens=0, model_extra={})
564
+ return SimpleNamespace(choices=[SimpleNamespace(message=message)], model=MODEL, usage=usage)
565
+
566
+
567
+ class ReferenceTasks:
568
+ """Private tasks by ID, so ``run_episode`` can build each episode's expert."""
569
+
570
+ def __init__(self, benchmark_dir: str | Path):
571
+ self.benchmark = load_benchmark(str(Path(benchmark_dir).resolve()))
572
+ self.tasks = {task.task_id: task for task in self.benchmark.store.iter_all()}
573
+
574
+ def expert(self, task_id: str, seed: str | None = None) -> ReferenceExpert:
575
+ try:
576
+ task = self.tasks[task_id]
577
+ stock = self.benchmark.store.stock(task.stock_id)
578
+ return ReferenceExpert(task, self.benchmark.tool_library, stock, seed)
579
+ except KeyError:
580
+ raise KeyError(f"{task_id} is not in the private tasks given to the reference expert") from None
581
+
582
+
583
+ def run_episode(
584
+ llm: ReferenceTasks, env: RetroEnvClient, opening: dict[str, Any], config: agent.AgentConfig
585
+ ) -> dict[str, Any]:
586
+ # The episode ID differs per attempt, so a second attempt explores differently.
587
+ return agent.run_episode(llm.expert(opening["task_id"], opening.get("episode_id")), env, opening, config)
openenv/retroenv_openenv/agent_responses.py ADDED
@@ -0,0 +1,167 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """OpenAI Responses API agent loop against a RetroEnv server.
2
+
3
+ GPT-5.6 models reject function tools with reasoning on /v1/chat/completions,
4
+ so they run here. Same protocol and result shape as ``agent.run_episode``. The
5
+ history is sent back each turn (``store=False``) with encrypted reasoning items
6
+ included, so no conversation state is kept at OpenAI.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import json
12
+ import time
13
+ from dataclasses import dataclass
14
+ from typing import Any
15
+
16
+ from .agent import SYSTEM_PROMPT, close_episode, normalize_arguments
17
+ from .client import RetroEnvClient
18
+
19
+
20
+ @dataclass
21
+ class ResponsesConfig:
22
+ model: str
23
+ max_turns: int = 16
24
+ max_output_tokens: int = 16000
25
+ reasoning_effort: str | None = None # None keeps the model default
26
+ max_empty_turns: int = 2
27
+
28
+
29
+ def run_episode(llm: Any, env: RetroEnvClient, opening: dict[str, Any], config: ResponsesConfig) -> dict[str, Any]:
30
+ tools = [
31
+ {
32
+ "type": "function",
33
+ "name": tool["function"]["name"],
34
+ "description": tool["function"]["description"],
35
+ "parameters": tool["function"]["parameters"],
36
+ "strict": False,
37
+ }
38
+ for tool in env.openai_tools()
39
+ ]
40
+ emit_tool = [tool for tool in tools if tool["name"] == "emit_routes"]
41
+ allowed = {tool["name"] for tool in tools}
42
+ items: list[dict[str, Any]] = [
43
+ {"role": "developer", "content": SYSTEM_PROMPT.format(max_turns=config.max_turns)},
44
+ {"role": "user", "content": opening["prompt"]},
45
+ ]
46
+ transcript: list[dict[str, Any]] = [{"role": "user", "content": opening["prompt"]}]
47
+ errors: list[str] = []
48
+ usage = {"prompt_tokens": 0, "completion_tokens": 0, "cached_tokens": 0, "reasoning_tokens": 0}
49
+ submission: Any = None
50
+ final: dict[str, Any] | None = None
51
+ tool_calls = 0
52
+ empty_turns = 0
53
+ force_terminal = False
54
+ coerced = False
55
+ turns = 0
56
+ started = time.perf_counter()
57
+
58
+ for turn_index in range(config.max_turns):
59
+ terminal_turn = force_terminal or turn_index == config.max_turns - 1
60
+ request: dict[str, Any] = {
61
+ "model": config.model,
62
+ "input": items,
63
+ "tools": emit_tool if terminal_turn else tools,
64
+ "tool_choice": "required",
65
+ "parallel_tool_calls": False,
66
+ "max_output_tokens": config.max_output_tokens,
67
+ "store": False,
68
+ "include": ["reasoning.encrypted_content"],
69
+ }
70
+ if config.reasoning_effort:
71
+ request["reasoning"] = {"effort": config.reasoning_effort}
72
+ try:
73
+ response = llm.responses.create(**request)
74
+ except Exception as exc: # provider errors end the episode; it is still scored
75
+ errors.append(f"API error: {type(exc).__name__}: {str(exc)[:500]}")
76
+ break
77
+ turns += 1
78
+ if response.usage:
79
+ usage["prompt_tokens"] += int(response.usage.input_tokens or 0)
80
+ usage["completion_tokens"] += int(response.usage.output_tokens or 0)
81
+ details = response.usage.input_tokens_details
82
+ usage["cached_tokens"] += int(getattr(details, "cached_tokens", 0) or 0)
83
+ out_details = response.usage.output_tokens_details
84
+ usage["reasoning_tokens"] += int(getattr(out_details, "reasoning_tokens", 0) or 0)
85
+ output = [item.model_dump(exclude_none=True) for item in response.output]
86
+ items.extend(output)
87
+ transcript.append(
88
+ {
89
+ "role": "assistant",
90
+ "content": [{k: v for k, v in item.items() if k != "encrypted_content"} for item in output],
91
+ }
92
+ )
93
+
94
+ calls = [item for item in response.output if item.type == "function_call"]
95
+ if not calls:
96
+ empty_turns += 1
97
+ text = (response.output_text or "")[:200]
98
+ errors.append(f"no tool call on turn {turn_index + 1}: {text}")
99
+ if terminal_turn:
100
+ break
101
+ force_terminal = empty_turns >= config.max_empty_turns
102
+ nudge = (
103
+ "No tool call was made. Call one of the available tools now; on your final "
104
+ "turn you must call emit_routes."
105
+ )
106
+ items.append({"role": "user", "content": nudge})
107
+ transcript.append({"role": "user", "content": nudge})
108
+ continue
109
+
110
+ for call in calls:
111
+ try:
112
+ arguments = json.loads(call.arguments or "{}")
113
+ if not isinstance(arguments, dict):
114
+ raise ValueError("arguments must be a JSON object")
115
+ except ValueError as exc:
116
+ result: Any = {"error": f"invalid tool arguments: {exc}"}
117
+ errors.append(result["error"])
118
+ else:
119
+ arguments, was_coerced = normalize_arguments(call.name, arguments)
120
+ coerced = coerced or was_coerced
121
+ if call.name not in allowed:
122
+ result = {"error": f"unknown tool {call.name!r}"}
123
+ else:
124
+ outcome = env.call(call.name, arguments)
125
+ tool_calls += 1
126
+ result = outcome.result if outcome.error is None else {"error": outcome.error}
127
+ if call.name == "emit_routes":
128
+ submission = arguments.get("submission")
129
+ if outcome.done and outcome.reward is not None:
130
+ score = result.get("score") if isinstance(result, dict) else None
131
+ final = {**(score or {}), "reward": float(outcome.reward)}
132
+ payload = result if isinstance(result, dict) else {"result": result}
133
+ text = json.dumps({**payload, "model_turns_remaining": config.max_turns - turns}, sort_keys=True)
134
+ items.append({"type": "function_call_output", "call_id": call.call_id, "output": text})
135
+ transcript.append({"role": "tool", "name": call.name, "content": text})
136
+ if final is not None:
137
+ break
138
+
139
+ auto_emitted = False
140
+ if final is None:
141
+ final, fallback = close_episode(env)
142
+ auto_emitted = True
143
+ if fallback is not None:
144
+ submission = fallback
145
+
146
+ return {
147
+ "reward": final.get("reward", 0.0),
148
+ "valid": bool(final.get("valid", False)),
149
+ "exact_match": bool((final.get("metrics") or {}).get("reference_match", False)),
150
+ "components": final.get("components", {}),
151
+ "hard_failures": final.get("hard_failures", []),
152
+ "verification_tier": final.get("verification_tier"),
153
+ "route_count": (final.get("metrics") or {}).get("route_count", 0),
154
+ "submission": submission,
155
+ "auto_emitted": auto_emitted,
156
+ "submission_coerced": coerced,
157
+ "tool_calls": tool_calls,
158
+ "turns": turns,
159
+ "errors": errors,
160
+ "usage": {
161
+ **usage,
162
+ "reported_cost_usd": None,
163
+ "latency_seconds": round(time.perf_counter() - started, 3),
164
+ },
165
+ "resolved_models": [config.model],
166
+ "transcript": transcript,
167
+ }
openenv/retroenv_openenv/client.py ADDED
@@ -0,0 +1,260 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Clients for a running RetroEnv server (local or a Space).
2
+
3
+ ``RetroEnvClient`` holds one WebSocket session, so one episode at a time; open
4
+ one client per concurrent episode. ``RemoteRetroRouteEnv`` exposes the same
5
+ tools as plain methods for TRL's ``environment_factory``, mirroring the
6
+ in-process ``retroenv.training.RetroRouteTrainingEnv``.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import json
12
+ from dataclasses import dataclass
13
+ from typing import Any
14
+
15
+ import httpx
16
+ from openenv.core.env_server.mcp_types import CallToolAction
17
+ from openenv.core.mcp_client import MCPToolClient
18
+
19
+ from .config import ENV_NAME
20
+
21
+
22
+ @dataclass
23
+ class ToolOutcome:
24
+ name: str
25
+ result: Any
26
+ done: bool
27
+ reward: float | None
28
+ error: str | None = None
29
+
30
+
31
+ def _tool_payload(result: Any) -> Any:
32
+ """The tool's return value from a CallToolResult (object or JSON dict)."""
33
+ if result is None:
34
+ return None
35
+ data = getattr(result, "data", None)
36
+ if data is not None:
37
+ return data
38
+ if isinstance(result, dict):
39
+ if result.get("data") is not None:
40
+ return result["data"]
41
+ structured = result.get("structured_content") or result.get("structuredContent")
42
+ if isinstance(structured, dict) and "result" in structured:
43
+ return structured["result"]
44
+ for block in result.get("content") or []:
45
+ if block.get("type") == "text":
46
+ try:
47
+ return json.loads(block["text"])
48
+ except (TypeError, ValueError):
49
+ return block["text"]
50
+ return result
51
+
52
+
53
+ class RetroEnvClient:
54
+ def __init__(self, base_url: str, message_timeout_s: float = 300.0):
55
+ self.base_url = base_url.rstrip("/")
56
+ self._env = MCPToolClient(self.base_url, message_timeout_s=message_timeout_s).sync()
57
+ self._tools: list[dict[str, Any]] | None = None
58
+
59
+ # --- Task API over HTTP ----------------------------------------------
60
+
61
+ def _post(self, route: str, payload: dict[str, Any]) -> Any:
62
+ response = httpx.post(f"{self.base_url}/{ENV_NAME}/{route}", json=payload, timeout=600)
63
+ response.raise_for_status()
64
+ return response.json()
65
+
66
+ def splits(self) -> list[dict[str, Any]]:
67
+ response = httpx.get(f"{self.base_url}/{ENV_NAME}/splits", timeout=600)
68
+ response.raise_for_status()
69
+ return response.json()
70
+
71
+ def num_tasks(self, split: str) -> int:
72
+ value = self._post("num_tasks", {"split": split})
73
+ return int(value["num_tasks"] if isinstance(value, dict) else value)
74
+
75
+ def task(self, split: str, index: int) -> dict[str, Any]:
76
+ value = self._post("task", {"split": split, "index": index})
77
+ return value.get("task", value) if isinstance(value, dict) else value
78
+
79
+ def tasks(self, split: str, start: int | None = None, stop: int | None = None) -> list[dict[str, Any]]:
80
+ value = self._post("task_range", {"split": split, "start": start, "stop": stop})
81
+ return value.get("tasks", value) if isinstance(value, dict) else value
82
+
83
+ # --- Episode ------------------------------------------------------------
84
+
85
+ def reset(
86
+ self, split: str, index: int | None = None, task_id: str | None = None, episode_id: str | None = None
87
+ ) -> dict[str, Any]:
88
+ kwargs: dict[str, Any] = {"split": split}
89
+ if index is not None:
90
+ kwargs["index"] = index
91
+ if task_id is not None:
92
+ kwargs["task_id"] = task_id
93
+ if episode_id is not None:
94
+ kwargs["episode_id"] = episode_id
95
+ result = self._env.reset(**kwargs)
96
+ return dict(result.observation.metadata or {})
97
+
98
+ def openai_tools(self) -> list[dict[str, Any]]:
99
+ """Discovered MCP tools as OpenAI function definitions."""
100
+ if self._tools is None:
101
+ self._tools = [
102
+ {
103
+ "type": "function",
104
+ "function": {
105
+ "name": tool.name,
106
+ "description": tool.description or "",
107
+ "parameters": tool.input_schema,
108
+ },
109
+ }
110
+ for tool in self._env.list_tools()
111
+ ]
112
+ return self._tools
113
+
114
+ def call(self, name: str, arguments: dict[str, Any]) -> ToolOutcome:
115
+ step = self._env.step(CallToolAction(tool_name=name, arguments=arguments))
116
+ observation = step.observation
117
+ error = getattr(observation, "error", None)
118
+ return ToolOutcome(
119
+ name=name,
120
+ result=_tool_payload(getattr(observation, "result", None)),
121
+ done=bool(step.done),
122
+ reward=step.reward,
123
+ error=getattr(error, "message", None) if error else None,
124
+ )
125
+
126
+ def close(self) -> None:
127
+ self._env.close()
128
+
129
+ def __enter__(self) -> "RetroEnvClient":
130
+ return self
131
+
132
+ def __exit__(self, *exc: Any) -> None:
133
+ self.close()
134
+
135
+
136
+ class RemoteRetroRouteEnv:
137
+ """TRL ``environment_factory`` tools backed by a RetroEnv server.
138
+
139
+ Public methods other than ``reset`` and ``get_reward`` are agent tools.
140
+ Set ``RETROENV_SERVER`` and pass ``environment_factory=RemoteRetroRouteEnv``.
141
+ """
142
+
143
+ def __init__(self, server: str | None = None):
144
+ import os
145
+
146
+ self._client = RetroEnvClient(server or os.environ["RETROENV_SERVER"])
147
+ self._reward = 0.0
148
+
149
+ def reset(self, split: str = "train", index: int = 0, **_: Any) -> str:
150
+ self._reward = 0.0
151
+ return self._client.reset(split=split, index=index)["prompt"]
152
+
153
+ def get_reward(self) -> float:
154
+ return self._reward
155
+
156
+ def _close(self) -> None:
157
+ """Release the WebSocket session. TRL and the evaluators call this."""
158
+ self._client.close()
159
+
160
+ def _call(self, name: str, **arguments: Any) -> str:
161
+ outcome = self._client.call(name, arguments)
162
+ if outcome.reward is not None:
163
+ self._reward = float(outcome.reward)
164
+ payload = outcome.result if outcome.error is None else {"error": outcome.error}
165
+ return json.dumps(payload, sort_keys=True)
166
+
167
+ def inspect_molecule(self, smiles: str) -> str:
168
+ """Inspect a molecule with RDKit: formula, scaffold, rings, charge and stereo.
169
+
170
+ Args:
171
+ smiles: The molecule as SMILES.
172
+ """
173
+ return self._call("inspect_molecule", smiles=smiles)
174
+
175
+ def pubchem_lookup(self, query: str) -> str:
176
+ """Canonicalize a SMILES or look up the frozen molecule cache.
177
+
178
+ Args:
179
+ query: A SMILES, or a name or CAS number present in the cache.
180
+ """
181
+ return self._call("pubchem_lookup", query=query)
182
+
183
+ def stock_retrieve(self, query: str, mode: str = "auto", limit: int = 10) -> str:
184
+ """Search the purchasable stock: exact, inchikey, class, substructure or similarity.
185
+
186
+ Args:
187
+ query: SMILES, InChIKey, class name or SMARTS.
188
+ mode: One of auto, exact, inchikey, class, substructure, similarity.
189
+ limit: Maximum results, at most 20.
190
+ """
191
+ return self._call("stock_retrieve", query=query, mode=mode, limit=limit)
192
+
193
+ def reaction_precedent_search(self, product_smiles: str = "", reaction_class: str = "", limit: int = 10) -> str:
194
+ """Find analogous reactions from training-split records.
195
+
196
+ Args:
197
+ product_smiles: Product to find analogues for.
198
+ reaction_class: Optional reaction class filter.
199
+ limit: Maximum results, at most 20.
200
+ """
201
+ return self._call(
202
+ "reaction_precedent_search", product_smiles=product_smiles, reaction_class=reaction_class, limit=limit
203
+ )
204
+
205
+ def validate_disconnection(self, product_smiles: str, reactants: list[str]) -> str:
206
+ """Check one proposed cut against train-visible reactions and frequent templates.
207
+
208
+ Args:
209
+ product_smiles: The product of the step.
210
+ reactants: The proposed reactant SMILES.
211
+ """
212
+ return self._call("validate_disconnection", product_smiles=product_smiles, reactants=reactants)
213
+
214
+ def reaction_class_lookup(self, product_smiles: str, reactants: list[str]) -> str:
215
+ """Name the reaction class of a proposed cut.
216
+
217
+ Args:
218
+ product_smiles: The product of the step.
219
+ reactants: The proposed reactant SMILES.
220
+ """
221
+ return self._call("reaction_class_lookup", product_smiles=product_smiles, reactants=reactants)
222
+
223
+ def reaction_conditions_search(
224
+ self, product_smiles: str = "", reactants: list[str] | None = None, reaction_class: str = "", limit: int = 5
225
+ ) -> str:
226
+ """Find reported conditions for a cut or close precedents.
227
+
228
+ Args:
229
+ product_smiles: The product of the step.
230
+ reactants: The proposed reactant SMILES.
231
+ reaction_class: Optional reaction class.
232
+ limit: Maximum results, at most 20.
233
+ """
234
+ return self._call(
235
+ "reaction_conditions_search",
236
+ product_smiles=product_smiles,
237
+ reactants=reactants or [],
238
+ reaction_class=reaction_class,
239
+ limit=limit,
240
+ )
241
+
242
+ def search_literature(self, product_smiles: str = "", reaction_class: str = "", limit: int = 5) -> str:
243
+ """Search frozen citation metadata attached to training precedents.
244
+
245
+ Args:
246
+ product_smiles: Product to search for.
247
+ reaction_class: Optional reaction class filter.
248
+ limit: Maximum results, at most 20.
249
+ """
250
+ return self._call(
251
+ "search_literature", product_smiles=product_smiles, reaction_class=reaction_class, limit=limit
252
+ )
253
+
254
+ def emit_routes(self, submission: dict) -> str:
255
+ """Submit the final route trees and end the episode.
256
+
257
+ Args:
258
+ submission: {"routes": [root molecule nodes]} in retro-route-graph-v1 form.
259
+ """
260
+ return self._call("emit_routes", submission=submission)
openenv/retroenv_openenv/config.py ADDED
@@ -0,0 +1,107 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Server settings from environment variables, and the read-only data every session shares.
2
+
3
+ Everything is read from one release directory (``tasks-private/``, ``stocks/``,
4
+ ``library/`` and ``manifest.json``; see ``retroenv.benchmark``). The hidden
5
+ routes stay inside the server process; nothing here is bundled into the Docker
6
+ image (``prepare.py`` fetches the release at startup).
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import json
12
+ import os
13
+ from dataclasses import dataclass, field
14
+ from functools import lru_cache
15
+ from pathlib import Path
16
+ from typing import Any
17
+
18
+ from retroenv.benchmark import Benchmark, load_benchmark
19
+ from retroenv.environment import RetroRouteSession
20
+ from retroenv.retrieval import cached_stock_index
21
+ from retroenv.store import TaskStore
22
+ from retroenv.tools import tool_names
23
+ from retroenv.verifier import prepare_stock
24
+
25
+ ENV_NAME = "retro_route"
26
+
27
+
28
+ def _resolve_root() -> Path:
29
+ benchmark = os.getenv("RETROENV_BENCHMARK_DIR")
30
+ if benchmark:
31
+ return Path(benchmark)
32
+ prepared = Path(os.getenv("RETROENV_PREPARED_DIR", "prepared"))
33
+ if (prepared / "tasks-private").is_dir():
34
+ return prepared
35
+ raise RuntimeError(
36
+ "No release configured. Set RETROENV_BENCHMARK_DIR to a release directory "
37
+ "(tasks-private/, stocks/, library/), or run prepare.py first."
38
+ )
39
+
40
+
41
+ @dataclass(frozen=True)
42
+ class Settings:
43
+ benchmark_dir: Path
44
+ default_split: str = "train"
45
+ max_tool_calls: int = 32
46
+ toolset: str = "full"
47
+ pubchem_cache: Path | None = None
48
+
49
+ @classmethod
50
+ def from_env(cls) -> "Settings":
51
+ cache = os.getenv("RETROENV_PUBCHEM_CACHE") or None
52
+ settings = cls(
53
+ benchmark_dir=_resolve_root(),
54
+ default_split=os.getenv("RETROENV_DEFAULT_SPLIT", "train"),
55
+ max_tool_calls=int(os.getenv("RETROENV_MAX_TOOL_CALLS", "32")),
56
+ toolset=os.getenv("RETROENV_TOOLSET", "full"),
57
+ pubchem_cache=Path(cache) if cache else None,
58
+ )
59
+ tool_names(settings.toolset) # fail fast on an unknown toolset
60
+ return settings
61
+
62
+
63
+ @dataclass
64
+ class Resources:
65
+ settings: Settings
66
+ benchmark: Benchmark
67
+ pubchem_cache: dict[str, dict[str, Any]] = field(default_factory=dict)
68
+
69
+ @property
70
+ def store(self) -> TaskStore: # or SqliteTaskStore / EvalsetStore: the same interface
71
+ return self.benchmark.store
72
+
73
+ @classmethod
74
+ def load(cls, settings: Settings) -> "Resources":
75
+ benchmark = load_benchmark(str(settings.benchmark_dir.resolve()))
76
+ splits = benchmark.store.splits()
77
+ if not splits:
78
+ raise RuntimeError(f"no task splits found in {settings.benchmark_dir}")
79
+ if settings.default_split not in splits:
80
+ raise RuntimeError(f"default split {settings.default_split!r} is not among {splits}")
81
+ # Index every stock and canonicalize it for the verifier once, so no episode pays for it.
82
+ for stock_id in benchmark.store.stock_ids():
83
+ stock = benchmark.store.stock(stock_id)
84
+ prepare_stock(cached_stock_index(stock).known)
85
+ return cls(settings=settings, benchmark=benchmark, pubchem_cache=_load_pubchem_cache(settings.pubchem_cache))
86
+
87
+ def session(self) -> RetroRouteSession:
88
+ return self.benchmark.session(
89
+ max_tool_calls=self.settings.max_tool_calls,
90
+ pubchem_cache=self.pubchem_cache,
91
+ toolset=self.settings.toolset,
92
+ )
93
+
94
+
95
+ def _load_pubchem_cache(path: Path | None) -> dict[str, dict[str, Any]]:
96
+ if path is None:
97
+ return {}
98
+ value = json.loads(path.read_text(encoding="utf-8"))
99
+ if not isinstance(value, dict):
100
+ raise ValueError(f"PubChem cache must be a JSON object: {path}")
101
+ return {str(key).casefold(): row for key, row in value.items() if isinstance(row, dict)}
102
+
103
+
104
+ @lru_cache(maxsize=1)
105
+ def shared_resources() -> Resources:
106
+ """Loaded once per process, on the first environment instance."""
107
+ return Resources.load(Settings.from_env())
openenv/retroenv_openenv/environment.py ADDED
@@ -0,0 +1,260 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """The RetroEnv OpenEnv environment: one retrosynthesis episode per WebSocket session.
2
+
3
+ Tools are MCP calls over the shared ``RetroRouteSession`` from core. Every tool
4
+ advertises the JSON schema from ``retroenv.tools``, while argument validation
5
+ stays loose so a malformed route submission reaches the verifier and is scored
6
+ instead of rejected. ``emit_routes`` ends the episode: that step's observation
7
+ carries ``done=True`` and the dense reward, exactly once.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import asyncio
13
+ import functools
14
+ import os
15
+ import random
16
+ from typing import Any
17
+
18
+ from fastmcp import FastMCP
19
+ from fastmcp.tools import Tool
20
+ from openenv.core.env_server.mcp_environment import MCPEnvironment
21
+ from openenv.core.env_server.mcp_types import CallToolObservation
22
+ from openenv.core.env_server.types import EnvironmentMetadata, Observation, State
23
+ from retroenv.tools import tool_spec
24
+
25
+ from .config import ENV_NAME, Resources, shared_resources
26
+
27
+ # OpenEnv's default is 30 s; a scored submission or a stock substructure search can take longer.
28
+ TOOL_TIMEOUT_S = float(os.getenv("RETROENV_TOOL_TIMEOUT", "300"))
29
+
30
+
31
+ def _threaded(handler: Any) -> Any:
32
+ """Run a synchronous tool off the event loop, so one slow call cannot stall other sessions."""
33
+
34
+ @functools.wraps(handler)
35
+ async def run(*args: Any, **kwargs: Any) -> Any:
36
+ return await asyncio.to_thread(handler, *args, **kwargs)
37
+
38
+ return run
39
+
40
+
41
+ DESCRIPTION = (
42
+ "Plan retrosynthesis routes for a target molecule from a fixed purchasable stock. "
43
+ "Tools inspect molecules, search the stock and train-visible reactions, and check "
44
+ "disconnections against a frozen reaction library; emit_routes submits molecule/reaction trees and returns the "
45
+ "verifier's dense reward."
46
+ )
47
+
48
+
49
+ class RetroRouteState(State):
50
+ split: str = ""
51
+ task_index: int = -1
52
+ task_id: str = ""
53
+ toolset: str = "full"
54
+ tool_calls: int = 0
55
+ max_tool_calls: int = 0
56
+ done: bool = False
57
+ reward: float | None = None
58
+
59
+
60
+ class RetroRouteEnvironment(MCPEnvironment):
61
+ # Each WebSocket session gets its own instance; only read-only data is shared.
62
+ SUPPORTS_CONCURRENT_SESSIONS = True
63
+
64
+ def __init__(self, resources: Resources | None = None):
65
+ self.resources = resources or shared_resources()
66
+ settings = self.resources.settings
67
+ self.session = self.resources.session()
68
+ self._state = RetroRouteState(toolset=settings.toolset, max_tool_calls=settings.max_tool_calls)
69
+ self._rng = random.Random()
70
+ mcp = FastMCP("retroenv")
71
+ handlers = self._handlers()
72
+ for name in self.session.tool_names:
73
+ spec = tool_spec(name)
74
+ tool = Tool.from_function(_threaded(handlers[name]), name=name, description=spec["description"])
75
+ mcp.add_tool(tool.model_copy(update={"parameters": spec["parameters"]}))
76
+ super().__init__(mcp)
77
+
78
+ def _handlers(self) -> dict[str, Any]:
79
+ session = self.session
80
+
81
+ def inspect_molecule(smiles: str) -> dict[str, Any]:
82
+ return self._record(session.inspect_molecule(smiles))
83
+
84
+ def pubchem_lookup(query: str) -> dict[str, Any]:
85
+ return self._record(session.pubchem_lookup(query))
86
+
87
+ def stock_retrieve(query: str, mode: str = "auto", limit: int = 10) -> dict[str, Any]:
88
+ return self._record(session.stock_retrieve(query, mode, limit))
89
+
90
+ def reaction_precedent_search(
91
+ product_smiles: str = "", reaction_class: str = "", limit: int = 10
92
+ ) -> dict[str, Any]:
93
+ return self._record(session.reaction_precedent_search(product_smiles, reaction_class, limit))
94
+
95
+ def validate_disconnection(product_smiles: str, reactants: list[str] | str) -> dict[str, Any]:
96
+ return self._record(session.validate_disconnection(product_smiles, reactants))
97
+
98
+ def reaction_class_lookup(product_smiles: str, reactants: list[str] | str) -> dict[str, Any]:
99
+ return self._record(session.reaction_class_lookup(product_smiles, reactants))
100
+
101
+ def reaction_conditions_search(
102
+ product_smiles: str = "",
103
+ reactants: list[str] | str | None = None,
104
+ reaction_class: str = "",
105
+ limit: int = 5,
106
+ ) -> dict[str, Any]:
107
+ return self._record(
108
+ session.reaction_conditions_search(product_smiles, reactants or [], reaction_class, limit)
109
+ )
110
+
111
+ def search_literature(product_smiles: str = "", reaction_class: str = "", limit: int = 5) -> dict[str, Any]:
112
+ return self._record(session.search_literature(product_smiles, reaction_class, limit))
113
+
114
+ def emit_routes(submission: Any) -> dict[str, Any]:
115
+ return self._record(session.emit_routes(submission))
116
+
117
+ return {
118
+ "inspect_molecule": inspect_molecule,
119
+ "pubchem_lookup": pubchem_lookup,
120
+ "stock_retrieve": stock_retrieve,
121
+ "reaction_precedent_search": reaction_precedent_search,
122
+ "validate_disconnection": validate_disconnection,
123
+ "reaction_class_lookup": reaction_class_lookup,
124
+ "reaction_conditions_search": reaction_conditions_search,
125
+ "search_literature": search_literature,
126
+ "emit_routes": emit_routes,
127
+ }
128
+
129
+ def _record(self, value: dict[str, Any]) -> dict[str, Any]:
130
+ self._state.step_count += 1
131
+ self._state.tool_calls = self.session.tool_calls
132
+ if self.session.done and not self._state.done:
133
+ self._state.done = True
134
+ self._state.reward = float((self.session.final_score or {}).get("reward", 0.0))
135
+ return value
136
+
137
+ # --- Task API (metadata only; never references) -------------------------
138
+
139
+ def list_splits(self) -> list[dict[str, Any]]:
140
+ store = self.resources.store
141
+ return [
142
+ {
143
+ "name": split,
144
+ "type": "train" if split == "train" else ("validation" if split == "dev" else "test"),
145
+ "num_tasks": len(store.tasks(split)),
146
+ "default": split == self.resources.settings.default_split,
147
+ }
148
+ for split in store.splits()
149
+ ]
150
+
151
+ def num_tasks(self, split: str) -> int:
152
+ return len(self.resources.store.tasks(split))
153
+
154
+ def get_task(self, split: str, index: int) -> dict[str, Any]:
155
+ tasks = self.resources.store.tasks(split)
156
+ if not 0 <= int(index) < len(tasks):
157
+ raise IndexError(f"task index {index} is out of range for split {split!r}")
158
+ return {"index": int(index), **tasks[int(index)].to_dict(include_hidden=False)}
159
+
160
+ def get_task_range(self, split: str, start: int | None = None, stop: int | None = None) -> list[dict[str, Any]]:
161
+ indices = range(*slice(start, stop).indices(self.num_tasks(split)))
162
+ return [self.get_task(split, index) for index in indices]
163
+
164
+ def list_tasks(self, split: str) -> list[dict[str, Any]]:
165
+ return self.get_task_range(split)
166
+
167
+ # --- Episode lifecycle ---------------------------------------------------
168
+
169
+ def reset(
170
+ self,
171
+ seed: int | None = None,
172
+ episode_id: str | None = None,
173
+ split: str | None = None,
174
+ index: int | None = None,
175
+ task_id: str | None = None,
176
+ **kwargs: Any,
177
+ ) -> Observation:
178
+ """Start an episode. Choose the task by ``index`` or ``task_id``; with
179
+ neither, ``seed`` picks one deterministically, else one is random."""
180
+ store = self.resources.store
181
+ split = split or self.resources.settings.default_split
182
+ tasks = store.tasks(split)
183
+ if not tasks:
184
+ raise IndexError(f"split {split!r} contains no tasks")
185
+ if task_id is not None:
186
+ index = store.position(split, task_id)
187
+ if index is None:
188
+ raise KeyError(f"task {task_id!r} is not in split {split!r}")
189
+ elif index is None:
190
+ index = int(seed) % len(tasks) if seed is not None else self._rng.randrange(len(tasks))
191
+ index = int(index)
192
+ if not 0 <= index < len(tasks):
193
+ raise IndexError(f"task index {index} is out of range for split {split!r}")
194
+ task = tasks[index]
195
+ opening = self.session.reset(task, store.stock(task.stock_id), episode_id=episode_id)
196
+ settings = self.resources.settings
197
+ self._state = RetroRouteState(
198
+ episode_id=self.session.episode_id,
199
+ split=split,
200
+ task_index=index,
201
+ task_id=task.task_id,
202
+ toolset=settings.toolset,
203
+ max_tool_calls=settings.max_tool_calls,
204
+ )
205
+ return Observation(
206
+ done=False,
207
+ reward=None,
208
+ metadata={
209
+ "prompt": opening["prompt"],
210
+ "episode_id": opening["episode_id"],
211
+ "split": split,
212
+ "index": index,
213
+ "task_id": task.task_id,
214
+ "target_smiles": task.target_smiles,
215
+ "variant": task.variant,
216
+ "max_depth": task.max_depth,
217
+ "constraints": task.constraints.to_dict(),
218
+ "min_routes": task.min_routes,
219
+ "max_routes": task.max_routes,
220
+ "stock_id": task.stock_id,
221
+ "toolset": settings.toolset,
222
+ "tools": list(self.session.tool_names),
223
+ "max_tool_calls": settings.max_tool_calls,
224
+ },
225
+ )
226
+
227
+ def step(self, action: Any, timeout_s: float | None = None, **kwargs: Any) -> Observation:
228
+ was_done = self.session.done
229
+ observation = super().step(action, timeout_s=timeout_s or TOOL_TIMEOUT_S, **kwargs)
230
+ return self._mark_terminal(observation, was_done)
231
+
232
+ async def step_async(self, action: Any, timeout_s: float | None = None, **kwargs: Any) -> Observation:
233
+ was_done = self.session.done
234
+ observation = await super().step_async(action, timeout_s=timeout_s or TOOL_TIMEOUT_S, **kwargs)
235
+ return self._mark_terminal(observation, was_done)
236
+
237
+ def _mark_terminal(self, observation: Observation, was_done: bool) -> Observation:
238
+ if self.session.done and isinstance(observation, CallToolObservation):
239
+ observation.done = True
240
+ # Report the episode reward once, on the call that ended it.
241
+ observation.reward = None if was_done else self._state.reward
242
+ return observation
243
+
244
+ def _step_impl(self, action: Any, timeout_s: float | None = None, **kwargs: Any) -> Observation:
245
+ return Observation(
246
+ done=self.session.done,
247
+ reward=None,
248
+ metadata={"error": "Use MCP actions: list_tools, then call_tool."},
249
+ )
250
+
251
+ @property
252
+ def state(self) -> RetroRouteState:
253
+ return self._state
254
+
255
+ def get_metadata(self) -> EnvironmentMetadata:
256
+ return EnvironmentMetadata(
257
+ name=ENV_NAME,
258
+ description=DESCRIPTION,
259
+ version="0.3.0",
260
+ )
openenv/retroenv_openenv/molecule3d.py ADDED
@@ -0,0 +1,128 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """3D molecule views for the playground: one RDKit conformer per molecule, drawn by 3Dmol.js.
2
+
3
+ The server embeds a single deterministic conformer (ETKDG, then MMFF) and returns a small
4
+ self-contained page that the playground shows in an iframe. 3Dmol.js is vendored under
5
+ ``static/`` (BSD-3-Clause), so the view works on a laptop with no network. A conformer shows
6
+ a plausible shape; nothing in the environment or its reward depends on it.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import hashlib
12
+ import json
13
+ from functools import lru_cache
14
+ from html import escape
15
+ from pathlib import Path
16
+ from urllib.parse import quote
17
+
18
+ from rdkit import Chem
19
+ from rdkit.Chem import AllChem
20
+
21
+ STATIC = Path(__file__).resolve().parent / "static"
22
+ MAX_SMILES = 500
23
+ MAX_HEAVY_ATOMS = 120
24
+ SEED = 0xF00D
25
+
26
+
27
+ @lru_cache(maxsize=512)
28
+ def conformer_block(smiles: str) -> str | None:
29
+ """A MOL block with 3D coordinates and explicit hydrogens, or None when RDKit cannot embed it."""
30
+ if not smiles or len(smiles) > MAX_SMILES:
31
+ return None
32
+ mol = Chem.MolFromSmiles(smiles)
33
+ if mol is None or mol.GetNumHeavyAtoms() > MAX_HEAVY_ATOMS:
34
+ return None
35
+ mol = Chem.AddHs(mol)
36
+ params = AllChem.ETKDGv3()
37
+ params.randomSeed = SEED
38
+ if AllChem.EmbedMolecule(mol, params) != 0:
39
+ params.useRandomCoords = True # strained or caged systems often need random starts
40
+ if AllChem.EmbedMolecule(mol, params) != 0:
41
+ return None
42
+ if AllChem.MMFFHasAllMoleculeParams(mol):
43
+ AllChem.MMFFOptimizeMolecule(mol, maxIters=500)
44
+ return Chem.MolToMolBlock(mol)
45
+
46
+
47
+ _PAGE = """<!doctype html>
48
+ <html lang="en">
49
+ <meta charset="utf-8">
50
+ <meta name="viewport" content="width=device-width, initial-scale=1">
51
+ <title>3D view</title>
52
+ <style>
53
+ :root { color-scheme: light dark; --text: #262626; --muted: #737373; --line: #d4d4d4; }
54
+ @media (prefers-color-scheme: dark) { :root { --text: #e5e5e5; --muted: #a3a3a3; --line: #404040; } }
55
+ html, body { margin: 0; height: 100%; overflow: hidden; background: transparent; color: var(--text);
56
+ font: 12px/1.4 Inter, ui-sans-serif, system-ui, sans-serif; }
57
+ #view { position: absolute; inset: 0 0 26px 0; }
58
+ #bar { position: absolute; left: 0; right: 0; bottom: 0; height: 26px; display: flex; gap: 12px;
59
+ align-items: center; color: var(--muted); }
60
+ #bar label, #bar span { display: flex; gap: 4px; align-items: center; white-space: nowrap; }
61
+ @media (max-width: 380px) { #bar .hint { display: none; } }
62
+ select { font: inherit; color: inherit; background: transparent; border: 1px solid var(--line);
63
+ border-radius: 4px; padding: 1px 4px; }
64
+ #empty { padding: 12px 0; color: var(--muted); }
65
+ </style>
66
+ <body>
67
+ __BODY__
68
+ </body>
69
+ </html>
70
+ """
71
+
72
+ _VIEWER = """<div id="view" aria-label="3D structure of __SMILES__"></div>
73
+ <div id="bar">
74
+ <label>Style
75
+ <select id="style">
76
+ <option value="ballstick">Ball and stick</option>
77
+ <option value="stick">Stick</option>
78
+ <option value="sphere">Space filling</option>
79
+ </select>
80
+ </label>
81
+ <label><input type="checkbox" id="hydrogens"> Hydrogens</label>
82
+ <span class="hint">Drag to rotate, scroll to zoom</span>
83
+ </div>
84
+ <script src="/molecule/static/3Dmol-min.js"></script>
85
+ <script>
86
+ const block = __BLOCK__;
87
+ const viewer = $3Dmol.createViewer("view", { backgroundAlpha: 0, antialias: true });
88
+ viewer.addModel(block, "mol");
89
+ const styles = {
90
+ ballstick: { stick: { radius: 0.14 }, sphere: { scale: 0.24 } },
91
+ stick: { stick: { radius: 0.18 } },
92
+ sphere: { sphere: { scale: 1.0 } },
93
+ };
94
+ function draw() {
95
+ const style = styles[document.getElementById("style").value];
96
+ const showH = document.getElementById("hydrogens").checked;
97
+ viewer.setStyle({}, style);
98
+ if (!showH) viewer.setStyle({ elem: "H" }, {});
99
+ viewer.render();
100
+ }
101
+ document.getElementById("style").addEventListener("change", draw);
102
+ document.getElementById("hydrogens").addEventListener("change", draw);
103
+ draw();
104
+ viewer.zoomTo();
105
+ viewer.render();
106
+ // A tab that starts hidden gives the canvas no size; refit once it is shown.
107
+ window.addEventListener("resize", () => { viewer.resize(); viewer.zoomTo(); viewer.render(); });
108
+ </script>"""
109
+
110
+
111
+ # Pages are cached by browsers for a day; changing the template changes this, which changes the URL.
112
+ VERSION = hashlib.sha256((_PAGE + _VIEWER).encode()).hexdigest()[:8]
113
+
114
+
115
+ def viewer_url(smiles: str) -> str:
116
+ return f"/molecule/3d?smiles={quote(smiles, safe='')}&v={VERSION}"
117
+
118
+
119
+ def viewer_page(smiles: str) -> str:
120
+ block = conformer_block(smiles)
121
+ if block is None:
122
+ body = '<p id="empty">No 3D conformer for this molecule.</p>'
123
+ else:
124
+ # json.dumps quotes the block for JavaScript; "</" is split so it cannot end the script.
125
+ body = _VIEWER.replace("__BLOCK__", json.dumps(block).replace("</", "<\\/")).replace(
126
+ "__SMILES__", escape(smiles)
127
+ )
128
+ return _PAGE.replace("__BODY__", body)
openenv/retroenv_openenv/render.py ADDED
@@ -0,0 +1,285 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """HTML for the playground: molecule drawings, route trees and score tables."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import html
6
+ from functools import lru_cache
7
+ from typing import Any
8
+
9
+ from rdkit import Chem
10
+ from rdkit.Chem.Draw import rdMolDraw2D
11
+
12
+ from .molecule3d import viewer_url
13
+
14
+ STYLE = """
15
+ <style>
16
+ /* OpenEnv mounts the playground with its own Gradio theme (a green primary and accent);
17
+ Gradio 6 ignores a theme passed to Blocks, so these variables give it neutral greys. */
18
+ body .gradio-container {
19
+ --button-primary-background-fill: #171717; --button-primary-background-fill-hover: #404040;
20
+ --button-primary-border-color: #171717; --button-primary-text-color: #ffffff;
21
+ --color-accent: #404040; --color-accent-soft: #f5f5f5; --border-color-accent: #a3a3a3;
22
+ --checkbox-background-color-selected: #262626; --loader-color: #525252; --slider-color: #525252;
23
+ }
24
+ body.dark .gradio-container {
25
+ --button-primary-background-fill: #30363d; --button-primary-background-fill-hover: #484f58;
26
+ --button-primary-border-color: #484f58; --button-primary-text-color: #e6edf3;
27
+ --color-accent: #c9d1d9; --color-accent-soft: #30363d; --border-color-accent: #6e7781;
28
+ --checkbox-background-color-selected: #8b949e; --loader-color: #8b949e; --slider-color: #8b949e;
29
+ }
30
+ /* Gradio's own chrome: its footer advertises Gradio rather than the environment. */
31
+ footer { display: none !important; }
32
+ .gradio-container { max-width: 1280px !important; }
33
+ .gradio-container .block { box-shadow: none; }
34
+ .gradio-container .tabs { border: none; }
35
+ .gradio-container .tab-nav button { font-weight: 500; }
36
+ .gradio-container .retro { font-size: 13px; line-height: 1.5; color: var(--body-text-color); }
37
+ .gradio-container .retro .muted { color: var(--body-text-color-subdued); }
38
+ .gradio-container .retro .mono { font-family: var(--font-mono); font-size: 12px; overflow-wrap: anywhere; }
39
+ .gradio-container .retro .mol { border: 1px solid var(--border-color-primary); border-radius: 6px;
40
+ display: inline-block; line-height: 0; padding: 2px; color: var(--body-text-color); }
41
+ .gradio-container .retro table { border-collapse: collapse; width: 100%; font-variant-numeric: tabular-nums; }
42
+ .gradio-container .retro th, .gradio-container .retro td { text-align: left; padding: 4px 8px;
43
+ border-bottom: 1px solid var(--border-color-primary); vertical-align: top; }
44
+ .gradio-container .retro th { color: var(--body-text-color-subdued); font-weight: 500; }
45
+ .gradio-container .retro td.num { text-align: right; }
46
+ .gradio-container .retro .kv { display: grid; grid-template-columns: max-content 1fr; gap: 2px 14px; }
47
+ .gradio-container .retro .kv dt { color: var(--body-text-color-subdued); }
48
+ .gradio-container .retro .kv dd { margin: 0; min-width: 0; }
49
+ .gradio-container .retro .tree { margin-left: 18px; border-left: 1px solid var(--border-color-primary); padding-left: 12px; }
50
+ .gradio-container .retro .node { display: flex; gap: 10px; align-items: center; margin: 6px 0; }
51
+ .gradio-container .retro .rxn { margin: 4px 0 4px 6px; color: var(--body-text-color-subdued); }
52
+ .gradio-container .retro .dot { display: inline-block; width: 7px; height: 7px; border-radius: 50%;
53
+ margin-right: 5px; vertical-align: 1px; background: var(--body-text-color-subdued); }
54
+ .gradio-container .retro .dot.ok { background: #15803d; }
55
+ .gradio-container .retro .dot.bad { background: #c2410c; }
56
+ .gradio-container .retro .views { display: grid; grid-template-columns: repeat(auto-fit, minmax(220px, 1fr)); gap: 10px; }
57
+ .gradio-container .retro .views .mol { display: block; }
58
+ .gradio-container .retro .views .mol svg { width: 100%; height: auto; }
59
+ .gradio-container .retro .frame { border: 1px solid var(--border-color-primary); border-radius: 6px; padding: 4px; }
60
+ .gradio-container .retro .frame iframe { display: block; width: 100%; border: 0; background: transparent; }
61
+ .gradio-container .retro .caption { margin: 2px 0 6px; color: var(--body-text-color-subdued); font-size: 12px; }
62
+ </style>
63
+ """
64
+
65
+
66
+ # Heteroatoms in mid-tone element colours that read on light and dark backgrounds; carbon
67
+ # and every bond stay black in the SVG and are then switched to the page's text colour.
68
+ ATOM_COLOURS = {
69
+ 5: (0.83, 0.48, 0.48), # B
70
+ 7: (0.24, 0.44, 0.85), # N
71
+ 8: (0.88, 0.28, 0.23), # O
72
+ 9: (0.23, 0.65, 0.33), # F
73
+ 15: (0.88, 0.54, 0.12), # P
74
+ 16: (0.79, 0.64, 0.15), # S
75
+ 17: (0.23, 0.65, 0.33), # Cl
76
+ 35: (0.71, 0.40, 0.23), # Br
77
+ 53: (0.56, 0.36, 0.71), # I
78
+ }
79
+
80
+
81
+ @lru_cache(maxsize=512)
82
+ def molecule_svg(smiles: str, width: int = 240, height: int = 160) -> str:
83
+ """A 2D drawing whose bonds follow the page theme and whose heteroatoms keep element colours."""
84
+ mol = Chem.MolFromSmiles(smiles)
85
+ if mol is None:
86
+ return '<span class="muted">unparsable SMILES</span>'
87
+ drawer = rdMolDraw2D.MolDraw2DSVG(width, height)
88
+ options = drawer.drawOptions()
89
+ options.clearBackground = False
90
+ options.padding = 0.08
91
+ options.bondLineWidth = 1.4
92
+ options.useBWAtomPalette()
93
+ options.updateAtomPalette(ATOM_COLOURS)
94
+ drawer.DrawMolecule(mol)
95
+ drawer.FinishDrawing()
96
+ svg = drawer.GetDrawingText().replace("#000000", "currentColor")
97
+ return f'<span class="mol">{svg[svg.find("<svg") :]}</span>'
98
+
99
+
100
+ def wrap(body: str) -> str:
101
+ return f'<div class="retro">{body}</div>'
102
+
103
+
104
+ def key_values(rows: list[tuple[str, str]]) -> str:
105
+ items = "".join(f"<dt>{html.escape(k)}</dt><dd>{v}</dd>" for k, v in rows)
106
+ return f'<dl class="kv">{items}</dl>'
107
+
108
+
109
+ def target_panel(opening: dict[str, Any] | None, state: Any = None) -> str:
110
+ if not opening:
111
+ return wrap('<p class="muted">Choose a split and task, then start an episode.</p>')
112
+ remaining = opening["max_tool_calls"] - (state.tool_calls if state else 0)
113
+ rows = [
114
+ ("Task", f'<span class="mono">{html.escape(opening["task_id"])}</span>'),
115
+ ("Target", f'<span class="mono">{html.escape(opening["target_smiles"])}</span>'),
116
+ ("Depth", f"at most {opening['max_depth']} reactions (longest linear sequence)"),
117
+ ("Variant", html.escape(opening.get("variant", "standard"))),
118
+ ("Routes", f"{opening['min_routes']} to {opening['max_routes']}"),
119
+ ("Stock", html.escape(opening["stock_id"])),
120
+ ("Tool calls left", f"{remaining} of {opening['max_tool_calls']}"),
121
+ ]
122
+ if state is not None and state.done:
123
+ rows.append(("Reward", f"{state.reward:.3f}" if state.reward is not None else "not scored"))
124
+ return wrap(key_values(rows))
125
+
126
+
127
+ def structure_2d(smiles: str | None, width: int = 420, height: int = 280) -> str:
128
+ if not smiles:
129
+ return wrap('<p class="muted">Start an episode to see the target.</p>')
130
+ return wrap(f'<div class="views">{molecule_svg(smiles, width, height)}</div>')
131
+
132
+
133
+ def structure_3d(smiles: str | None, height: int = 300) -> str:
134
+ """The 3D view: an iframe onto the server's conformer page, loaded when it is shown."""
135
+ if not smiles:
136
+ return wrap('<p class="muted">Start an episode to see the target.</p>')
137
+ return wrap(
138
+ f'<div class="frame"><iframe title="3D structure" loading="lazy" height="{height}" '
139
+ f'src="{viewer_url(smiles)}"></iframe></div>'
140
+ '<p class="caption">One RDKit conformer (ETKDG, then MMFF), for shape only.</p>'
141
+ )
142
+
143
+
144
+ def molecule_views(smiles: str | None) -> str:
145
+ """The molecule under study, 2D beside 3D."""
146
+ if not smiles:
147
+ return wrap("")
148
+ return wrap(
149
+ f'<p class="caption mono">{html.escape(smiles)}</p>'
150
+ f'<div class="views">{molecule_svg(smiles, 360, 240)}'
151
+ f'<div class="frame"><iframe title="3D structure" loading="lazy" height="240" '
152
+ f'src="{viewer_url(smiles)}"></iframe></div></div>'
153
+ )
154
+
155
+
156
+ def _route_node(node: Any, depth: int = 0) -> str:
157
+ if not isinstance(node, dict) or depth > 12:
158
+ return '<div class="muted">not a molecule node</div>'
159
+ smiles = str(node.get("smiles", ""))
160
+ stock = node.get("in_stock")
161
+ label = "in stock" if stock else ("intermediate" if node.get("children") else "leaf, not claimed in stock")
162
+ out = (
163
+ f'<div class="node">{molecule_svg(smiles, 150, 100)}'
164
+ f'<div><div class="mono">{html.escape(smiles)}</div><div class="muted">{label}</div></div></div>'
165
+ )
166
+ for reaction in node.get("children") or []:
167
+ if not isinstance(reaction, dict):
168
+ continue
169
+ metadata = reaction.get("metadata") or {}
170
+ title = html.escape(str(metadata.get("reaction_class") or "reaction"))
171
+ note = html.escape(str(metadata.get("explanation") or "")[:240]) # slice first: never split an entity
172
+ children = "".join(_route_node(child, depth + 1) for child in reaction.get("children") or [])
173
+ out += f'<div class="tree"><div class="rxn">{title}{" · " + note if note else ""}</div>{children}</div>'
174
+ return out
175
+
176
+
177
+ def plan_panel(target: str, plan: dict[str, tuple[str, ...]], stock: dict[str, bool]) -> str:
178
+ """The route being assembled by hand, with each precursor's stock status as the tools reported it."""
179
+ if not target:
180
+ return wrap('<p class="muted">Start an episode to plan a route.</p>')
181
+
182
+ def node(smiles: str, depth: int = 0) -> str:
183
+ precursors = plan.get(smiles) if depth <= 12 else None
184
+ if precursors:
185
+ label = "to make"
186
+ elif stock.get(smiles):
187
+ label = '<span class="dot ok"></span>in stock'
188
+ elif smiles in stock:
189
+ label = '<span class="dot bad"></span>not in stock, not yet cut'
190
+ else:
191
+ label = '<span class="dot"></span>stock not checked'
192
+ out = (
193
+ f'<div class="node">{molecule_svg(smiles, 140, 95)}'
194
+ f'<div><div class="mono">{html.escape(smiles)}</div><div class="muted">{label}</div></div></div>'
195
+ )
196
+ for precursor in precursors or ():
197
+ out += f'<div class="tree">{node(precursor, depth + 1)}</div>'
198
+ return out
199
+
200
+ return wrap(node(target))
201
+
202
+
203
+ def verdict_panel(result: dict[str, Any]) -> str:
204
+ """What validate_disconnection said about one proposed cut."""
205
+ if not isinstance(result, dict) or not result:
206
+ return wrap("")
207
+ if result.get("error"):
208
+ return wrap(f'<p><span class="dot bad"></span>{html.escape(str(result["error"]))}</p>')
209
+ supported = bool(result.get("supported"))
210
+ kind = {"known_precedent": "a recorded reaction", "reaction_template": "a frequent reaction template"}.get(
211
+ str(result.get("support")), str(result.get("support"))
212
+ )
213
+ head = (
214
+ f'<span class="dot ok"></span>Supported by {html.escape(kind)}'
215
+ if supported
216
+ else '<span class="dot bad"></span>The train-visible evidence does not support this cut'
217
+ )
218
+ rows = [("Reaction class", html.escape(str(result.get("reaction_class") or "unclassified")))]
219
+ if result.get("template_frequency"):
220
+ rows.append(("Template seen", f"{result['template_frequency']} times"))
221
+ if result.get("stereo_consistent") is not None:
222
+ rows.append(("Stereochemistry", "agrees" if result["stereo_consistent"] else "differs"))
223
+ return wrap(
224
+ f"<p style='margin:0 0 6px'>{head}</p>"
225
+ + key_values(rows)
226
+ + '<p class="muted" style="margin:6px 0 0">The final verifier uses a larger library, so it may still '
227
+ "accept a cut this call rejects.</p>"
228
+ )
229
+
230
+
231
+ def stock_panel(found: list[tuple[str, dict[str, Any]]]) -> str:
232
+ """Stock lookups for the precursors of one proposed cut."""
233
+ rows = []
234
+ for smiles, result in found:
235
+ held = bool(result.get("results"))
236
+ status = '<span class="dot ok"></span>in stock' if held else '<span class="dot bad"></span>not in stock'
237
+ rows.append(
238
+ f"<tr><td>{molecule_svg(smiles, 110, 70)}</td>"
239
+ f'<td class="mono">{html.escape(smiles)}</td><td>{status}</td></tr>'
240
+ )
241
+ return wrap(f"<table><tbody>{''.join(rows)}</tbody></table>")
242
+
243
+
244
+ def routes_panel(submission: Any) -> str:
245
+ routes = submission.get("routes") if isinstance(submission, dict) else None
246
+ if not routes:
247
+ return wrap('<p class="muted">Submitted routes appear here.</p>')
248
+ blocks = "".join(f"<h4>Route {i + 1}</h4>{_route_node(route)}" for i, route in enumerate(routes))
249
+ return wrap(blocks)
250
+
251
+
252
+ def score_panel(score: dict[str, Any] | None) -> str:
253
+ if not score:
254
+ return wrap('<p class="muted">Emit routes to score them.</p>')
255
+ valid = score.get("valid")
256
+ status = f'<span class="dot {"ok" if valid else "bad"}"></span>{"Pass" if valid else "Fail"}'
257
+ rows = "".join(
258
+ f"<tr><td>{html.escape(name.replace('_', ' '))}</td><td class='num'>{value:.3f}</td></tr>"
259
+ for name, value in sorted((score.get("components") or {}).items())
260
+ )
261
+ failures = "".join(f"<li>{html.escape(str(f))}</li>" for f in (score.get("hard_failures") or [])[:6])
262
+ return wrap(
263
+ key_values(
264
+ [
265
+ ("Result", status),
266
+ ("Reward", f"{score.get('reward', 0.0):.3f}"),
267
+ ("Tier", html.escape(str(score.get("verification_tier")))),
268
+ ]
269
+ )
270
+ + f"<table><thead><tr><th>Component</th><th class='num'>Score</th></tr></thead><tbody>{rows}</tbody></table>"
271
+ + (f"<p class='muted'>Why it failed</p><ul>{failures}</ul>" if failures else "")
272
+ )
273
+
274
+
275
+ def history_panel(history: list[dict[str, Any]]) -> str:
276
+ if not history:
277
+ return wrap('<p class="muted">Tool calls appear here.</p>')
278
+ rows = "".join(
279
+ f"<tr><td class='num'>{i + 1}</td><td class='mono'>{html.escape(item['tool'])}</td>"
280
+ f"<td class='mono'>{html.escape(item['arguments'][:120])}</td><td class='mono'>{html.escape(item['summary'][:160])}</td></tr>"
281
+ for i, item in enumerate(history)
282
+ )
283
+ return wrap(
284
+ f"<table><thead><tr><th class='num'>#</th><th>Tool</th><th>Arguments</th><th>Result</th></tr></thead><tbody>{rows}</tbody></table>"
285
+ )
openenv/retroenv_openenv/server.py ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """FastAPI app: MCP tools over /ws and /mcp, the Task API, and the playground at /web."""
2
+
3
+ import os
4
+
5
+ from fastapi.responses import HTMLResponse
6
+ from fastapi.staticfiles import StaticFiles
7
+ from openenv.core.env_server.http_server import create_app
8
+ from openenv.core.env_server.mcp_types import CallToolAction, CallToolObservation
9
+ from rdkit import RDLogger
10
+
11
+ from .config import ENV_NAME
12
+ from .environment import RetroRouteEnvironment
13
+ from .molecule3d import STATIC, viewer_page
14
+
15
+ # Agents send unparsable SMILES all the time; the verifier reports them, so
16
+ # RDKit's per-molecule stderr messages are only noise in the server log.
17
+ RDLogger.DisableLog("rdApp.*")
18
+ os.environ.setdefault("ENABLE_WEB_INTERFACE", "true")
19
+
20
+
21
+ def _build_ui(*args, **kwargs):
22
+ from .ui import build_ui
23
+
24
+ return build_ui(*args, **kwargs)
25
+
26
+
27
+ app = create_app(
28
+ RetroRouteEnvironment,
29
+ CallToolAction,
30
+ CallToolObservation,
31
+ env_name=ENV_NAME,
32
+ max_concurrent_envs=int(os.getenv("MAX_CONCURRENT_ENVS", "64")),
33
+ gradio_builder=_build_ui,
34
+ show_default_tab=False,
35
+ title_override="RetroEnv",
36
+ )
37
+
38
+ # The playground's 3D view: a conformer page per SMILES, and the vendored 3Dmol.js it loads.
39
+ app.mount("/molecule/static", StaticFiles(directory=STATIC), name="molecule-static")
40
+
41
+
42
+ @app.get("/molecule/3d", response_class=HTMLResponse, include_in_schema=False)
43
+ def molecule_3d(smiles: str) -> HTMLResponse:
44
+ # A given SMILES always yields the same conformer, so browsers may keep it.
45
+ return HTMLResponse(viewer_page(smiles), headers={"Cache-Control": "public, max-age=86400"})
openenv/retroenv_openenv/static/3Dmol-LICENSE.txt ADDED
@@ -0,0 +1,90 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 3Dmol.js incorporates code from GLmol, Three.js, and jQuery and
2
+ is licensed under a BSD-3-Clause license.
3
+
4
+ * 3Dmol.js
5
+ Copyright (c) 2014, University of Pittsburgh and contributors
6
+ All rights reserved.
7
+
8
+ Redistribution and use in source and binary forms, with or without
9
+ modification, are permitted provided that the following conditions are met:
10
+
11
+ 1. Redistributions of source code must retain the above copyright
12
+ notice, this list of conditions and the following disclaimer.
13
+
14
+ 2. Redistributions in binary form must reproduce the above copyright
15
+ notice, this list of conditions and the following disclaimer in the
16
+ documentation and/or other materials provided with the distribution.
17
+
18
+ 3. Neither the name of the copyright holder nor the names of its
19
+ contributors may be used to endorse or promote products derived from
20
+ this software without specific prior written permission.
21
+
22
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
23
+ "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
24
+ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
25
+ PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
26
+ HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
27
+ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
28
+ TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
29
+ PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
30
+ LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
31
+ NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
32
+ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
33
+
34
+ * GLmol
35
+ GLmol - Molecular Viewer on WebGL/Javascript (0.47)
36
+ (C) Copyright 2011-2012, biochem_fan
37
+ License: dual license of MIT or LGPL3
38
+
39
+ Contributors:
40
+ Robert Hanson for parseXYZ, deferred instantiation
41
+
42
+
43
+
44
+ * Three.js
45
+ https://github.com/mrdoob/three.js
46
+
47
+ Copyright (c) 2010-2012 three.js Authors. All rights reserved.
48
+
49
+ Permission is hereby granted, free of charge, to any person obtaining a copy
50
+ of this software and associated documentation files (the "Software"), to deal
51
+ in the Software without restriction, including without limitation the rights
52
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
53
+ copies of the Software, and to permit persons to whom the Software is
54
+ furnished to do so, subject to the following conditions:
55
+
56
+ The above copyright notice and this permission notice shall be included in
57
+ all copies or substantial portions of the Software.
58
+
59
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
60
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
61
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
62
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
63
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
64
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
65
+ THE SOFTWARE.
66
+
67
+ * jQuery
68
+ http://jquery.org/
69
+
70
+ Copyright (c) 2011 John Resig
71
+
72
+ Permission is hereby granted, free of charge, to any person obtaining
73
+ a copy of this software and associated documentation files (the
74
+ "Software"), to deal in the Software without restriction, including
75
+ without limitation the rights to use, copy, modify, merge, publish,
76
+ distribute, sublicense, and/or sell copies of the Software, and to
77
+ permit persons to whom the Software is furnished to do so, subject to
78
+ the following conditions:
79
+
80
+ The above copyright notice and this permission notice shall be
81
+ included in all copies or substantial portions of the Software.
82
+
83
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
84
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
85
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
86
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
87
+ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
88
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
89
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
90
+
openenv/retroenv_openenv/static/3Dmol-min.js ADDED
The diff for this file is too large to render. See raw diff
 
openenv/retroenv_openenv/static/3Dmol-min.js.LICENSE.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ /*!
2
+ * 3dmol v2.5.5
3
+ * JavaScript/TypeScript molecular visualization library
4
+ * Author: David Koes and contributors
5
+ */
openenv/retroenv_openenv/ui.py ADDED
@@ -0,0 +1,389 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Browser playground at /web: pick a task, call the tools by hand, submit routes.
2
+
3
+ Each browser session owns one RetroRouteEnvironment, and every call goes
4
+ through the same MCP step path an agent uses, so scores match training and
5
+ evaluation exactly.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import json
11
+ import threading
12
+ from typing import Any
13
+
14
+ import gradio as gr
15
+ from openenv.core.env_server.mcp_types import CallToolAction
16
+ from retroenv.chemistry import ChemistryError, canonicalize_smiles
17
+ from retroenv.disconnections import describe, strategic_disconnections
18
+
19
+ from . import render
20
+ from .client import _tool_payload
21
+ from .config import shared_resources
22
+ from .environment import RetroRouteEnvironment
23
+
24
+
25
+ def _arguments_template(tool: str, target: str) -> dict[str, Any]:
26
+ return {
27
+ "inspect_molecule": {"smiles": target},
28
+ "pubchem_lookup": {"query": target},
29
+ "stock_retrieve": {"query": target, "mode": "exact", "limit": 10},
30
+ "reaction_precedent_search": {"product_smiles": target, "limit": 5},
31
+ "validate_disconnection": {"product_smiles": target, "reactants": ["", ""]},
32
+ "reaction_class_lookup": {"product_smiles": target, "reactants": ["", ""]},
33
+ "reaction_conditions_search": {"product_smiles": target, "reactants": [], "limit": 5},
34
+ "search_literature": {"product_smiles": target, "limit": 5},
35
+ }.get(tool, {})
36
+
37
+
38
+ def _submission_template(target: str) -> dict[str, Any]:
39
+ return {
40
+ "routes": [
41
+ {
42
+ "type": "mol",
43
+ "smiles": target,
44
+ "in_stock": False,
45
+ "children": [
46
+ {
47
+ "type": "reaction",
48
+ "is_reaction": True,
49
+ "metadata": {
50
+ "explanation": "",
51
+ "reaction_class": "",
52
+ "confidence": 0.5,
53
+ "literature": [],
54
+ "precursor_roles": {},
55
+ },
56
+ "children": [{"type": "mol", "smiles": "REACTANT_SMILES", "in_stock": True, "children": []}],
57
+ }
58
+ ],
59
+ }
60
+ ]
61
+ }
62
+
63
+
64
+ def _summary(result: Any) -> str:
65
+ if not isinstance(result, dict):
66
+ return str(result)
67
+ if "error" in result:
68
+ return f"error: {result['error']}"
69
+ if "returned" in result:
70
+ return f"{result['returned']} result(s)"
71
+ if "supported" in result:
72
+ return f"supported={result['supported']} support={result.get('support')}"
73
+ if "score" in result:
74
+ return f"reward={result['score'].get('reward')}"
75
+ return ", ".join(sorted(result))[:160]
76
+
77
+
78
+ class PlaygroundSession:
79
+ def __init__(self) -> None:
80
+ self.lock = threading.RLock()
81
+ self.env: RetroRouteEnvironment | None = None
82
+ self.opening: dict[str, Any] | None = None
83
+ self.history: list[dict[str, Any]] = []
84
+ self.submission: Any = None
85
+ self.score: dict[str, Any] | None = None
86
+ # The route being assembled by hand: product -> precursors, plus what the
87
+ # stock tool has revealed so far. Both drive the Plan tab.
88
+ self.plan: dict[str, tuple[str, ...]] = {}
89
+ self.stock_known: dict[str, bool] = {}
90
+
91
+ def __deepcopy__(self, memo: dict) -> "PlaygroundSession":
92
+ # Gradio copies the initial state per browser session; start each one empty.
93
+ return type(self)()
94
+
95
+ def start(self, split: str, index: int) -> None:
96
+ with self.lock:
97
+ self.close()
98
+ self.env = RetroRouteEnvironment()
99
+ self.opening = self.env.reset(split=split, index=int(index)).metadata
100
+ self.history, self.submission, self.score = [], None, None
101
+ self.plan, self.stock_known = {}, {}
102
+
103
+ def frontier(self) -> list[str]:
104
+ """Molecules still to disconnect: the target, then any precursor neither cut nor known in stock."""
105
+ if not self.opening:
106
+ return []
107
+ out: list[str] = []
108
+ queue, seen = [canonicalize_smiles(self.opening["target_smiles"])], set()
109
+ while queue:
110
+ smiles = queue.pop(0)
111
+ if smiles in seen:
112
+ continue
113
+ seen.add(smiles)
114
+ precursors = self.plan.get(smiles)
115
+ if precursors:
116
+ queue.extend(precursors)
117
+ elif not self.stock_known.get(smiles):
118
+ out.append(smiles)
119
+ return out
120
+
121
+ def build_submission(self) -> dict[str, Any]:
122
+ """The plan as an emit_routes submission, claiming stock only where the stock tool confirmed it."""
123
+ target = canonicalize_smiles(self.opening["target_smiles"]) if self.opening else ""
124
+
125
+ def node(smiles: str, depth: int = 0) -> dict[str, Any]:
126
+ precursors = self.plan.get(smiles) if depth <= 12 else None
127
+ if not precursors:
128
+ return {
129
+ "type": "mol",
130
+ "smiles": smiles,
131
+ "in_stock": self.stock_known.get(smiles, False),
132
+ "children": [],
133
+ }
134
+ reaction = {
135
+ "type": "reaction",
136
+ "is_reaction": True,
137
+ "metadata": {
138
+ "explanation": "",
139
+ "reaction_class": "",
140
+ "confidence": 0.5,
141
+ "literature": [],
142
+ "precursor_roles": {},
143
+ },
144
+ "children": [node(p, depth + 1) for p in precursors],
145
+ }
146
+ return {"type": "mol", "smiles": smiles, "in_stock": False, "children": [reaction]}
147
+
148
+ return {"routes": [node(target)]}
149
+
150
+ def close(self) -> None:
151
+ with self.lock:
152
+ if self.env is not None:
153
+ self.env.close()
154
+ self.env = None
155
+
156
+ def call(self, tool: str, arguments: dict[str, Any]) -> Any:
157
+ with self.lock:
158
+ if self.env is None:
159
+ raise gr.Error("Start an episode first.")
160
+ observation = self.env.step(CallToolAction(tool_name=tool, arguments=arguments))
161
+ error = getattr(observation, "error", None)
162
+ result = {"error": error.message} if error else _tool_payload(observation.result)
163
+ self.history.append(
164
+ {"tool": tool, "arguments": json.dumps(arguments, sort_keys=True), "summary": _summary(result)}
165
+ )
166
+ if tool == "stock_retrieve" and isinstance(result, dict):
167
+ self._note_stock(arguments, result)
168
+ if tool == "emit_routes" and isinstance(result, dict) and result.get("score"):
169
+ self.submission, self.score = arguments.get("submission"), result["score"]
170
+ return result
171
+
172
+ def _note_stock(self, arguments: dict[str, Any], result: dict[str, Any]) -> None:
173
+ """Everything the stock returns is in stock; an exact miss proves the query is not."""
174
+ for row in result.get("results") or []:
175
+ self.stock_known[str(row["smiles"])] = True
176
+ if result.get("mode") in {"exact", "inchikey"} and not result.get("results"):
177
+ try:
178
+ self.stock_known[canonicalize_smiles(str(arguments.get("query", "")))] = False
179
+ except ChemistryError:
180
+ pass
181
+
182
+
183
+ def build_ui(*_: Any, **__: Any) -> gr.Blocks:
184
+ store = shared_resources().store
185
+ splits = store.splits()
186
+ default_split = "test_id" if "test_id" in splits else splits[0]
187
+
188
+ def task_choices(split: str) -> list[tuple[str, int]]:
189
+ return [
190
+ (
191
+ f"{i:03d} · {task.variant} · depth ≤ {task.max_depth} · {task.min_routes} route{'s' if task.min_routes > 1 else ''} · "
192
+ f"{task.target_smiles[:48]}",
193
+ i,
194
+ )
195
+ for i, task in enumerate(store.tasks(split))
196
+ ]
197
+
198
+ def tool_names(session: PlaygroundSession) -> list[str]:
199
+ names = list(session.opening["tools"]) if session.opening else []
200
+ return [name for name in names if name != "emit_routes"]
201
+
202
+ def panels(
203
+ session: PlaygroundSession, keep: str = "", keep_cut: str = ""
204
+ ) -> tuple[str, str, str, str, str, Any, Any, Any]:
205
+ """Every live panel. ``keep`` holds the molecule under study while it still needs cutting,
206
+ and ``keep_cut`` the proposed cut, so checking one does not make you choose it again."""
207
+ state = session.env.state if session.env else None
208
+ target = canonicalize_smiles(session.opening["target_smiles"]) if session.opening else ""
209
+ frontier = session.frontier()
210
+ chosen = keep if keep in frontier else (frontier[0] if frontier else None)
211
+ cuts = cut_choices(chosen or "")
212
+ still_offered = any(keep_cut == value for _, value in cuts)
213
+ return (
214
+ render.target_panel(session.opening, state),
215
+ render.history_panel(session.history),
216
+ render.score_panel(session.score),
217
+ render.routes_panel(session.submission),
218
+ render.plan_panel(target, session.plan, session.stock_known),
219
+ gr.update(choices=frontier, value=chosen),
220
+ # Gradio fires .change only on user input, so the cuts are refreshed here too.
221
+ gr.update(choices=cuts, value=keep_cut if still_offered else None),
222
+ # Redrawing an unchanged molecule would reload its 3D view on every tool call.
223
+ render.molecule_views(chosen) if chosen != keep else gr.update(),
224
+ )
225
+
226
+ def cut_choices(product: str) -> list[tuple[str, str]]:
227
+ """Label each proposed cut with the forward reaction; the value carries the precursors."""
228
+ if not product:
229
+ return []
230
+ out = []
231
+ for cut in strategic_disconnections(product)[:8]:
232
+ phrase = describe(cut.family, cut.reactants, product)
233
+ out.append((f"{cut.bond} · {phrase}", ".".join(cut.reactants)))
234
+ return out
235
+
236
+ with gr.Blocks(title="RetroEnv") as demo:
237
+ session = gr.State(PlaygroundSession())
238
+ gr.HTML(
239
+ render.STYLE
240
+ + render.wrap(
241
+ "<h2 style='margin:0'>RetroEnv</h2><p class='muted' style='margin:2px 0 0'>Plan routes back to "
242
+ "purchasable molecules. These are the tools and the verifier that agents use. "
243
+ "API: <a href='/docs'>/docs</a> · tasks: <a href='/retro_route/splits'>/retro_route/splits</a></p>"
244
+ ),
245
+ apply_default_css=False,
246
+ )
247
+ with gr.Row(equal_height=False):
248
+ with gr.Column(scale=4, min_width=320):
249
+ split = gr.Dropdown(splits, value=default_split, label="Split")
250
+ task = gr.Dropdown(task_choices(default_split), value=0, label="Task")
251
+ start = gr.Button("Start episode", variant="primary")
252
+ with gr.Tabs():
253
+ with gr.Tab("2D"):
254
+ target_2d = gr.HTML(render.structure_2d(None), apply_default_css=False)
255
+ with gr.Tab("3D"):
256
+ target_3d = gr.HTML(render.structure_3d(None), apply_default_css=False)
257
+ target = gr.HTML(render.target_panel(None), apply_default_css=False)
258
+ with gr.Column(scale=7, min_width=360):
259
+ with gr.Tab("Plan"):
260
+ gr.HTML(
261
+ render.wrap(
262
+ "<p class='muted' style='margin:0 0 6px'>Cut the target back to molecules the stock "
263
+ "holds. Checking a cut or a precursor spends a tool call, exactly as it would for a "
264
+ "model.</p>"
265
+ ),
266
+ apply_default_css=False,
267
+ )
268
+ frontier = gr.Dropdown([], label="Molecule to disconnect", interactive=True)
269
+ selected = gr.HTML(render.molecule_views(None), apply_default_css=False)
270
+ candidate = gr.Dropdown([], label="Proposed cut", interactive=True)
271
+ custom = gr.Textbox("", label="Or precursors by hand", placeholder="SMILES.SMILES", max_lines=1)
272
+ with gr.Row():
273
+ check_cut = gr.Button("Check this cut")
274
+ add_cut = gr.Button("Add to plan", variant="primary")
275
+ check_stock = gr.Button("Is it in stock?")
276
+ verdict = gr.HTML(render.wrap(""), apply_default_css=False)
277
+ plan_view = gr.HTML(render.plan_panel("", {}, {}), apply_default_css=False)
278
+ with gr.Tab("Tools"):
279
+ tool = gr.Dropdown([], label="Tool", interactive=True)
280
+ arguments = gr.Code("{}", language="json", label="Arguments", lines=6)
281
+ run = gr.Button("Run tool")
282
+ result = gr.Code("", language="json", label="Result", lines=12, interactive=False)
283
+ with gr.Tab("Submit"):
284
+ from_plan = gr.Button("Fill from the plan")
285
+ submission = gr.Code("", language="json", label="emit_routes submission", lines=16)
286
+ emit = gr.Button("Emit routes and score", variant="primary")
287
+ score = gr.HTML(render.score_panel(None), apply_default_css=False)
288
+ routes = gr.HTML(render.routes_panel(None), apply_default_css=False)
289
+ with gr.Tab("History"):
290
+ history = gr.HTML(render.history_panel([]), apply_default_css=False)
291
+
292
+ def on_split(name: str):
293
+ return gr.update(choices=task_choices(name), value=0)
294
+
295
+ def on_start(state: PlaygroundSession, split_name: str, index: int):
296
+ state.start(split_name, index)
297
+ names = tool_names(state)
298
+ target_smiles = state.opening["target_smiles"]
299
+ first = names[0] if names else None
300
+ return (
301
+ state,
302
+ render.structure_2d(target_smiles),
303
+ render.structure_3d(target_smiles),
304
+ *panels(state),
305
+ gr.update(choices=names, value=first),
306
+ json.dumps(_arguments_template(first, target_smiles), indent=2) if first else "{}",
307
+ "",
308
+ json.dumps(_submission_template(target_smiles), indent=2),
309
+ )
310
+
311
+ def on_tool(state: PlaygroundSession, name: str):
312
+ if not state.opening or not name:
313
+ return "{}"
314
+ return json.dumps(_arguments_template(name, state.opening["target_smiles"]), indent=2)
315
+
316
+ def on_run(state: PlaygroundSession, name: str, text: str, keep: str):
317
+ try:
318
+ args = json.loads(text or "{}")
319
+ except json.JSONDecodeError as exc:
320
+ raise gr.Error(f"Arguments are not valid JSON: {exc}") from exc
321
+ value = state.call(name, args)
322
+ return (state, json.dumps(value, indent=2, sort_keys=True), *panels(state, keep))
323
+
324
+ def on_emit(state: PlaygroundSession, text: str, keep: str):
325
+ try:
326
+ value = json.loads(text or "{}")
327
+ except json.JSONDecodeError as exc:
328
+ raise gr.Error(f"Submission is not valid JSON: {exc}") from exc
329
+ state.call("emit_routes", {"submission": value})
330
+ return (state, *panels(state, keep))
331
+
332
+ def _precursors(chosen: str, typed: str) -> list[str]:
333
+ raw = (typed or chosen or "").strip()
334
+ parts = [piece.strip() for piece in raw.split(".") if piece.strip()]
335
+ if not parts:
336
+ raise gr.Error("Choose a proposed cut, or type the precursors.")
337
+ return parts
338
+
339
+ def on_frontier(product: str):
340
+ return gr.update(choices=cut_choices(product), value=None), render.molecule_views(product)
341
+
342
+ def on_check_cut(state: PlaygroundSession, product: str, chosen: str, typed: str):
343
+ if not product:
344
+ raise gr.Error("Start an episode first.")
345
+ value = state.call(
346
+ "validate_disconnection", {"product_smiles": product, "reactants": _precursors(chosen, typed)}
347
+ )
348
+ return (state, render.verdict_panel(value), *panels(state, product, chosen))
349
+
350
+ def on_check_stock(state: PlaygroundSession, product: str, chosen: str, typed: str):
351
+ if not product:
352
+ raise gr.Error("Start an episode first.")
353
+ found = []
354
+ for smiles in _precursors(chosen, typed):
355
+ found.append((smiles, state.call("stock_retrieve", {"query": smiles, "mode": "exact", "limit": 1})))
356
+ return (state, render.stock_panel(found), *panels(state, product, chosen))
357
+
358
+ def on_add_cut(state: PlaygroundSession, product: str, chosen: str, typed: str):
359
+ if not product:
360
+ raise gr.Error("Start an episode first.")
361
+ try:
362
+ state.plan[canonicalize_smiles(product)] = tuple(
363
+ canonicalize_smiles(piece) for piece in _precursors(chosen, typed)
364
+ )
365
+ except ChemistryError as exc:
366
+ raise gr.Error(f"Not a readable SMILES: {exc}") from exc
367
+ return (state, render.wrap(""), *panels(state))
368
+
369
+ def on_from_plan(state: PlaygroundSession):
370
+ if not state.opening:
371
+ raise gr.Error("Start an episode first.")
372
+ return json.dumps(state.build_submission(), indent=2)
373
+
374
+ plan_outputs = [target, history, score, routes, plan_view, frontier, candidate, selected]
375
+ split.change(on_split, split, task)
376
+ start.click(
377
+ on_start,
378
+ [session, split, task],
379
+ [session, target_2d, target_3d, *plan_outputs, tool, arguments, result, submission],
380
+ )
381
+ tool.change(on_tool, [session, tool], arguments)
382
+ run.click(on_run, [session, tool, arguments, frontier], [session, result, *plan_outputs])
383
+ emit.click(on_emit, [session, submission, frontier], [session, *plan_outputs])
384
+ frontier.input(on_frontier, frontier, [candidate, selected])
385
+ check_cut.click(on_check_cut, [session, frontier, candidate, custom], [session, verdict, *plan_outputs])
386
+ check_stock.click(on_check_stock, [session, frontier, candidate, custom], [session, verdict, *plan_outputs])
387
+ add_cut.click(on_add_cut, [session, frontier, candidate, custom], [session, verdict, *plan_outputs])
388
+ from_plan.click(on_from_plan, session, submission)
389
+ return demo
openenv/rollout.py ADDED
@@ -0,0 +1,89 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Run one RetroEnv episode against a server and print the trajectory.
3
+
4
+ python rollout.py --server http://127.0.0.1:8000 --split eval --index 0 \\
5
+ --provider anthropic --model claude-opus-5-5
6
+
7
+ Providers: anthropic (Messages API), openai (Responses API), or any
8
+ OpenAI-compatible chat endpoint via --endpoint (vLLM, HF router, OpenRouter).
9
+ For many tasks, use eval/run_eval.py in the project folder.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import argparse
15
+ import json
16
+ import os
17
+
18
+ from retroenv_openenv import agent, agent_anthropic, agent_responses
19
+ from retroenv_openenv.client import RetroEnvClient
20
+
21
+
22
+ def main() -> int:
23
+ parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
24
+ parser.add_argument("--server", default=os.getenv("RETROENV_SERVER", "http://127.0.0.1:8000"))
25
+ parser.add_argument("--split", default="eval")
26
+ parser.add_argument("--index", type=int, default=0)
27
+ parser.add_argument("--provider", choices=("anthropic", "openai", "chat"), default="anthropic")
28
+ parser.add_argument("--model", default="claude-opus-5-5")
29
+ parser.add_argument("--endpoint", help="OpenAI-compatible base URL for --provider chat")
30
+ parser.add_argument("--api-key-env", default=None)
31
+ parser.add_argument("--max-turns", type=int, default=int(os.getenv("MAX_TURNS", "16")))
32
+ args = parser.parse_args()
33
+
34
+ with RetroEnvClient(args.server) as env:
35
+ opening = env.reset(args.split, index=args.index)
36
+ print(f"task {opening['task_id']} ({args.split}[{args.index}]) target {opening['target_smiles']}")
37
+ print(f"tools: {', '.join(opening['tools'])}\n")
38
+ if args.provider == "anthropic":
39
+ import anthropic
40
+
41
+ llm = anthropic.Anthropic(api_key=os.getenv(args.api_key_env or "ANTHROPIC_API_KEY"))
42
+ result = agent_anthropic.run_episode(
43
+ llm, env, opening, agent_anthropic.ClaudeConfig(model=args.model, max_turns=args.max_turns)
44
+ )
45
+ else:
46
+ from openai import OpenAI
47
+
48
+ if args.provider == "openai":
49
+ llm = OpenAI(api_key=os.getenv(args.api_key_env or "OPENAI_API_KEY"))
50
+ result = agent_responses.run_episode(
51
+ llm, env, opening, agent_responses.ResponsesConfig(model=args.model, max_turns=args.max_turns)
52
+ )
53
+ else:
54
+ if not args.endpoint:
55
+ parser.error("--endpoint is required for --provider chat")
56
+ llm = OpenAI(base_url=args.endpoint, api_key=os.getenv(args.api_key_env or "OPENAI_API_KEY", "unused"))
57
+ result = agent.run_episode(
58
+ llm, env, opening, agent.AgentConfig(model=args.model, max_turns=args.max_turns)
59
+ )
60
+
61
+ for message in result["transcript"]:
62
+ if message["role"] == "tool":
63
+ print(f" -> {message['content'][:200]}")
64
+ continue
65
+ content = message.get("content")
66
+ calls = message.get("tool_calls") or [
67
+ block
68
+ for block in (content if isinstance(content, list) else [])
69
+ if block.get("type") in ("tool_use", "function_call")
70
+ ]
71
+ for call in calls:
72
+ name = call.get("name") or call.get("function", {}).get("name")
73
+ arguments = call.get("input") or call.get("arguments") or call.get("function", {}).get("arguments")
74
+ print(f" {name}({json.dumps(arguments)[:160] if not isinstance(arguments, str) else arguments[:160]})")
75
+ if isinstance(content, list):
76
+ for block in content:
77
+ if block.get("type") == "tool_result":
78
+ print(f" -> {str(block.get('content'))[:200]}")
79
+ print(
80
+ f"\nreward {result['reward']:.3f} valid {result['valid']} exact {result['exact_match']} "
81
+ f"turns {result['turns']} tool calls {result['tool_calls']}"
82
+ )
83
+ if result["hard_failures"]:
84
+ print("failures: " + "; ".join(result["hard_failures"][:3]))
85
+ return 0
86
+
87
+
88
+ if __name__ == "__main__":
89
+ raise SystemExit(main())
openenv/start.sh ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ cd "$(dirname "$0")"
4
+ # Fetch or check the task bundle, then point the server at the directory prepare.py printed.
5
+ prepared="$(python prepare.py | tail -n 1)"
6
+ export RETROENV_BENCHMARK_DIR="${RETROENV_BENCHMARK_DIR:-${prepared:-${RETROENV_PREPARED_DIR:-prepared}}}"
7
+ exec uvicorn retroenv_openenv.server:app --host 0.0.0.0 --port "${PORT:-8000}" --ws-ping-timeout 600