proef 0.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (200) hide show
  1. proef/__init__.py +25 -0
  2. proef/acquisition.py +244 -0
  3. proef/ad.py +159 -0
  4. proef/adapters/__init__.py +0 -0
  5. proef/adapters/admet.py +196 -0
  6. proef/adapters/bio/__init__.py +0 -0
  7. proef/adapters/bio/rdkit_ops.py +52 -0
  8. proef/adapters/bio/safety_rules.json +146 -0
  9. proef/adapters/bio/seq_alerts.py +79 -0
  10. proef/adapters/bio/structure_score.py +85 -0
  11. proef/adapters/bio/tox_alerts.py +99 -0
  12. proef/adapters/data/__init__.py +0 -0
  13. proef/adapters/data/admet.py +62 -0
  14. proef/adapters/data/chembl.py +110 -0
  15. proef/adapters/data/frozen/admet/MANIFEST.json +48 -0
  16. proef/adapters/data/frozen/admet/bbb_martins/test.csv +407 -0
  17. proef/adapters/data/frozen/admet/bbb_martins/train_val.csv +1625 -0
  18. proef/adapters/data/frozen/admet/caco2_wang/test.csv +183 -0
  19. proef/adapters/data/frozen/admet/caco2_wang/train_val.csv +729 -0
  20. proef/adapters/data/frozen/admet/hia_hou/test.csv +118 -0
  21. proef/adapters/data/frozen/admet/hia_hou/train_val.csv +462 -0
  22. proef/adapters/data/moleculenet.py +60 -0
  23. proef/adapters/databases/__init__.py +0 -0
  24. proef/adapters/databases/chembl_gates.py +121 -0
  25. proef/adapters/databases/chembl_lookup.py +35 -0
  26. proef/adapters/databases/open_targets.py +102 -0
  27. proef/adapters/databases/pubmed.py +94 -0
  28. proef/adapters/devices/__init__.py +0 -0
  29. proef/adapters/devices/ezo_ph.py +251 -0
  30. proef/adapters/devices/hcs_microscope.py +143 -0
  31. proef/adapters/devices/lcms.py +123 -0
  32. proef/adapters/devices/scheduler.py +84 -0
  33. proef/adapters/devices/sila2.py +134 -0
  34. proef/adapters/genomics/alphagenome.py +146 -0
  35. proef/adapters/lab/__init__.py +0 -0
  36. proef/adapters/lab/bioprocess.py +32 -0
  37. proef/adapters/lab/devices.py +170 -0
  38. proef/adapters/lab/imaging.py +226 -0
  39. proef/adapters/lab/mhs_driver.py +124 -0
  40. proef/adapters/lab/opentrons.py +222 -0
  41. proef/adapters/lab/ot2_sim.py +174 -0
  42. proef/adapters/lab/plate_reader_share.py +108 -0
  43. proef/adapters/lab/protein_design.py +199 -0
  44. proef/adapters/lab/recording.py +119 -0
  45. proef/adapters/lab/replay.py +107 -0
  46. proef/adapters/lab/simulator.py +282 -0
  47. proef/adapters/lab/synthesis.py +92 -0
  48. proef/adapters/models/__init__.py +0 -0
  49. proef/adapters/models/anthropic_provider.py +157 -0
  50. proef/adapters/models/assayloop_ranker.py +67 -0
  51. proef/adapters/models/from_env.py +93 -0
  52. proef/adapters/models/gp_policy.py +93 -0
  53. proef/adapters/models/gp_policy_gp.py +36 -0
  54. proef/adapters/models/llm_policy.py +187 -0
  55. proef/adapters/models/openai_compat.py +150 -0
  56. proef/adapters/models/sklearn_policy.py +65 -0
  57. proef/adapters/retrosynthesis.py +247 -0
  58. proef/adapters/sandbox/__init__.py +20 -0
  59. proef/adapters/sandbox/agentenv.py +145 -0
  60. proef/adapters/sandbox/docker.py +217 -0
  61. proef/adapters/sandbox/local.py +164 -0
  62. proef/adapters/sandbox/opensandbox.py +122 -0
  63. proef/adapters/store/__init__.py +0 -0
  64. proef/adapters/store/sqlite.py +207 -0
  65. proef/adaptive.py +108 -0
  66. proef/advisory.py +76 -0
  67. proef/analysis_profiles/__init__.py +8 -0
  68. proef/analysis_profiles/measurements.py +266 -0
  69. proef/analysis_profiles/plate_assay.py +316 -0
  70. proef/analysis_report.py +195 -0
  71. proef/analysis_store.py +183 -0
  72. proef/anchor.py +154 -0
  73. proef/api/app.py +107 -0
  74. proef/api/launch.py +170 -0
  75. proef/api/v1/__init__.py +29 -0
  76. proef/api/v1/analyses.py +367 -0
  77. proef/api/v1/campaigns.py +802 -0
  78. proef/api/v1/deps.py +10 -0
  79. proef/api/v1/evals.py +16 -0
  80. proef/api/v1/evidence.py +132 -0
  81. proef/api/v1/governance.py +35 -0
  82. proef/api/v1/inbox.py +119 -0
  83. proef/api/v1/lab.py +110 -0
  84. proef/api/v1/pauses.py +77 -0
  85. proef/api/v1/programs.py +397 -0
  86. proef/api/v1/results.py +147 -0
  87. proef/api/v1/schemas.py +932 -0
  88. proef/api/v1/system.py +79 -0
  89. proef/api/v1/trees.py +216 -0
  90. proef/api/wizard_sessions.py +253 -0
  91. proef/approvals.py +102 -0
  92. proef/assays/__init__.py +15 -0
  93. proef/assays/dls.py +114 -0
  94. proef/assays/dsf.py +81 -0
  95. proef/assays/elisa.py +58 -0
  96. proef/assays/properties.py +65 -0
  97. proef/assays/simulate.py +157 -0
  98. proef/audit.py +152 -0
  99. proef/autoloop.py +1620 -0
  100. proef/benchmark.py +442 -0
  101. proef/campaign_fsm.py +151 -0
  102. proef/citations.py +141 -0
  103. proef/cli.py +1249 -0
  104. proef/connect.py +74 -0
  105. proef/core/__init__.py +0 -0
  106. proef/core/contracts/__init__.py +35 -0
  107. proef/core/contracts/analysis.py +100 -0
  108. proef/core/contracts/models.py +395 -0
  109. proef/core/device_card.py +125 -0
  110. proef/core/hypothesis.py +720 -0
  111. proef/core/interfaces.py +164 -0
  112. proef/core/registry.py +123 -0
  113. proef/core/safety.py +324 -0
  114. proef/core/workflow.py +159 -0
  115. proef/critic.py +62 -0
  116. proef/demo.py +164 -0
  117. proef/derivation.py +128 -0
  118. proef/diary.py +301 -0
  119. proef/eln.py +87 -0
  120. proef/evals/__init__.py +1 -0
  121. proef/evals/hallucination.py +86 -0
  122. proef/evals/harness.py +358 -0
  123. proef/evals/orchestration.py +254 -0
  124. proef/evals/tasks.py +1010 -0
  125. proef/evals/toolcalls.py +425 -0
  126. proef/experiment.py +172 -0
  127. proef/experiment_analysis.py +114 -0
  128. proef/experiments/__init__.py +0 -0
  129. proef/experiments/grounding_exp.py +689 -0
  130. proef/figures.py +218 -0
  131. proef/fitting.py +309 -0
  132. proef/fixtures.py +140 -0
  133. proef/flywheel.py +125 -0
  134. proef/followup.py +126 -0
  135. proef/governance.py +290 -0
  136. proef/groundedness.py +361 -0
  137. proef/grounding.py +202 -0
  138. proef/hypothesis_agent.py +369 -0
  139. proef/ingest.py +157 -0
  140. proef/instruments.json +173 -0
  141. proef/interpret.py +95 -0
  142. proef/kinetic.py +102 -0
  143. proef/labread/__init__.py +45 -0
  144. proef/labread/analysis.py +428 -0
  145. proef/labread/common.py +153 -0
  146. proef/labread/formats.py +190 -0
  147. proef/labread/layout.py +168 -0
  148. proef/labread/pubchem.py +179 -0
  149. proef/labselect.py +431 -0
  150. proef/materials.py +140 -0
  151. proef/mcp_instrument.py +396 -0
  152. proef/mcp_server.py +283 -0
  153. proef/modality.py +111 -0
  154. proef/model_guard.py +245 -0
  155. proef/output_blocks.py +183 -0
  156. proef/paths.py +32 -0
  157. proef/physfail.py +55 -0
  158. proef/plan.py +160 -0
  159. proef/plots.py +123 -0
  160. proef/predictors.py +217 -0
  161. proef/probes.py +79 -0
  162. proef/problem_tree.py +581 -0
  163. proef/program.py +308 -0
  164. proef/protocol_design.py +42 -0
  165. proef/proxy.py +78 -0
  166. proef/readiness.py +259 -0
  167. proef/reliability.py +49 -0
  168. proef/report.py +117 -0
  169. proef/reproduce.py +310 -0
  170. proef/reviewer.py +254 -0
  171. proef/sandbox_session.py +247 -0
  172. proef/sandboxd.py +109 -0
  173. proef/scaffold.py +195 -0
  174. proef/series.py +327 -0
  175. proef/skills.py +203 -0
  176. proef/sweep.py +83 -0
  177. proef/taste.py +177 -0
  178. proef/templates/confirmatory-followup.json +34 -0
  179. proef/templates/dose-response-screen.json +39 -0
  180. proef/templates/sar-exploration.json +38 -0
  181. proef/templates.py +124 -0
  182. proef/toolkit.py +433 -0
  183. proef/toolloop.py +133 -0
  184. proef/tools.py +441 -0
  185. proef/tpp.py +185 -0
  186. proef/views/__init__.py +14 -0
  187. proef/views/counts.py +102 -0
  188. proef/views/experiment.py +154 -0
  189. proef/views/ids.py +49 -0
  190. proef/views/narrative.py +294 -0
  191. proef/views/pipeline.py +370 -0
  192. proef/vision.py +165 -0
  193. proef/watch.py +790 -0
  194. proef/wizard_chain.py +25 -0
  195. proef/wizard_store.py +373 -0
  196. proef-0.2.0.dist-info/METADATA +662 -0
  197. proef-0.2.0.dist-info/RECORD +200 -0
  198. proef-0.2.0.dist-info/WHEEL +4 -0
  199. proef-0.2.0.dist-info/entry_points.txt +14 -0
  200. proef-0.2.0.dist-info/licenses/LICENSE +202 -0
