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.
- proef/__init__.py +25 -0
- proef/acquisition.py +244 -0
- proef/ad.py +159 -0
- proef/adapters/__init__.py +0 -0
- proef/adapters/admet.py +196 -0
- proef/adapters/bio/__init__.py +0 -0
- proef/adapters/bio/rdkit_ops.py +52 -0
- proef/adapters/bio/safety_rules.json +146 -0
- proef/adapters/bio/seq_alerts.py +79 -0
- proef/adapters/bio/structure_score.py +85 -0
- proef/adapters/bio/tox_alerts.py +99 -0
- proef/adapters/data/__init__.py +0 -0
- proef/adapters/data/admet.py +62 -0
- proef/adapters/data/chembl.py +110 -0
- proef/adapters/data/frozen/admet/MANIFEST.json +48 -0
- proef/adapters/data/frozen/admet/bbb_martins/test.csv +407 -0
- proef/adapters/data/frozen/admet/bbb_martins/train_val.csv +1625 -0
- proef/adapters/data/frozen/admet/caco2_wang/test.csv +183 -0
- proef/adapters/data/frozen/admet/caco2_wang/train_val.csv +729 -0
- proef/adapters/data/frozen/admet/hia_hou/test.csv +118 -0
- proef/adapters/data/frozen/admet/hia_hou/train_val.csv +462 -0
- proef/adapters/data/moleculenet.py +60 -0
- proef/adapters/databases/__init__.py +0 -0
- proef/adapters/databases/chembl_gates.py +121 -0
- proef/adapters/databases/chembl_lookup.py +35 -0
- proef/adapters/databases/open_targets.py +102 -0
- proef/adapters/databases/pubmed.py +94 -0
- proef/adapters/devices/__init__.py +0 -0
- proef/adapters/devices/ezo_ph.py +251 -0
- proef/adapters/devices/hcs_microscope.py +143 -0
- proef/adapters/devices/lcms.py +123 -0
- proef/adapters/devices/scheduler.py +84 -0
- proef/adapters/devices/sila2.py +134 -0
- proef/adapters/genomics/alphagenome.py +146 -0
- proef/adapters/lab/__init__.py +0 -0
- proef/adapters/lab/bioprocess.py +32 -0
- proef/adapters/lab/devices.py +170 -0
- proef/adapters/lab/imaging.py +226 -0
- proef/adapters/lab/mhs_driver.py +124 -0
- proef/adapters/lab/opentrons.py +222 -0
- proef/adapters/lab/ot2_sim.py +174 -0
- proef/adapters/lab/plate_reader_share.py +108 -0
- proef/adapters/lab/protein_design.py +199 -0
- proef/adapters/lab/recording.py +119 -0
- proef/adapters/lab/replay.py +107 -0
- proef/adapters/lab/simulator.py +282 -0
- proef/adapters/lab/synthesis.py +92 -0
- proef/adapters/models/__init__.py +0 -0
- proef/adapters/models/anthropic_provider.py +157 -0
- proef/adapters/models/assayloop_ranker.py +67 -0
- proef/adapters/models/from_env.py +93 -0
- proef/adapters/models/gp_policy.py +93 -0
- proef/adapters/models/gp_policy_gp.py +36 -0
- proef/adapters/models/llm_policy.py +187 -0
- proef/adapters/models/openai_compat.py +150 -0
- proef/adapters/models/sklearn_policy.py +65 -0
- proef/adapters/retrosynthesis.py +247 -0
- proef/adapters/sandbox/__init__.py +20 -0
- proef/adapters/sandbox/agentenv.py +145 -0
- proef/adapters/sandbox/docker.py +217 -0
- proef/adapters/sandbox/local.py +164 -0
- proef/adapters/sandbox/opensandbox.py +122 -0
- proef/adapters/store/__init__.py +0 -0
- proef/adapters/store/sqlite.py +207 -0
- proef/adaptive.py +108 -0
- proef/advisory.py +76 -0
- proef/analysis_profiles/__init__.py +8 -0
- proef/analysis_profiles/measurements.py +266 -0
- proef/analysis_profiles/plate_assay.py +316 -0
- proef/analysis_report.py +195 -0
- proef/analysis_store.py +183 -0
- proef/anchor.py +154 -0
- proef/api/app.py +107 -0
- proef/api/launch.py +170 -0
- proef/api/v1/__init__.py +29 -0
- proef/api/v1/analyses.py +367 -0
- proef/api/v1/campaigns.py +802 -0
- proef/api/v1/deps.py +10 -0
- proef/api/v1/evals.py +16 -0
- proef/api/v1/evidence.py +132 -0
- proef/api/v1/governance.py +35 -0
- proef/api/v1/inbox.py +119 -0
- proef/api/v1/lab.py +110 -0
- proef/api/v1/pauses.py +77 -0
- proef/api/v1/programs.py +397 -0
- proef/api/v1/results.py +147 -0
- proef/api/v1/schemas.py +932 -0
- proef/api/v1/system.py +79 -0
- proef/api/v1/trees.py +216 -0
- proef/api/wizard_sessions.py +253 -0
- proef/approvals.py +102 -0
- proef/assays/__init__.py +15 -0
- proef/assays/dls.py +114 -0
- proef/assays/dsf.py +81 -0
- proef/assays/elisa.py +58 -0
- proef/assays/properties.py +65 -0
- proef/assays/simulate.py +157 -0
- proef/audit.py +152 -0
- proef/autoloop.py +1620 -0
- proef/benchmark.py +442 -0
- proef/campaign_fsm.py +151 -0
- proef/citations.py +141 -0
- proef/cli.py +1249 -0
- proef/connect.py +74 -0
- proef/core/__init__.py +0 -0
- proef/core/contracts/__init__.py +35 -0
- proef/core/contracts/analysis.py +100 -0
- proef/core/contracts/models.py +395 -0
- proef/core/device_card.py +125 -0
- proef/core/hypothesis.py +720 -0
- proef/core/interfaces.py +164 -0
- proef/core/registry.py +123 -0
- proef/core/safety.py +324 -0
- proef/core/workflow.py +159 -0
- proef/critic.py +62 -0
- proef/demo.py +164 -0
- proef/derivation.py +128 -0
- proef/diary.py +301 -0
- proef/eln.py +87 -0
- proef/evals/__init__.py +1 -0
- proef/evals/hallucination.py +86 -0
- proef/evals/harness.py +358 -0
- proef/evals/orchestration.py +254 -0
- proef/evals/tasks.py +1010 -0
- proef/evals/toolcalls.py +425 -0
- proef/experiment.py +172 -0
- proef/experiment_analysis.py +114 -0
- proef/experiments/__init__.py +0 -0
- proef/experiments/grounding_exp.py +689 -0
- proef/figures.py +218 -0
- proef/fitting.py +309 -0
- proef/fixtures.py +140 -0
- proef/flywheel.py +125 -0
- proef/followup.py +126 -0
- proef/governance.py +290 -0
- proef/groundedness.py +361 -0
- proef/grounding.py +202 -0
- proef/hypothesis_agent.py +369 -0
- proef/ingest.py +157 -0
- proef/instruments.json +173 -0
- proef/interpret.py +95 -0
- proef/kinetic.py +102 -0
- proef/labread/__init__.py +45 -0
- proef/labread/analysis.py +428 -0
- proef/labread/common.py +153 -0
- proef/labread/formats.py +190 -0
- proef/labread/layout.py +168 -0
- proef/labread/pubchem.py +179 -0
- proef/labselect.py +431 -0
- proef/materials.py +140 -0
- proef/mcp_instrument.py +396 -0
- proef/mcp_server.py +283 -0
- proef/modality.py +111 -0
- proef/model_guard.py +245 -0
- proef/output_blocks.py +183 -0
- proef/paths.py +32 -0
- proef/physfail.py +55 -0
- proef/plan.py +160 -0
- proef/plots.py +123 -0
- proef/predictors.py +217 -0
- proef/probes.py +79 -0
- proef/problem_tree.py +581 -0
- proef/program.py +308 -0
- proef/protocol_design.py +42 -0
- proef/proxy.py +78 -0
- proef/readiness.py +259 -0
- proef/reliability.py +49 -0
- proef/report.py +117 -0
- proef/reproduce.py +310 -0
- proef/reviewer.py +254 -0
- proef/sandbox_session.py +247 -0
- proef/sandboxd.py +109 -0
- proef/scaffold.py +195 -0
- proef/series.py +327 -0
- proef/skills.py +203 -0
- proef/sweep.py +83 -0
- proef/taste.py +177 -0
- proef/templates/confirmatory-followup.json +34 -0
- proef/templates/dose-response-screen.json +39 -0
- proef/templates/sar-exploration.json +38 -0
- proef/templates.py +124 -0
- proef/toolkit.py +433 -0
- proef/toolloop.py +133 -0
- proef/tools.py +441 -0
- proef/tpp.py +185 -0
- proef/views/__init__.py +14 -0
- proef/views/counts.py +102 -0
- proef/views/experiment.py +154 -0
- proef/views/ids.py +49 -0
- proef/views/narrative.py +294 -0
- proef/views/pipeline.py +370 -0
- proef/vision.py +165 -0
- proef/watch.py +790 -0
- proef/wizard_chain.py +25 -0
- proef/wizard_store.py +373 -0
- proef-0.2.0.dist-info/METADATA +662 -0
- proef-0.2.0.dist-info/RECORD +200 -0
- proef-0.2.0.dist-info/WHEEL +4 -0
- proef-0.2.0.dist-info/entry_points.txt +14 -0
- proef-0.2.0.dist-info/licenses/LICENSE +202 -0
proef/groundedness.py
ADDED
|
@@ -0,0 +1,361 @@
|
|
|
1
|
+
"""Is a claim about outside information backed by something this run actually retrieved?
|
|
2
|
+
|
|
3
|
+
A model that cites a paper or a database row can cite a real one it never looked at, or an invented one. The engine cannot tell a true
|
|
4
|
+
claim from a false one, but it can tell whether the identifier the claim rests on appears in a tool result of THIS run. That is cheap,
|
|
5
|
+
mechanical and needs no network. A claim that does not trace is not shown as evidence, and a citation that does not trace is flagged
|
|
6
|
+
(it may still be real: a model's memory is not worthless, it is just not what was read).
|
|
7
|
+
"""
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import json
|
|
11
|
+
import re
|
|
12
|
+
from typing import Any
|
|
13
|
+
|
|
14
|
+
# the identifiers a claim can rest on: PubMed ids, ChEMBL ids, Ensembl gene ids, DOIs
|
|
15
|
+
_ID = re.compile(r"CHEMBL\d+|ENSG\d{6,}|10\.\d{4,9}/[^\s;,]+|(?<![\w.])\d{6,9}(?![\w.])", re.I)
|
|
16
|
+
KINDS = ("supports", "contradicts", "prior_measurement", "already_known", "prior") # "prior": what a prediction or synthesis tool returned, never evidence
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def ids_in(text: Any) -> list[str]:
|
|
20
|
+
"""The identifiers in a citation or source string, in order, without duplicates."""
|
|
21
|
+
return list(dict.fromkeys(m.group(0).rstrip(".)") for m in _ID.finditer(str(text or ""))))
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def haystack(bodies: list[Any]) -> str:
|
|
25
|
+
return json.dumps(bodies, default=str).lower()
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def traces(source: Any, bodies: list[Any]) -> bool:
|
|
29
|
+
"""True when at least one identifier in `source` appears in what the tools returned. A source with no identifier cannot trace."""
|
|
30
|
+
ids = ids_in(source)
|
|
31
|
+
hay = haystack(bodies)
|
|
32
|
+
return bool(ids) and any(i.lower() in hay for i in ids)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _prior_ok(source: str, called: set[str], bodies: list[Any]) -> bool:
|
|
36
|
+
"""A `prior` source names a compute tool that returned a result in this step: "check_synthesis", "predict", or "predict:<predictor>" where the predictor is
|
|
37
|
+
one a `predict` result in this step actually names."""
|
|
38
|
+
head, _, sub = source.partition(":")
|
|
39
|
+
if head.strip() not in called:
|
|
40
|
+
return False
|
|
41
|
+
if sub.strip():
|
|
42
|
+
return sub.strip() in {b.get("tool") for b in bodies if isinstance(b, dict) and b.get("kind") == "prediction"}
|
|
43
|
+
return True
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def verify_items(items: Any, bodies: list[Any], max_items: int = 8, tools_called: tuple[str, ...] | list[str] = ()) -> tuple[list[dict], list[dict]]:
|
|
47
|
+
"""Split a model's grounding items into (kept, dropped). Kept: a known kind, a claim, and a source that traces to a result of this run. For a literature or
|
|
48
|
+
database item the source is an identifier in a retrieved result; for a `prior` item it is the NAME of a compute tool that actually returned a result in
|
|
49
|
+
this loop ("predict", "predict:admet-physchem", "check_synthesis"). Dropped items carry the reason, so a person can see what was refused and why."""
|
|
50
|
+
kept: list[dict] = []
|
|
51
|
+
dropped: list[dict] = []
|
|
52
|
+
called = {str(t) for t in tools_called}
|
|
53
|
+
for it in (items if isinstance(items, list) else [])[: max_items * 2]:
|
|
54
|
+
if not isinstance(it, dict):
|
|
55
|
+
dropped.append({"reason": "not an object"})
|
|
56
|
+
continue
|
|
57
|
+
kind, claim, source = str(it.get("kind") or "")[:20], str(it.get("claim") or "")[:300], str(it.get("source") or "")[:120]
|
|
58
|
+
if kind not in KINDS:
|
|
59
|
+
dropped.append({"kind": kind, "claim": claim, "reason": f"kind must be one of {', '.join(KINDS)}"})
|
|
60
|
+
elif not claim:
|
|
61
|
+
dropped.append({"kind": kind, "reason": "no claim"})
|
|
62
|
+
elif kind == "prior" and not _prior_ok(source, called, bodies):
|
|
63
|
+
dropped.append({"kind": kind, "claim": claim, "source": source, "reason": "no such compute tool returned a result in this step"})
|
|
64
|
+
elif kind != "prior" and not traces(source, bodies):
|
|
65
|
+
dropped.append({"kind": kind, "claim": claim, "source": source, "reason": "its source is not in any result this run retrieved"})
|
|
66
|
+
elif len(kept) < max_items:
|
|
67
|
+
kept.append({"kind": kind, "claim": claim, "source": source})
|
|
68
|
+
return kept, dropped
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
# ---- detectors for what a model says (5F, 5G narrative kinds) -----------------------------------------------------------------------------
|
|
72
|
+
# Each is lexical and deterministic. They catch what can be checked mechanically against facts Proef holds (a library, a gate, a ledger,
|
|
73
|
+
# a finding); they do NOT judge whether an argument is good. Their precision limits are stated in each docstring and measured in the
|
|
74
|
+
# `hallucination` eval on a labelled fixture, so a number here is a measured one.
|
|
75
|
+
|
|
76
|
+
_UNIT_TO_UM = {"pm": 1e-6, "nm": 1e-3, "um": 1.0, "µm": 1.0, "μm": 1.0, "mm": 1e3}
|
|
77
|
+
_NUM_UNIT = re.compile(r"(\d+(?:\.\d+)?)[\s-]*(pM|nM|[uµμ]M|mM)\b", re.I)
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def to_um(value: float, unit: str) -> float:
|
|
81
|
+
return float(value) * _UNIT_TO_UM[unit.lower().replace("u", "u")] if unit.lower() in _UNIT_TO_UM else float(value)
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def not_in_library(name: str, library: list[str]) -> bool:
|
|
85
|
+
"""True when a compound name is not one the library offered (case and surrounding space ignored). Only meaningful when a library was
|
|
86
|
+
offered: with no library every name is the model's own and this says nothing."""
|
|
87
|
+
return bool(library) and name.strip().lower() not in {x.strip().lower() for x in library}
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def structure_problem(smiles: str, name: str = "", library: dict[str, str] | None = None) -> str | None:
|
|
91
|
+
"""None when the structure is fine; else why not: it does not parse, or it disagrees with the structure the library holds for the name
|
|
92
|
+
(compared as canonical SMILES, so a different spelling of the same molecule passes)."""
|
|
93
|
+
from proef.predictors import _check_smiles
|
|
94
|
+
bad = _check_smiles(smiles)
|
|
95
|
+
if bad:
|
|
96
|
+
return bad
|
|
97
|
+
held = (library or {}).get(name) or (library or {}).get(name.lower())
|
|
98
|
+
if held:
|
|
99
|
+
try:
|
|
100
|
+
from rdkit import Chem
|
|
101
|
+
a, b = Chem.MolFromSmiles(smiles), Chem.MolFromSmiles(held)
|
|
102
|
+
if a is not None and b is not None and Chem.MolToSmiles(a) != Chem.MolToSmiles(b):
|
|
103
|
+
return f"the library holds a different structure for {name}"
|
|
104
|
+
except ImportError:
|
|
105
|
+
return None
|
|
106
|
+
return None
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
_OBSERVABLE = re.compile(
|
|
110
|
+
r"\d|<|>|≤|≥|\b(below|above|under|over|exceed\w*|less than|greater than|fewer|more than|no (saturable|specific|measurable|detectable|binding|"
|
|
111
|
+
r"inhibition|activity|shift|effect|dose)|fails? to (reach|show|inhibit|bind)|ic50|ec50|kd|ki|potency|fold|ratio|signal|curve|"
|
|
112
|
+
r"saturat\w*|plateau|competition|shift)\b", re.I)
|
|
113
|
+
_CIRCULAR = re.compile(r"^\W*(if|when|should)\b.{0,40}\b(does not|doesn'?t|fails?|is wrong|is false|is incorrect|is not (true|correct|valid)|"
|
|
114
|
+
r"does not work|isn'?t (true|correct|right)|turns out (wrong|false))\b", re.I)
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def untestable_refutation(text: str) -> str | None:
|
|
118
|
+
"""None when a 'refuted if' clause names something that could be observed; else why not. Lexical: empty, circular ('if it does not
|
|
119
|
+
work') with nothing observable, or nothing observable at all. It cannot tell a sharp clause from a vague one that happens to contain a
|
|
120
|
+
number or the word 'binding'; it catches the obviously empty and obviously circular."""
|
|
121
|
+
t = (text or "").strip()
|
|
122
|
+
if len(t) < 8:
|
|
123
|
+
return "empty"
|
|
124
|
+
if not _OBSERVABLE.search(t):
|
|
125
|
+
return "circular" if _CIRCULAR.search(t) else "no observable or threshold"
|
|
126
|
+
return None
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
_STATE_WORDS = re.compile(r"\b(gate|threshold|cut-?off|criterion|criteria|success|hit|goal|target|requirement)\b|ic50|potency", re.I)
|
|
130
|
+
_CMP = re.compile(r"(below|under|less than|at most|up to|within|sub-?|<=?|≤|above|over|greater than|at least|>=?|≥)\s*(?:an? )?(\d+(?:\.\d+)?)[\s-]*(pM|nM|[uµμ]M|mM)\b", re.I)
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def gate_misstated(text: str, threshold_um: float | None, tol: float = 0.01) -> list[dict]:
|
|
134
|
+
"""A threshold written in the text that is not the gate's, after converting units ('below 20 nM' against a gate of 20 µM). Only a number
|
|
135
|
+
with a concentration unit and a comparison word, in a sentence that talks about the gate, is considered, so a dose or a measurement
|
|
136
|
+
is not mistaken for a threshold. Does not check direction."""
|
|
137
|
+
if not threshold_um:
|
|
138
|
+
return []
|
|
139
|
+
out = []
|
|
140
|
+
for sent in re.split(r"(?<=[.;!?])\s+|\n", text or ""):
|
|
141
|
+
if not _STATE_WORDS.search(sent):
|
|
142
|
+
continue
|
|
143
|
+
# a sentence that states the RIGHT gate is not misstating it: its other comparisons are predictions or examples ("IC50 below
|
|
144
|
+
# 1 uM, and so below the 20 uM gate"). Added after the first real-model text showed exactly that false positive.
|
|
145
|
+
if any(abs(to_um(float(n.group(1)), n.group(2)) - threshold_um) <= tol * threshold_um for n in _NUM_UNIT.finditer(sent)):
|
|
146
|
+
continue
|
|
147
|
+
for m in _CMP.finditer(sent):
|
|
148
|
+
val = to_um(float(m.group(2)), m.group(3))
|
|
149
|
+
if abs(val - threshold_um) > tol * threshold_um:
|
|
150
|
+
out.append({"stated": f"{m.group(2)} {m.group(3)}", "stated_um": val, "gate_um": threshold_um})
|
|
151
|
+
return out
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
_QUOTE_CTX = re.compile(r"(ic50|ec50|kd|\bki\b|observed|measured|potency|gave|showed|yielded|reported|value|=)"
|
|
155
|
+
r"(?:[\s:=~≈]|\b(?:of|was|is|at|about|around|near|approximately|roughly|only|just|to be)\b){0,6}$", re.I)
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
_LITERATURE = re.compile(r"\b(reported|published|literature|chembl|pubmed|pmid|paper|study|studies|previously|prior work)\b", re.I)
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def quoted_number_problems(text: str, findings: list[dict], gate_um: float | None = None, tol: float = 0.05) -> list[dict]:
|
|
162
|
+
"""A value quoted for a named candidate that the data does not show. `findings`: [{'candidate', 'observed_um', 'ci_um': (lo, hi)|None}].
|
|
163
|
+
Only a number with a concentration unit, introduced by a measurement word (IC50, observed, measured, gave...), and within 80 characters
|
|
164
|
+
after a candidate's name is checked; it must match the candidate's observed value or a bound of its interval within `tol`. The gate's own
|
|
165
|
+
value is allowed. Names and numbers only: it does not judge whether the claim built on them is right."""
|
|
166
|
+
out = []
|
|
167
|
+
by = {str(f["candidate"]).lower(): f for f in findings}
|
|
168
|
+
low = (text or "").lower()
|
|
169
|
+
for name, f in by.items():
|
|
170
|
+
for nm in re.finditer(re.escape(name), low):
|
|
171
|
+
window = (text or "")[nm.end(): nm.end() + 80]
|
|
172
|
+
if _LITERATURE.search((text or "")[max(0, nm.start() - 30): nm.end() + 80]):
|
|
173
|
+
continue # "reported IC50 is 506 nM (ChEMBL ...)": a published value, not this campaign's measurement (added after a real flag)
|
|
174
|
+
for m in _NUM_UNIT.finditer(window):
|
|
175
|
+
if not _QUOTE_CTX.search(window[: m.start()]):
|
|
176
|
+
continue
|
|
177
|
+
val = to_um(float(m.group(1)), m.group(2))
|
|
178
|
+
known = [x for x in [f.get("observed_um"), *(f.get("ci_um") or ()), gate_um] if x is not None]
|
|
179
|
+
if not any(abs(val - k) <= tol * abs(k) for k in known) and not any(
|
|
180
|
+
o["candidate"] == f["candidate"] and o["quoted"] == f"{m.group(1)} {m.group(2)}" for o in out):
|
|
181
|
+
out.append({"candidate": f["candidate"], "quoted": f"{m.group(1)} {m.group(2)}", "quoted_um": val,
|
|
182
|
+
"observed_um": f.get("observed_um")})
|
|
183
|
+
return out
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
def ruled_out(candidate: str, family: str | None, negatives: list[dict]) -> dict | None:
|
|
187
|
+
"""The flywheel negative a proposal repeats: the same candidate, or the same mechanistic family, already refuted or invalidated."""
|
|
188
|
+
c, fam = (candidate or "").strip().lower(), (family or "").strip().lower()
|
|
189
|
+
for n in negatives or []:
|
|
190
|
+
if c and str(n.get("candidate", "")).strip().lower() == c:
|
|
191
|
+
return {**n, "match": "candidate"}
|
|
192
|
+
if fam and str(n.get("family") or "").strip().lower() == fam:
|
|
193
|
+
return {**n, "match": "family"}
|
|
194
|
+
return None
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
_NEG = re.compile(r"(\bnot\b|n't\b|\bnever\b|\bno need to\b|\bwithout\b|\bfailed to\b|\bunable to\b)\W+(?:\w+\W+){0,2}$", re.I)
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
def phantom_tool_claims(text: str, called: set[str], offered: set[str]) -> list[str]:
|
|
201
|
+
"""Tool names a narrative says it used that the ledger has no call for. A name must be an offered tool and sit within 40 characters
|
|
202
|
+
after a verb of use (ran, called, used, queried, searched, submitted), and the verb must not be negated ('did not run', 'never used').
|
|
203
|
+
Name-based: it cannot tell a call that failed from one that never happened, only that none is on the record. The negation handling was
|
|
204
|
+
added AFTER the first fixture run showed a false positive on 'I did not run predict', so that category is no longer an untouched test."""
|
|
205
|
+
out = []
|
|
206
|
+
for tool in sorted(offered - called):
|
|
207
|
+
for m in re.finditer(rf"\b(ran|run|called|used|queried|searched|submitted|invoked|checked)\b.{{0,40}}\b{re.escape(tool)}\b", text or "", re.I):
|
|
208
|
+
if not _NEG.search((text or "")[max(0, m.start() - 30): m.start()]):
|
|
209
|
+
out.append(tool)
|
|
210
|
+
break
|
|
211
|
+
return out
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
_VERDICT_CLASS = {"confirmed": "positive", "validated": "positive", "refuted": "negative", "invalidated": "negative", "inconclusive": "abstain",
|
|
215
|
+
"abstained": "abstain", "abstention": "abstain"}
|
|
216
|
+
_STATUS_CLASS = {"confirmed": "positive", "validated": "positive", "refuted": "negative", "invalidated": "negative", "inconclusive": "abstain"}
|
|
217
|
+
_WORD_NUM = {"no": 0, "zero": 0, "one": 1, "two": 2, "three": 3, "four": 4, "five": 5, "six": 6, "seven": 7, "eight": 8, "nine": 9, "ten": 10}
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
def _num(tok: str) -> int | None:
|
|
221
|
+
t = tok.lower()
|
|
222
|
+
return int(t) if t.isdigit() else _WORD_NUM.get(t)
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
def state_claims(text: str, verdicts: dict[str, str], queued: int | None = None, runs_left: int | None = None) -> list[dict]:
|
|
226
|
+
"""What a narrative (an orchestrator's reason, a follow-up's rationale) says about the campaign's own state, checked against it: a
|
|
227
|
+
candidate's verdict, the number of hypotheses queued, the number of lab runs left. Verdicts are compared by class (confirmed and validated
|
|
228
|
+
are positive, refuted and invalidated negative, inconclusive and abstained neither), so 'refuted' for an 'invalidated' result is not an
|
|
229
|
+
error but 'confirmed' for an inconclusive one is. Names and numbers only."""
|
|
230
|
+
out: list[dict] = []
|
|
231
|
+
t = text or ""
|
|
232
|
+
for cand, status in (verdicts or {}).items():
|
|
233
|
+
actual = _STATUS_CLASS.get(str(status).lower())
|
|
234
|
+
for m in re.finditer(rf"\b{re.escape(str(cand))}\b", t, re.I):
|
|
235
|
+
tail = t[m.end(): m.end() + 45]
|
|
236
|
+
for v in re.finditer(r"\b(inconclusive|invalidated|validated|confirmed|refuted|abstained|abstention)\b", tail, re.I):
|
|
237
|
+
# a verdict word used as an ADJECTIVE is not a claim about the candidate: "a validated follow-up", "a confirmed assay". Added after
|
|
238
|
+
# a real model's "the inconclusive AZ191 result may benefit from a validated follow-up" was flagged as claiming AZ191 was validated.
|
|
239
|
+
before = tail[max(0, v.start() - 10): v.start()].lower()
|
|
240
|
+
after = tail[v.end(): v.end() + 14].lower()
|
|
241
|
+
if re.search(r"\b(a|an|the|any|each|another|prior)\s+$", before) or re.match(r"\s+(follow-?up|assay|run|result|method|test|confirmation|replicate)", after):
|
|
242
|
+
continue
|
|
243
|
+
if actual and _VERDICT_CLASS[v.group(1).lower()] != actual:
|
|
244
|
+
out.append({"kind": "verdict", "candidate": cand, "claimed": v.group(1).lower(), "actual": status})
|
|
245
|
+
break
|
|
246
|
+
else:
|
|
247
|
+
continue
|
|
248
|
+
if out and out[-1].get("candidate") == cand:
|
|
249
|
+
break
|
|
250
|
+
if queued is not None:
|
|
251
|
+
for m in re.finditer(r"\b(\d+|no|zero|one|two|three|four|five|six|seven|eight|nine|ten)\b(?:\s+\w+){0,2}?\s+(?:hypothes[ie]s|candidates|variants)\b[^.]{0,30}?\bqueued", t, re.I):
|
|
252
|
+
n = _num(m.group(1))
|
|
253
|
+
if n is not None and n != queued:
|
|
254
|
+
out.append({"kind": "queued", "claimed": n, "actual": queued})
|
|
255
|
+
if runs_left is not None:
|
|
256
|
+
for m in re.finditer(r"\b(\d+)\s+(?:lab\s+)?runs?\s+(?:remain|are left|are available|left|remaining)", t, re.I):
|
|
257
|
+
if int(m.group(1)) != runs_left:
|
|
258
|
+
out.append({"kind": "runs_left", "claimed": int(m.group(1)), "actual": runs_left})
|
|
259
|
+
return out
|
|
260
|
+
|
|
261
|
+
|
|
262
|
+
# ---- what a tool loop's summary says about its own calls and what they returned ----------------------------------------------------------------
|
|
263
|
+
|
|
264
|
+
_NUM_ANY = re.compile(r"(?<![\w.])(\d+(?:\.\d+)?)(?![\w.]*\d)")
|
|
265
|
+
|
|
266
|
+
|
|
267
|
+
def _decomma(t: str) -> str:
|
|
268
|
+
return re.sub(r"(?<=\d),(?=\d{3}(?!\d))", "", t) # 1,100 nM is 1100 nM, not "100 nM"
|
|
269
|
+
|
|
270
|
+
|
|
271
|
+
def _numbers_in(bodies: list[Any]) -> list[float]:
|
|
272
|
+
out: list[float] = []
|
|
273
|
+
for m in _NUM_ANY.finditer(_decomma(json.dumps(bodies, default=str))):
|
|
274
|
+
try:
|
|
275
|
+
out.append(float(m.group(1)))
|
|
276
|
+
except ValueError:
|
|
277
|
+
continue
|
|
278
|
+
return out
|
|
279
|
+
|
|
280
|
+
|
|
281
|
+
def unsupported_values(text: str, bodies: list[Any], extra: str = "", tol: float = 0.02) -> list[dict]:
|
|
282
|
+
"""Values a summary states with a concentration unit or a percent sign that appear NOWHERE in what the tools returned or in the task the model was
|
|
283
|
+
given (`extra`: the objective and the round's results; "sub-20uM" is the task's own gate, not a finding) ("fabricated results"). A value counts as
|
|
284
|
+
supported if its number, or the number converted between nM, uM and mM, is in those within `tol`. Lexical: it cannot tell a value attached to the wrong
|
|
285
|
+
compound from a right one, only that it is not in the data at all, and it does not check values written as words."""
|
|
286
|
+
nums = _numbers_in(bodies) + [float(m.group(1)) for m in _NUM_ANY.finditer(_decomma(extra or ""))]
|
|
287
|
+
out = []
|
|
288
|
+
for m in re.finditer(r"(\d+(?:\.\d+)?)\s*(pM|nM|[uµμ]M|mM|%)", _decomma(text or ""), re.I):
|
|
289
|
+
v = float(m.group(1))
|
|
290
|
+
forms = {v} if m.group(2) == "%" else {v, v * 1e3, v / 1e3, v * 1e6, v / 1e6}
|
|
291
|
+
if not any(abs(n - f) <= tol * max(abs(f), 1e-12) for n in nums for f in forms):
|
|
292
|
+
out.append({"stated": f"{m.group(1)} {m.group(2)}"})
|
|
293
|
+
return out
|
|
294
|
+
|
|
295
|
+
|
|
296
|
+
_NAME_KEYS = ("name", "molecule_name", "pref_name", "title", "symbol", "candidate", "molecule_chembl_id")
|
|
297
|
+
|
|
298
|
+
|
|
299
|
+
def _records(x: Any, out: list[dict] | None = None) -> list[dict]:
|
|
300
|
+
out = [] if out is None else out
|
|
301
|
+
if isinstance(x, dict):
|
|
302
|
+
out.append(x)
|
|
303
|
+
for v in x.values():
|
|
304
|
+
_records(v, out)
|
|
305
|
+
elif isinstance(x, list):
|
|
306
|
+
for v in x:
|
|
307
|
+
_records(v, out)
|
|
308
|
+
return out
|
|
309
|
+
|
|
310
|
+
|
|
311
|
+
def misattributed_values(text: str, bodies: list[Any], tol: float = 0.02) -> list[dict]:
|
|
312
|
+
"""A value stated right after a compound's name that is in the results, but not in the results' record for THAT compound ("gefitinib 41 nM" when 41 is
|
|
313
|
+
erlotinib's). Only when the results hold a record carrying that name: otherwise there is nothing to compare against. A name is a record's own name field,
|
|
314
|
+
not any string inside it."""
|
|
315
|
+
recs = _records(bodies)
|
|
316
|
+
by_name: dict[str, list[dict]] = {}
|
|
317
|
+
for r in recs:
|
|
318
|
+
for k in _NAME_KEYS:
|
|
319
|
+
if isinstance(r.get(k), str) and len(r[k]) >= 3:
|
|
320
|
+
by_name.setdefault(r[k].strip().lower(), []).append(r)
|
|
321
|
+
out = []
|
|
322
|
+
t = _decomma(text or "")
|
|
323
|
+
for name, rs in by_name.items():
|
|
324
|
+
for nm in re.finditer(rf"(?<![\w-]){re.escape(name)}(?![\w-])", t, re.I):
|
|
325
|
+
window = t[nm.end(): nm.end() + 60]
|
|
326
|
+
nxt = [m2.start() for other in by_name if other != name for m2 in re.finditer(rf"(?<![\w-]){re.escape(other)}(?![\w-])", window, re.I)]
|
|
327
|
+
if nxt:
|
|
328
|
+
window = window[: min(nxt)] # a value after ANOTHER compound's name belongs to that compound
|
|
329
|
+
vals = [n for r in rs for n in _numbers_in([{k: v for k, v in r.items() if not isinstance(v, (dict, list))}])]
|
|
330
|
+
for m in re.finditer(r"(\d+(?:\.\d+)?)\s*(pM|nM|[uµμ]M|mM|%)", window, re.I):
|
|
331
|
+
v = float(m.group(1))
|
|
332
|
+
forms = {v} if m.group(2) == "%" else {v, v * 1e3, v / 1e3, v * 1e6, v / 1e6}
|
|
333
|
+
if vals and not any(abs(n - f) <= tol * max(abs(f), 1e-12) for n in vals for f in forms):
|
|
334
|
+
item = {"compound": name, "stated": f"{m.group(1)} {m.group(2)}"}
|
|
335
|
+
if item not in out:
|
|
336
|
+
out.append(item)
|
|
337
|
+
return out
|
|
338
|
+
|
|
339
|
+
|
|
340
|
+
def loop_narrative_flags(text: str, calls: list[dict], offered: set[str], bodies: list[Any], extra: str = "") -> list[dict]:
|
|
341
|
+
"""Advisory flags on a tool loop's own summary, checked against its own calls and results: a tool it says it used that it never called (`phantom_call`),
|
|
342
|
+
a tool it says it used whose every call was refused so nothing came back (`claimed_refused_call`), a refused call repeated unchanged (`ignored_refusal`),
|
|
343
|
+
and a value it states that is in no result (`unsupported_value`)."""
|
|
344
|
+
out: list[dict] = []
|
|
345
|
+
called = {c["tool"] for c in calls}
|
|
346
|
+
ok_tools = {c["tool"] for c in calls if c.get("status") == "ok"}
|
|
347
|
+
for t in phantom_tool_claims(text, called, offered):
|
|
348
|
+
out.append({"kind": "phantom_call", "tool": t})
|
|
349
|
+
for t in sorted(called - ok_tools - {"list_tools", "describe_tool"}):
|
|
350
|
+
if re.search(rf"\b(ran|run|called|used|queried|searched|invoked|checked|found|returned|according to)\b.{{0,40}}\b{re.escape(t)}\b", text or "", re.I):
|
|
351
|
+
out.append({"kind": "claimed_refused_call", "tool": t})
|
|
352
|
+
seen: set[str] = set()
|
|
353
|
+
for c in calls:
|
|
354
|
+
sig = c.get("sig") or c["tool"] + json.dumps(c.get("args"), sort_keys=True, default=str)
|
|
355
|
+
if c.get("status") == "refused" and sig in seen:
|
|
356
|
+
out.append({"kind": "ignored_refusal", "tool": c["tool"], "code": c.get("code")})
|
|
357
|
+
if c.get("status") == "refused":
|
|
358
|
+
seen.add(sig)
|
|
359
|
+
out += [{"kind": "unsupported_value", **x} for x in unsupported_values(text, bodies, extra)]
|
|
360
|
+
out += [{"kind": "misattributed_value", **x} for x in misattributed_values(text, bodies)]
|
|
361
|
+
return out
|
proef/grounding.py
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
"""Grounding before a proposal (5H, `propose`): a model reads PubMed, ChEMBL and Open Targets through the tool loop, then proposes.
|
|
2
|
+
|
|
3
|
+
The loop is state-scoped to `propose` and offered ONLY the knowledge tools the operator enabled: no flow tool, no lab door. Every query is
|
|
4
|
+
egress-checked and every result is delimited, sealed and on the ledger. What comes back is context for the proposal prompt and nothing
|
|
5
|
+
more: it is labelled untrusted, and it never becomes a verdict, an approval or a criterion (only a measurement does).
|
|
6
|
+
"""
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from dataclasses import dataclass, field
|
|
10
|
+
|
|
11
|
+
from proef.core.interfaces import system_actor
|
|
12
|
+
from proef.tools import KNOWLEDGE_TOOL_NAMES, KNOWLEDGE_TOOLS, ToolCatalog, ToolContext
|
|
13
|
+
from proef.toolloop import ToolLoop
|
|
14
|
+
|
|
15
|
+
TASK = ("Before hypotheses are proposed for this objective, look up what is already known. Use the tools offered to find relevant "
|
|
16
|
+
"literature, known target biology and published activities. Query by general scientific terms (target, mechanism, disease), "
|
|
17
|
+
"never by this campaign's own candidate ids. When you have enough, reply done with a short summary of what you found and "
|
|
18
|
+
"which tool it came from.\n\nOBJECTIVE: {objective}\nCONTEXT: {context}")
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
DECIDE_TASK = ("A round of experiments has just been judged. Look up published information that could explain these results or "
|
|
22
|
+
"suggest what to test next: known behaviour of the compound classes, assay interference, reported potency of related "
|
|
23
|
+
"compounds. Query by general scientific terms (target, mechanism, assay, compound class). Never put a measured value or "
|
|
24
|
+
"any of this campaign's own identifiers in a query. When you have enough, reply done with a short summary of what you "
|
|
25
|
+
"found and which tool it came from.\n\nOBJECTIVE: {objective}\n\nRESULTS OF THIS ROUND\n{results}")
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def library_secrets(candidates, public=()) -> set[str]:
|
|
29
|
+
"""What a campaign's own library must never send out in a query: each entry's id (`sample_id`, `id`, `candidate` or `name`), its structure
|
|
30
|
+
(`smiles`) and its `sequence`, except names the operator declared public."""
|
|
31
|
+
pub = {str(n).lower() for n in public}
|
|
32
|
+
out: set[str] = set()
|
|
33
|
+
for c in candidates or []:
|
|
34
|
+
if not isinstance(c, dict):
|
|
35
|
+
continue
|
|
36
|
+
ident = next((str(c[k]) for k in ("sample_id", "id", "candidate", "name") if c.get(k)), "")
|
|
37
|
+
if ident.lower() in pub:
|
|
38
|
+
continue
|
|
39
|
+
out |= {str(c[k]) for k in ("sample_id", "id", "candidate", "name", "smiles", "sequence") if c.get(k)}
|
|
40
|
+
return {x for x in out if len(x) >= 3}
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def operator_names(cfg) -> set[str]:
|
|
44
|
+
"""Candidate names the OPERATOR supplied, as opposed to names a model chose from its own knowledge: those in a configured hypothesis list.
|
|
45
|
+
(A library's ids are covered by `library_secrets`.) A name the model proposed itself ('gefitinib') is the model's own public knowledge."""
|
|
46
|
+
return {str(h.get("candidate")) for h in (getattr(cfg, "hypotheses", None) or []) if isinstance(h, dict) and h.get("candidate")}
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def value_strings(values) -> set[str]:
|
|
50
|
+
"""The ways a measured number could be written in a query, so egress checking can refuse it (three characters or more)."""
|
|
51
|
+
out: set[str] = set()
|
|
52
|
+
for v in values:
|
|
53
|
+
if isinstance(v, (int, float)) and not isinstance(v, bool):
|
|
54
|
+
out |= {f"{v:g}", f"{v:.3g}", f"{v:.2f}", f"{v:.1f}"}
|
|
55
|
+
return {x for x in out if len(x) >= 3}
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
@dataclass
|
|
59
|
+
class Grounding:
|
|
60
|
+
text: str = "" # what goes into the proposal prompt ("" when nothing was learned)
|
|
61
|
+
calls: list[dict] = field(default_factory=list) # every tool step: tool, status, code
|
|
62
|
+
flags: list[dict] = field(default_factory=list) # advisory flags on the loop's own summary (phantom call, claim from a refused call, unsupported value)
|
|
63
|
+
stopped: str | None = None
|
|
64
|
+
|
|
65
|
+
@property
|
|
66
|
+
def used(self) -> list[str]:
|
|
67
|
+
return [c["tool"] for c in self.calls if c.get("status") == "ok"]
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def gather(model, problem, store, services: dict, tools: tuple[str, ...], egress_ok: set | None = None, protected: set | None = None,
|
|
71
|
+
branch: str | None = None, replay: dict | None = None, max_steps: int = 6, max_tool_calls: int = 8,
|
|
72
|
+
state: str = "propose", round_no: int | None = None, results: str = "", compute: tuple[str, ...] = (),
|
|
73
|
+
registry=None, predictors: list[str] | None = None, modality: str | None = None, blinding: dict | None = None) -> Grounding:
|
|
74
|
+
cat = ToolCatalog()
|
|
75
|
+
for k in tools:
|
|
76
|
+
cat.register(KNOWLEDGE_TOOLS[k]())
|
|
77
|
+
names = {KNOWLEDGE_TOOL_NAMES[k] for k in tools}
|
|
78
|
+
if "predict" in compute and state == "propose":
|
|
79
|
+
from proef.predictors import DEFAULT
|
|
80
|
+
from proef.tools import predict_tool
|
|
81
|
+
cat.register(predict_tool(registry or DEFAULT, predictors, modality))
|
|
82
|
+
names.add("predict")
|
|
83
|
+
if "synthesis" in compute and state == "propose":
|
|
84
|
+
from proef.tools import synthesis_tool
|
|
85
|
+
cat.register(synthesis_tool())
|
|
86
|
+
names.add("check_synthesis")
|
|
87
|
+
ctx = ToolContext(state=state, autonomy="act", scope=(f"{state}-{round_no}" if state != "propose" else ""), store=store, actor=system_actor("grounding"),
|
|
88
|
+
branch=branch or f"problem/{problem.problem_id}", services=services, enabled=names,
|
|
89
|
+
egress_ok=set(egress_ok if egress_ok is not None else names), protected=set(protected or ()),
|
|
90
|
+
max_tool_calls=max_tool_calls, replay=replay, blinding=blinding)
|
|
91
|
+
task = (DECIDE_TASK.format(objective=problem.objective, results=results[:3000] or "(none)") if state == "decide"
|
|
92
|
+
else TASK.format(objective=problem.objective, context=problem.context or "-"))
|
|
93
|
+
if "predict" in names or "check_synthesis" in names:
|
|
94
|
+
task += ("\n\nYou may also run prediction tools on a structure and check whether a compound can be made. What they return are priors "
|
|
95
|
+
"with uncertainty, never evidence: a measurement is what judges a hypothesis.")
|
|
96
|
+
res = ToolLoop(model, cat, ctx, max_steps=max_steps).run(task)
|
|
97
|
+
g = Grounding(calls=[s for s in res.steps if s.get("tool")], stopped=res.stopped)
|
|
98
|
+
from proef.groundedness import loop_narrative_flags
|
|
99
|
+
g.flags = loop_narrative_flags(res.done or "", g.calls, names, [r["body"] for r in res.results], extra=task)
|
|
100
|
+
if g.flags and store is not None:
|
|
101
|
+
from proef.core.contracts import Envelope, EventType
|
|
102
|
+
from proef.core.interfaces import record_for
|
|
103
|
+
store.append(record_for(Envelope(experiment_branch_id=ctx.branch), EventType.gate_decision, system_actor("grounding"), decision={
|
|
104
|
+
"kind": "loop_flags", "advisory": True, "state": state, "scope": ctx.scope, "flags": g.flags, "summary": (res.done or "")[:300]}))
|
|
105
|
+
if res.done or g.used:
|
|
106
|
+
src = ", ".join(sorted(set(g.used))) or "no tool"
|
|
107
|
+
when = "BEFORE PROPOSING" if state == "propose" else f"AFTER ROUND {round_no}"
|
|
108
|
+
g.text = (f"BACKGROUND READ {when} (from {src}; outside information, untrusted: use it as context and as a reason, "
|
|
109
|
+
f"never as proof)\n{res.done or '(the model gave no summary)'}\n"
|
|
110
|
+
"Where a family, variant or suggestion rests on something above, name its source (a PMID or ChEMBL id) in its citation or rationale. "
|
|
111
|
+
"Where nothing above applies, propose from your own knowledge and do not invent a source.")
|
|
112
|
+
return g
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
# ---- the `ground` step: evidence for and against each family, checked against what was retrieved ----------------------------------------
|
|
116
|
+
|
|
117
|
+
GROUND_TASK = ("A research plan has proposed this family of hypotheses. Before a person reviews it, use the tools to look for: evidence that "
|
|
118
|
+
"SUPPORTS it, evidence that CONTRADICTS it, PRIOR MEASUREMENTS of its compounds, and whether the idea is ALREADY KNOWN.\n\n"
|
|
119
|
+
"FAMILY: {family}\nCLAIM: {claim}\nMECHANISM: {mechanism}\nCOMPOUNDS: {compounds}\n\n"
|
|
120
|
+
"When you have looked, reply with EXACTLY this shape, a JSON object under the key done (not a string):\n"
|
|
121
|
+
' {{"done": {{"items": [{{"kind": "{kinds}", "claim": "one sentence", '
|
|
122
|
+
'"source": "the PMID, ChEMBL id or Ensembl id of the tool result it comes from"}}]}}}}\n'
|
|
123
|
+
"Include only what you can point to in a tool result you received in this step. An item with no such source is thrown away. "
|
|
124
|
+
"If you found nothing, return an empty list: that is a useful answer. Never put a measured value or this campaign's own "
|
|
125
|
+
"identifiers in a query.")
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
COMPUTE_NOTE = ("\n\nFor a compound with a structure listed above you may also run a prediction tool on it or check whether it can be made. What they return is a PRIOR "
|
|
129
|
+
"with uncertainty, never evidence. To report one, use kind \"prior\" with the tool's name as the source (for example \"predict:admet-physchem\" or "
|
|
130
|
+
"\"check_synthesis\"); it is kept only if that tool actually returned a result in this step.")
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def _structure_of(h, cfg, tracker=None) -> tuple[str, str] | None:
|
|
134
|
+
"""(structure, where it came from) for a compound: the operator's library first (trusted), else the SMILES the model stated when it proposed the compound.
|
|
135
|
+
The model's own SMILES is a claim: it is not written onto the hypothesis (structure-keyed logic must not trust it) and is kept apart in
|
|
136
|
+
`tracker.claimed_structures`, so the task says plainly that it is the model's claim."""
|
|
137
|
+
for c in getattr(cfg, "candidates", None) or []:
|
|
138
|
+
if isinstance(c, dict) and str(c.get("sample_id") or c.get("id") or c.get("name") or "").lower() == str(h.candidate).lower() and c.get("smiles"):
|
|
139
|
+
return str(c["smiles"]), "structure"
|
|
140
|
+
claimed = (getattr(tracker, "claimed_structures", None) or {}).get(h.candidate)
|
|
141
|
+
return (str(claimed), "structure as the model stated it") if claimed else None
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def ground_families(cfg, portfolio, tracker, store, actor, say, label: str | None = None) -> dict[str, dict]:
|
|
145
|
+
"""One `propose`-style loop per family of the plan. Returns {family_id: {"items": kept, "dropped": n, "calls": n}}; every family's
|
|
146
|
+
outcome is a ledger record. Only the knowledge tools are offered. Nothing here changes a hypothesis, a verdict or an approval."""
|
|
147
|
+
from proef.core.contracts import Envelope, EventType
|
|
148
|
+
from proef.core.interfaces import record_for
|
|
149
|
+
from proef.groundedness import verify_items
|
|
150
|
+
|
|
151
|
+
info = getattr(tracker, "family_info", {}) or {}
|
|
152
|
+
pid = cfg.problem.problem_id or "unnamed"
|
|
153
|
+
by_family: dict[str, list] = {}
|
|
154
|
+
for h in portfolio:
|
|
155
|
+
by_family.setdefault(h.family or "ungrouped", []).append(h)
|
|
156
|
+
public = {n.lower() for n in getattr(cfg, "grounding_public_names", ())}
|
|
157
|
+
protected = library_secrets(cfg.candidates, public) | {pid}
|
|
158
|
+
names = {KNOWLEDGE_TOOL_NAMES[k] for k in cfg.grounding_tools}
|
|
159
|
+
out: dict[str, dict] = {}
|
|
160
|
+
for fid, hyps in by_family.items():
|
|
161
|
+
cat = ToolCatalog()
|
|
162
|
+
for k in cfg.grounding_tools:
|
|
163
|
+
cat.register(KNOWLEDGE_TOOLS[k]())
|
|
164
|
+
enabled = set(names)
|
|
165
|
+
compute = tuple(getattr(cfg, "ground_compute", ()) or ())
|
|
166
|
+
if "predict" in compute:
|
|
167
|
+
from proef.predictors import DEFAULT
|
|
168
|
+
from proef.tools import predict_tool
|
|
169
|
+
cat.register(predict_tool(getattr(cfg, "prediction_registry", None) or DEFAULT, cfg.prediction_tools, cfg.modality))
|
|
170
|
+
enabled.add("predict")
|
|
171
|
+
if "synthesis" in compute:
|
|
172
|
+
from proef.tools import synthesis_tool
|
|
173
|
+
cat.register(synthesis_tool())
|
|
174
|
+
enabled.add("check_synthesis")
|
|
175
|
+
ctx = ToolContext(state="propose", autonomy="act", store=store, actor=system_actor("grounding"), branch=f"problem/{pid}",
|
|
176
|
+
services=cfg.knowledge_services, enabled=enabled, egress_ok=set(names), protected=protected, max_tool_calls=8,
|
|
177
|
+
scope=f"ground-{label or 'initial'}-{fid}", replay=getattr(cfg, "grounding_replay", None),
|
|
178
|
+
blinding=getattr(cfg, "blinding", None))
|
|
179
|
+
f = info.get(fid, {})
|
|
180
|
+
structures = {str(h.candidate): _structure_of(h, cfg, tracker) for h in hyps}
|
|
181
|
+
listed = ", ".join(f"{n} ({structures[n][1]}: {structures[n][0][:120]})" if structures.get(n) and compute else n for n in sorted(structures))[:600]
|
|
182
|
+
task = GROUND_TASK.format(family=fid[:80], claim=str(f.get("parent_statement", ""))[:300], mechanism=str(f.get("mechanism", ""))[:300],
|
|
183
|
+
compounds=listed, kinds="supports|contradicts|prior_measurement|already_known" + ("|prior" if compute else "")) + (COMPUTE_NOTE if compute else "")
|
|
184
|
+
res = ToolLoop(cfg.model, cat, ctx, max_steps=6, done_chars=4000, done_keys=("items",)).run(task)
|
|
185
|
+
parsed = {}
|
|
186
|
+
if res.done:
|
|
187
|
+
import json
|
|
188
|
+
import re
|
|
189
|
+
m = re.search(r"\{.*\}", res.done, re.S)
|
|
190
|
+
try:
|
|
191
|
+
parsed = json.loads(m.group(0)) if m else {}
|
|
192
|
+
except ValueError:
|
|
193
|
+
parsed = {}
|
|
194
|
+
kept, dropped = verify_items(parsed.get("items") if isinstance(parsed, dict) else None, [r["body"] for r in res.results],
|
|
195
|
+
tools_called=[r["tool"] for r in res.results])
|
|
196
|
+
out[fid] = {"items": kept, "dropped": len(dropped), "calls": len(res.results), "stopped": res.stopped}
|
|
197
|
+
store.append(record_for(Envelope(experiment_branch_id=f"problem/{pid}"), EventType.gate_decision, actor, decision={
|
|
198
|
+
"kind": "grounding", "advisory": True, "family": fid, "stage": label or "initial", "items": kept, "dropped": dropped[:8],
|
|
199
|
+
"n_dropped": len(dropped), "tool_calls": len(res.results), "stopped": res.stopped}))
|
|
200
|
+
say(f"grounding: {len(out)} family(ies), {sum(len(v['items']) for v in out.values())} item(s) traced, "
|
|
201
|
+
f"{sum(v['dropped'] for v in out.values())} dropped as untraced")
|
|
202
|
+
return out
|