@@ -0,0 +1,93 @@
1
+ """Pick the campaign's model from the environment — a REAL one, or fail loudly.
2
+
3
+ PROEF_LLM_PRESET optional shortcut for a known gateway (see PRESETS), e.g. "opencode-go"
4
+ PROEF_LLM_MODEL model name
5
+ PROEF_LLM_TOKEN API key (read from the environment only, never a flag)
6
+ PROEF_LLM_BASE_URL endpoint base, e.g. https://api.anthropic.com or https://host/v1
7
+ PROEF_LLM_API "anthropic" (Messages API, default); "openai" (OpenAI-compatible
8
+ /chat/completions — OpenRouter, vLLM, Ollama, ...); or "openai-responses"
9
+ (the /responses API some gateways use for GPT-family models)
10
+ PROEF_LLM_SESSION_HEADER optional: header that carries a stable session id, for gateways that
11
+ require one (e.g. x-opencode-session)
12
+
13
+ Explicit settings always win over a preset. There is no silent offline stub here: a campaign whose
14
+ hypotheses come from a model must be able to say which model wrote them, so an unconfigured model
15
+ is an error, not a fake.
16
+ """
17
+ from __future__ import annotations
18
+
19
+ import os
20
+
21
+ # A preset only fills in what you did not set. `key_env` names the variable that already holds the
22
+ # key in your shell, so you do not have to copy it into PROEF_LLM_TOKEN.
23
+ PRESETS: dict[str, dict] = {
24
+ "opencode-go": {
25
+ "base_url": "https://opencode.ai/inference/go/openai/v1",
26
+ "session_header": "x-opencode-session",
27
+ "key_env": "OPENCODE_API_KEY",
28
+ # GPT / Grok models are served by the Responses API; the other models by chat completions
29
+ "api_by_model_prefix": {("gpt-", "grok-"): "openai-responses"},
30
+ "api_default": "openai",
31
+ },
32
+ }
33
+
34
+
35
+ class ModelNotConfigured(RuntimeError):
36
+ pass
37
+
38
+
39
+ def _resolve(role: str = "") -> dict:
40
+ """The model settings for the campaign, or for one ROLE (e.g. "critic"): PROEF_LLM_CRITIC_MODEL, _API, _BASE_URL,
41
+ _TOKEN, _PRESET and _SESSION_HEADER each override the main setting and fall back to it when unset."""
42
+ def env(name: str):
43
+ r = f"PROEF_LLM_{role.upper()}_{name[len('PROEF_LLM_'):]}" if role else None
44
+ return (os.environ.get(r) if r else None) or os.environ.get(name)
45
+ preset_name = (env("PROEF_LLM_PRESET") or "").strip().lower()
46
+ preset = PRESETS.get(preset_name, {})
47
+ if preset_name and not preset:
48
+ raise ModelNotConfigured(f"unknown PROEF_LLM_PRESET {preset_name!r}; known: {', '.join(sorted(PRESETS))}")
49
+ model = env("PROEF_LLM_MODEL")
50
+ api = env("PROEF_LLM_API")
51
+ if not api and preset:
52
+ api = preset.get("api_default", "openai")
53
+ for prefixes, name in (preset.get("api_by_model_prefix") or {}).items():
54
+ if model and model.startswith(prefixes):
55
+ api = name
56
+ api = (api or "anthropic").lower()
57
+ key = env("PROEF_LLM_TOKEN") or (env(preset["key_env"]) if preset.get("key_env") else None) \
58
+ or (env("ANTHROPIC_AUTH_TOKEN") if api == "anthropic" else None)
59
+ base = env("PROEF_LLM_BASE_URL") or preset.get("base_url")
60
+ return {"api": api, "model": model, "key": key, "base_url": base,
61
+ "session_header": env("PROEF_LLM_SESSION_HEADER") or preset.get("session_header")}
62
+
63
+
64
+ def _is_local(base_url: str | None) -> bool:
65
+ from urllib.parse import urlparse
66
+ return (urlparse(base_url or "").hostname or "") in ("localhost", "127.0.0.1", "::1")
67
+
68
+
69
+ def model_status(role: str = "") -> dict:
70
+ """What the workbench shows: is a real model configured, and which? Never includes the key."""
71
+ try:
72
+ c = _resolve(role)
73
+ except ModelNotConfigured:
74
+ return {"configured": False, "api": None, "model": None}
75
+ # a key is required for hosted endpoints; a local server (Ollama, vLLM) needs none
76
+ ok = bool(c["model"] and (c["key"] or _is_local(c["base_url"])) and (c["base_url"] or c["api"] == "anthropic"))
77
+ return {"configured": ok, "api": c["api"], "model": c["model"] if ok else None}
78
+
79
+
80
+ def model_from_env(role: str = ""):
81
+ c = _resolve(role)
82
+ if not model_status(role)["configured"]:
83
+ raise ModelNotConfigured(
84
+ "no model configured: set PROEF_LLM_MODEL and PROEF_LLM_TOKEN (not needed for a local server), plus PROEF_LLM_BASE_URL "
85
+ "and PROEF_LLM_API=openai or openai-responses for OpenAI-compatible endpoints "
86
+ "(or PROEF_LLM_PRESET=opencode-go with OPENCODE_API_KEY)")
87
+ if c["api"] in ("openai", "openai-responses"):
88
+ from proef.adapters.models.openai_compat import OpenAICompatProvider
89
+ return OpenAICompatProvider(model=c["model"], base_url=c["base_url"], api_key=c["key"],
90
+ api="responses" if c["api"] == "openai-responses" else "chat",
91
+ session_header=c["session_header"])
92
+ from proef.adapters.models.anthropic_provider import AnthropicProvider
93
+ return AnthropicProvider(model=c["model"], api_key=c["key"], base_url=c["base_url"])
@@ -0,0 +1,93 @@
1
+ """BoTorch Gaussian-process policy (optional deps: torch + botorch + rdkit).
2
+
3
+ Posterior PROVIDER, not a decision layer: it hands `proef.acquisition` a
4
+ real epistemic (mean, sd) per candidate instead of the RF tree-spread proxy,
5
+ and stays out of every other import path. The acquisition still does ranking,
6
+ AD veto, diversity and budget; GP optimization (`optimize_acqf`) is not used
7
+ here — its Monte-Carlo randomness would break the byte-exact-replay guarantee
8
+ that evals and `proef campaign reproduce` rely on. We only take the posterior.
9
+
10
+ Determinism: manual_seed makes the (fit, predict) pair reproducible on the
11
+ same machine; `noise="fixed"` skips the learned-noise optimizer so the result
12
+ is bit-identical, not merely same-seed.
13
+ """
14
+ from __future__ import annotations
15
+
16
+ import numpy as np
17
+
18
+
19
+ class GaussianProcessPolicy:
20
+ name = "morgan-gp"
21
+
22
+ def __init__(self, n_bits: int = 2048, radius: int = 2, seed: int = 0,
23
+ noise: float | str = "fit", nu: float = 2.5,
24
+ lengthscale: float | None = 256.0):
25
+ # These are NOT defaults-by-taste: the CS04 coverage check found an
26
+ # un-tuned GP pathologically overconfident (1-sigma coverage ~0.06
27
+ # with fixed noise/lengthscale=64, ~0.00 with lengthscale=n_dim),
28
+ # i.e. an uncertainty that is FICTION. Fitted noise + a ~sqrt-scale
29
+ # lengthscale is the starting point that got coverage near nominal.
30
+ # A GP does not hand you calibrated sd for free — you earn it by
31
+ # tuning against held-out outcomes, which is why this provider is
32
+ # opt-in and never the campaign default.
33
+ self.n_bits, self.radius, self.seed = n_bits, radius, seed
34
+ self.noise = noise
35
+ self.nu, self.lengthscale = nu, lengthscale
36
+
37
+ # ------------------------------------------------------------ features
38
+ def _fp(self, smiles: str) -> list[float]:
39
+ from rdkit import Chem
40
+ from rdkit.Chem import rdFingerprintGenerator
41
+ mol = Chem.MolFromSmiles(smiles)
42
+ if mol is None:
43
+ return [0.0] * self.n_bits
44
+ gen = rdFingerprintGenerator.GetMorganGenerator(
45
+ radius=self.radius, fpSize=self.n_bits)
46
+ return [float(b) for b in gen.GetFingerprint(mol).ToBitString()]
47
+
48
+ # ---------------------------------------------------------------- fit
49
+ def fit(self, data: list[tuple[str, float]]) -> None:
50
+ import torch
51
+ from proef.ad import ApplicabilityDomain
52
+ from proef.adapters.models.gp_policy_gp import _SimpleGP
53
+ from botorch.fit import fit_gpytorch_mll
54
+ from gpytorch.mlls import ExactMarginalLogLikelihood
55
+
56
+ torch.manual_seed(self.seed)
57
+ X = torch.tensor([self._fp(s) for s, _ in data], dtype=torch.float)
58
+ y = torch.tensor([v for _, v in data], dtype=torch.float) # (n,), not (n,1)
59
+ self.y_mean = float(y.mean())
60
+ self.y_std = float(y.std()) if float(y.std()) > 0 else 1.0
61
+ yz = (y - self.y_mean) / self.y_std
62
+ dim = X.shape[1]
63
+ init_ls = self.lengthscale or float(dim)
64
+ gp = _SimpleGP(X, yz, dim=dim, nu=self.nu, lengthscale=init_ls)
65
+ if self.noise == "fit":
66
+ mll = ExactMarginalLogLikelihood(gp.likelihood, gp)
67
+ fit_gpytorch_mll(mll)
68
+ else: # fixed noise => no optimizer, exact reruns
69
+ fixed = 1e-3 if self.noise == "fixed" else float(self.noise)
70
+ gp.likelihood.noise = float(fixed)
71
+ gp.eval()
72
+ self._gp = gp
73
+ self.ad = ApplicabilityDomain.from_smiles([s for s, _ in data],
74
+ basis="morgan")
75
+
76
+ # ------------------------------------------------------------- predict
77
+ def predict_with_sd(self, smiles: str) -> tuple[float, float]:
78
+ """(mean, sd) in the ORIGINAL y-units — the epistemic spread the
79
+ acquisition wants; sd is the GP posterior std, not a heuristic."""
80
+ import torch
81
+ X = torch.tensor([self._fp(smiles)], dtype=torch.float)
82
+ with torch.no_grad():
83
+ mvn = self._gp(X) # eval-mode forward = posterior MVN
84
+ mu = float(mvn.mean.item()) * self.y_std + self.y_mean
85
+ sd = float(mvn.variance.sqrt().item()) * self.y_std
86
+ return mu, sd
87
+
88
+ def predict(self, smiles: str) -> float:
89
+ return self.predict_with_sd(smiles)[0]
90
+
91
+ def predict_with_ad(self, smiles: str) -> tuple[float, dict]:
92
+ mu, sd = self.predict_with_sd(smiles)
93
+ return mu, self.ad.check(smiles)
@@ -0,0 +1,36 @@
1
+ """Minimal exact GP (gpytorch) used by gp_policy.GaussianProcessPolicy.
2
+
3
+ Small on purpose: constant mean, Matern(ν, ARD-off) kernel, Gaussian
4
+ likelihood. ARD-off + a fixed `lengthscale` init keeps it from burning
5
+ compute chasing per-dimension lengthscales over a 2048-bit fingerprint —
6
+ a deliberate, stated approximation, not an oversight; the acquisition needs
7
+ a usable epistemic sd, not the most-tuned GP in the literature.
8
+ """
9
+ from __future__ import annotations
10
+
11
+ import gpytorch
12
+ import torch
13
+
14
+
15
+ class _SimpleGP(gpytorch.models.ExactGP):
16
+ def __init__(self, train_X: torch.Tensor, train_Y: torch.Tensor,
17
+ dim: int, nu: float = 2.5, lengthscale: float = 64.0):
18
+ super().__init__(train_X, train_Y,
19
+ gpytorch.likelihoods.GaussianLikelihood())
20
+ self.mean_module = gpytorch.means.ConstantMean()
21
+ self.covar_module = gpytorch.kernels.ScaleKernel(
22
+ gpytorch.kernels.MaternKernel(
23
+ nu=nu, ard_num_dims=None,
24
+ lengthscale_prior=None,
25
+ lengthscale_constraint=gpytorch.constraints.Positive(),
26
+ ).initialize(lengthscale=lengthscale)
27
+ )
28
+
29
+ def forward(self, x: torch.Tensor):
30
+ return gpytorch.distributions.MultivariateNormal(
31
+ self.mean_module(x), self.covar_module(x))
32
+
33
+ def transform_inputs(self, X: torch.Tensor) -> torch.Tensor:
34
+ # we standardize y ourselves and leave X raw, so this pass-through
35
+ # is what botorch's fit-closure expects from a Model
36
+ return X
@@ -0,0 +1,187 @@
1
+ """LLM property/HTS policies — evaluate a real LLM on chemistry tasks.
2
+
3
+ AnthropicLLMPolicy speaks the Anthropic Messages protocol via stdlib urllib
4
+ (configured by env: PROEF_LLM_BASE_URL / PROEF_LLM_TOKEN / PROEF_LLM_MODEL,
5
+ falling back to ANTHROPIC_BASE_URL / ANTHROPIC_AUTH_TOKEN / ANTHROPIC_DEFAULT_*).
6
+
7
+ LLMs are expensive per call: use `subset` in the harness or evaluate on few
8
+ examples. Model version is pinned on every prediction (P5).
9
+ """
10
+ from __future__ import annotations
11
+
12
+ import json
13
+ import os
14
+ import re
15
+ import urllib.request
16
+ from typing import Any
17
+
18
+
19
+ class AnthropicLLMPolicy:
20
+ name = "llm"
21
+
22
+ def __init__(self, model: str | None = None, base_url: str | None = None,
23
+ token: str | None = None, max_examples: int | None = None):
24
+ self.model = (model or os.environ.get("PROEF_LLM_MODEL")
25
+ or os.environ.get("ANTHROPIC_DEFAULT_SONNET_MODEL")
26
+ or os.environ.get("ANTHROPIC_DEFAULT_HAIKU_MODEL"))
27
+ self.base_url = (base_url or os.environ.get("PROEF_LLM_BASE_URL")
28
+ or os.environ.get("ANTHROPIC_BASE_URL", "")).rstrip("/")
29
+ self.token = (token or os.environ.get("PROEF_LLM_TOKEN")
30
+ or os.environ.get("ANTHROPIC_AUTH_TOKEN") or "")
31
+ self.max_examples = max_examples
32
+ if not (self.model and self.base_url and self.token):
33
+ raise RuntimeError(
34
+ "LLM not configured: set PROEF_LLM_BASE_URL/TOKEN/MODEL "
35
+ "(or ANTHROPIC_BASE_URL/AUTH_TOKEN/... model)"
36
+ )
37
+
38
+ # -- Policy protocol ------------------------------------------------------
39
+
40
+ def fit(self, data: list[tuple[str, float]]) -> None: # noqa: ARG002
41
+ pass # zero-shot; few-shot variants would cache exemplars here
42
+
43
+ def predict(self, smiles: str) -> float:
44
+ raw = self._complete(
45
+ "You are a computational chemist. Predict the property value. "
46
+ "Reply with ONLY a JSON object: {\"value\": <number>}\n\n"
47
+ f"SMILES: {smiles}"
48
+ )
49
+ return self._parse(raw)
50
+
51
+ # -- extras ---------------------------------------------------------------
52
+
53
+ def predict_many(self, smiles_list: list[str], task_hint: str) -> list[float]:
54
+ if self.max_examples:
55
+ smiles_list = smiles_list[: self.max_examples]
56
+ return [self.predict(s) for s in smiles_list]
57
+
58
+ def _complete(self, prompt: str, max_tokens: int = 200) -> str:
59
+ body = json.dumps({
60
+ "model": self.model,
61
+ "max_tokens": max_tokens,
62
+ "messages": [{"role": "user", "content": prompt}],
63
+ }).encode()
64
+ req = urllib.request.Request(
65
+ f"{self.base_url}/v1/messages",
66
+ data=body,
67
+ headers={
68
+ "Content-Type": "application/json",
69
+ "Authorization": f"Bearer {self.token}",
70
+ "anthropic-version": "2023-06-01",
71
+ },
72
+ method="POST",
73
+ )
74
+ with urllib.request.urlopen(req, timeout=90) as resp: # noqa: S310
75
+ data = json.loads(resp.read())
76
+ parts = [c.get("text", "") for c in data.get("content", []) if c.get("type") == "text"]
77
+ return "".join(parts)
78
+
79
+ @staticmethod
80
+ def _parse(raw: str) -> float:
81
+ m = re.search(r"-?\d+(?:\.\d+)?", raw)
82
+ if not m:
83
+ raise ValueError(f"LLM returned no number: {raw[:120]}")
84
+ return float(m.group(0))
85
+
86
+
87
+ def llm_available() -> bool:
88
+ try:
89
+ AnthropicLLMPolicy()
90
+ return True
91
+ except RuntimeError:
92
+ return False
93
+
94
+
95
+ # ------------------------------------------------- few-shot / tool-augmented
96
+
97
+ def _char3gram_vec(s: str) -> dict[str, int]:
98
+ grams = [s[i:i + 3] for i in range(len(s) - 2)]
99
+ v: dict[str, int] = {}
100
+ for g in grams:
101
+ v[g] = v.get(g, 0) + 1
102
+ return v
103
+
104
+
105
+ def _cosine(a: dict[str, int], b: dict[str, int]) -> float:
106
+ num = sum(a[g] * b.get(g, 0) for g in a)
107
+ den = (sum(x * x for x in a.values()) ** 0.5) * (sum(x * x for x in b.values()) ** 0.5)
108
+ return num / den if den else 0.0
109
+
110
+
111
+ class FewShotLLMPolicy(AnthropicLLMPolicy):
112
+ """Zero-shot LLMs have no signal on logD (see docs/benchmarks.md). This policy
113
+ retrieves the k most structurally similar training exemplars (char-gram
114
+ cosine) and inlines them into the prompt."""
115
+
116
+ name = "llm-fewshot"
117
+
118
+ def __init__(self, k: int = 8, **kwargs: Any):
119
+ super().__init__(**kwargs)
120
+ self.k = k
121
+ self.data: list[tuple[str, float]] = []
122
+
123
+ def fit(self, data: list[tuple[str, float]]) -> None:
124
+ self.data = list(data)
125
+
126
+ def predict(self, smiles: str) -> float:
127
+ q = _char3gram_vec(smiles)
128
+ exemplars = sorted(self.data, key=lambda d: _cosine(q, _char3gram_vec(d[0])),
129
+ reverse=True)[: self.k]
130
+ lines = "\n".join(f"SMILES: {s} -> value: {v:.2f}" for s, v in exemplars)
131
+ raw = self._complete(
132
+ "You are a computational chemist. Below are measured examples. "
133
+ "Predict the value for the query molecule, interpolating from the "
134
+ 'examples. Reply with ONLY a JSON object: {"value": <number>}\n\n'
135
+ f"{lines}\n\nSMILES: {smiles}"
136
+ )
137
+ return self._parse(raw)
138
+
139
+
140
+ class ToolAugmentedLLMPolicy(AnthropicLLMPolicy):
141
+ """Gives the LLM what it lacks: computed molecular descriptors (the 'tool'
142
+ output: MolWt, LogP, TPSA, HBD/HBA, rotatable bonds). The LLM's job shifts
143
+ from memorizing chemistry to interpreting measured features."""
144
+
145
+ name = "llm+descriptors"
146
+
147
+ def __init__(self, k: int = 5, **kwargs: Any):
148
+ super().__init__(**kwargs)
149
+ self.k = k
150
+ self.data: list[tuple[str, float]] = []
151
+
152
+ def _desc(self, smiles: str) -> dict[str, float]:
153
+ from rdkit import Chem
154
+ from rdkit.Chem import Descriptors, rdMolDescriptors as rd
155
+
156
+ mol = Chem.MolFromSmiles(smiles)
157
+ if mol is None:
158
+ return {}
159
+ return {
160
+ "MolWt": round(Descriptors.MolWt(mol), 1),
161
+ "LogP": round(Descriptors.MolLogP(mol), 2),
162
+ "TPSA": round(Descriptors.TPSA(mol), 1),
163
+ "HBD": rd.CalcNumHBD(mol),
164
+ "HBA": rd.CalcNumHBA(mol),
165
+ "RotBonds": rd.CalcNumRotatableBonds(mol),
166
+ }
167
+
168
+ def fit(self, data: list[tuple[str, float]]) -> None:
169
+ self.data = list(data)
170
+
171
+ def predict(self, smiles: str) -> float:
172
+ q = _char3gram_vec(smiles)
173
+ exemplars = sorted(self.data, key=lambda d: _cosine(q, _char3gram_vec(d[0])),
174
+ reverse=True)[: self.k]
175
+ ex_lines = "\n".join(
176
+ f"SMILES: {s} | descriptors: {json.dumps(self._desc(s))} -> value: {v:.2f}"
177
+ for s, v in exemplars
178
+ )
179
+ raw = self._complete(
180
+ "You are a computational chemist. Descriptors were computed for each "
181
+ "molecule by an RDKit tool. Using the measured examples, predict the "
182
+ "value for the query molecule. Reply with ONLY: {\"value\": <number>}\n\n"
183
+ f"{ex_lines}\n\n"
184
+ f"Query SMILES: {smiles}\n"
185
+ f"Query descriptors: {json.dumps(self._desc(smiles))}"
186
+ )
187
+ return self._parse(raw)
@@ -0,0 +1,150 @@
1
+ """OpenAI-compatible model provider (P3).
2
+
3
+ Works with OpenAI, ollama, vLLM, llama.cpp server, OpenRouter — anything that
4
+ speaks POST {base_url}/chat/completions. Only stdlib urllib (keeps the adapter
5
+ dependency-free); `httpx` extra available for production use.
6
+
7
+ model_version is pinned from the constructor and stamped on every ToolResult
8
+ (P5). If no network is available (or base_url is None) the provider runs in
9
+ stub mode: deterministic proposals derived from the prompt — enough for
10
+ simulator-first CI (P8).
11
+ """
12
+ from __future__ import annotations
13
+
14
+ import hashlib
15
+ import json
16
+ import urllib.request
17
+ from typing import Any
18
+
19
+ from proef.core.contracts import ToolInvocation, ToolName, ToolResult
20
+
21
+
22
+ class OpenAICompatProvider:
23
+ name = "openai_compat"
24
+
25
+ def __init__(
26
+ self,
27
+ model: str = "stub-1",
28
+ base_url: str | None = None, # e.g. http://localhost:11434/v1 (ollama)
29
+ api_key: str | None = None,
30
+ api: str = "chat", # "chat" (/chat/completions) or "responses" (/responses)
31
+ session_header: str | None = None, # e.g. "x-opencode-session": some gateways route on a stable id
32
+ ):
33
+ import uuid
34
+ self.api = api
35
+ self.session_header = session_header
36
+ self._session = uuid.uuid4().hex
37
+ self.model = model
38
+ self.model_version = model
39
+ self.base_url = base_url
40
+ self.api_key = api_key
41
+
42
+ # -- ModelProvider ------------------------------------------------------
43
+
44
+ def generate(self, invocation: ToolInvocation, prompt: str, system: str | None = None, **kwargs: Any) -> ToolResult:
45
+ if self.base_url is None:
46
+ text = self._stub_generate(prompt, **kwargs)
47
+ else:
48
+ text = self._chat(prompt, system, **kwargs)
49
+ return ToolResult(
50
+ envelope=invocation.envelope.model_copy(),
51
+ invocation_id=invocation.invocation_id,
52
+ status="succeeded",
53
+ output={"text": text},
54
+ model_version=self.model_version,
55
+ )
56
+
57
+ def predict(self, invocation: ToolInvocation, kind: ToolName, payload: dict[str, Any]) -> ToolResult:
58
+ # providers only do text; structured prediction belongs to BioTools.
59
+ return ToolResult(
60
+ envelope=invocation.envelope.model_copy(),
61
+ invocation_id=invocation.invocation_id,
62
+ status="rejected",
63
+ rejection_reason=f"{self.name} does not implement structured prediction '{kind}'",
64
+ )
65
+
66
+ # -- internals ------------------------------------------------------------
67
+
68
+ UA = "proef/0.1 (+https://github.com/rbalachandar/proef)" # some gateways refuse generic HTTP-library agents
69
+
70
+ def _post(self, path: str, body: dict) -> dict:
71
+ import time
72
+ import urllib.error
73
+ req = urllib.request.Request(
74
+ f"{self.base_url.rstrip('/')}/{path}", data=json.dumps(body).encode(), method="POST",
75
+ headers={"Content-Type": "application/json", "User-Agent": self.UA,
76
+ **({"Authorization": f"Bearer {self.api_key}"} if self.api_key else {}),
77
+ **({self.session_header: self._session} if self.session_header else {})})
78
+ for attempt in range(4):
79
+ try:
80
+ with urllib.request.urlopen(req, timeout=120) as resp:
81
+ return json.loads(resp.read())
82
+ except urllib.error.HTTPError as exc: # rate limits and gateway hiccups: back off, then give up loudly
83
+ if exc.code not in (429, 502, 503, 529) or attempt == 3:
84
+ raise
85
+ time.sleep(min(float(exc.headers.get("Retry-After") or 0) or 5 * 2 ** attempt, 60))
86
+ raise RuntimeError("unreachable")
87
+
88
+ def _chat(self, prompt: str, system: str | None, **kwargs: Any) -> str:
89
+ if self.api == "responses":
90
+ body: dict[str, Any] = {"model": self.model, "input": prompt}
91
+ if system:
92
+ body["instructions"] = system
93
+ if "max_tokens" in kwargs:
94
+ body["max_output_tokens"] = kwargs.pop("max_tokens")
95
+ d = self._post("responses", {**body, **kwargs})
96
+ if d.get("output_text"):
97
+ return d["output_text"]
98
+ return "".join(c.get("text", "") for o in d.get("output", []) for c in (o.get("content") or [])
99
+ if c.get("type") in ("output_text", "text"))
100
+ body = {"model": self.model,
101
+ "messages": ([{"role": "system", "content": system}] if system else [])
102
+ + [{"role": "user", "content": prompt}], **kwargs}
103
+ return self._post("chat/completions", body)["choices"][0]["message"]["content"]
104
+
105
+ def call_with_tools(self, messages: list[dict], tools: list[dict],
106
+ system: str = "") -> dict:
107
+ """Send a conversation with tool definitions. Stub mode returns
108
+ a scripted tool call (check synthesis) so the loop works offline."""
109
+ if self.base_url is None:
110
+ # stub: check synthesis for first compound, then done
111
+ self._stub_step = getattr(self, "_stub_step", 0) + 1
112
+ if self._stub_step == 1:
113
+ smi = messages[-1].get("content", "")[-20:]
114
+ return {
115
+ "text": "", "stop_reason": "tool_use",
116
+ "tool_calls": [{"name": "check_synthesis",
117
+ "arguments": {"smiles": smi}}],
118
+ }
119
+ return {"text": "DONE: stub analysis complete",
120
+ "tool_calls": [], "stop_reason": "end_turn"}
121
+ # real API
122
+ body = {
123
+ "model": self.model, "messages": messages,
124
+ "tools": [{"type": "function", "function": t} for t in tools],
125
+ }
126
+ req = urllib.request.Request(
127
+ f"{self.base_url.rstrip('/')}/chat/completions",
128
+ data=json.dumps(body).encode(),
129
+ headers={"Content-Type": "application/json",
130
+ **({"Authorization": f"Bearer {self.api_key}"}
131
+ if self.api_key else {})}, method="POST")
132
+ with urllib.request.urlopen(req, timeout=120) as resp:
133
+ data = json.loads(resp.read())
134
+ msg = data["choices"][0]["message"]
135
+ tool_calls = [
136
+ {"name": tc["function"]["name"],
137
+ "arguments": json.loads(tc["function"]["arguments"])}
138
+ for tc in msg.get("tool_calls", [])
139
+ ]
140
+ return {"text": msg.get("content", ""), "tool_calls": tool_calls,
141
+ "stop_reason": data["choices"][0].get("finish_reason", "")}
142
+
143
+ def _stub_generate(self, prompt: str, n: int = 3, **kwargs: Any) -> str:
144
+ """Deterministic offline generation so CI never needs a model server."""
145
+ h = hashlib.sha256(prompt.encode()).hexdigest()
146
+ proposals = [
147
+ {"smiles": f"C{'C' * (1 + int(h[i:i + 2], 16) % 6)}O", "seed": h[i:i + 8]}
148
+ for i in range(0, 2 * n, 2)
149
+ ]
150
+ return json.dumps(proposals)
@@ -0,0 +1,65 @@
1
+ """Real property-model policies (optional deps: rdkit + scikit-learn).
2
+
3
+ MorganFingerprintRF is the standard cheminformatics baseline: 2048-bit Morgan
4
+ fingerprints (radius 2) + Random Forest. This is the row a real model must beat.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import math
9
+
10
+
11
+ class MorganFingerprintRF:
12
+ name = "morgan2048-rf"
13
+
14
+ def __init__(self, n_estimators: int = 300, n_bits: int = 2048, radius: int = 2, seed: int = 0,
15
+ compute_ad: bool = True):
16
+ self.n_estimators, self.n_bits, self.radius, self.seed = n_estimators, n_bits, radius, seed
17
+ # the applicability domain is O(n^2) in the training set; benchmark-only
18
+ # callers that never read it (case-study RF baselines) can skip it —
19
+ # the forest and its predictions are identical either way
20
+ self.compute_ad = compute_ad
21
+
22
+ def _fp(self, smiles: str) -> list[float]:
23
+ from rdkit import Chem
24
+ from rdkit.Chem import rdFingerprintGenerator
25
+
26
+ mol = Chem.MolFromSmiles(smiles)
27
+ if mol is None:
28
+ return [0.0] * self.n_bits
29
+ gen = rdFingerprintGenerator.GetMorganGenerator(radius=self.radius, fpSize=self.n_bits)
30
+ return [float(b) for b in gen.GetFingerprint(mol).ToBitString()]
31
+
32
+ def fit(self, data: list[tuple[str, float]]) -> None:
33
+ from sklearn.ensemble import RandomForestClassifier, RandomForestRegressor
34
+
35
+ X = [self._fp(s) for s, _ in data]
36
+ y = [v for _, v in data]
37
+ if all(float(v).is_integer() and v in (0.0, 1.0) for v in set(y)):
38
+ self.task = "classification"
39
+ self.model = RandomForestClassifier(n_estimators=self.n_estimators,
40
+ random_state=self.seed, n_jobs=-1,
41
+ class_weight="balanced")
42
+ else:
43
+ self.task = "regression"
44
+ self.model = RandomForestRegressor(n_estimators=self.n_estimators,
45
+ random_state=self.seed, n_jobs=-1)
46
+ self.model.fit(X, y)
47
+ if not self.compute_ad:
48
+ self.ad = None
49
+ return
50
+ from proef.ad import ApplicabilityDomain
51
+ self.ad = ApplicabilityDomain.from_smiles([s for s, _ in data],
52
+ basis="morgan")
53
+
54
+ def predict(self, smiles: str) -> float:
55
+ if self.task == "classification":
56
+ return float(self.model.predict_proba([self._fp(smiles)])[0][1])
57
+ return float(self.model.predict([self._fp(smiles)])[0])
58
+
59
+ def predict_with_ad(self, smiles: str) -> tuple[float, dict]:
60
+ """predict() plus the applicability-domain stamp — the local-model
61
+ guard: outside the training chemistry the number comes back, but
62
+ flagged `extrapolation` so abstention rules widen and cards chip."""
63
+ if self.ad is None:
64
+ raise RuntimeError("built with compute_ad=False — no applicability domain")
65
+ return self.predict(smiles), self.ad.check(smiles)