ryan-superman's picture
Publish trajectories and metrics (BMB content gated)
673d45d verified
Raw History Blame Contribute Delete
20.8 kB
"""The VERA agent loop: bounded state instead of transcript replay.
The one structural difference from `bmb.agent`, and the reason this module exists: the
prompt is rebuilt each step from a **bounded rendering of the analysis graph** plus the
single most recent tool output, rather than from the whole transcript. Measured on
BioMysteryBench, transcript replay costs 9,267 tokens per step to deliver ~400 tokens of
new content; at a 4k state budget the same token spend buys roughly four times the steps.
Everything else is deliberately reused from the existing harness -- workspace staging,
`run_bash`, the `Attempt` record and its status taxonomy -- so a VERA row and a baseline
row differ in the loop and nothing else, and remain directly comparable.
"""
from __future__ import annotations
import json
import re
import time
import urllib.error
import urllib.request
from typing import Sequence
from pathlib import Path
from bmb.codex_backend import Attempt, emission_is_malformed, extract_answer, strip_reasoning
from bmb.problems import Problem, RULES
from bmb.sandbox import Workspace, run_bash
from vera.checks import rho
from vera.protocol import parse_emission, run_checks
from vera.state import AnalysisState, Node
PROTOCOL = """Work in your current directory. Each turn, emit exactly one block:
<command>SHELL COMMAND TO RUN</command>
When a command has established a finding, add a NODE line and its CHECK lines:
NODE kind=KIND summary="WHAT YOU ESTABLISHED" artifact=FILE parents=n1,n2
CHECK CHECKKIND "WHAT MUST BE TRUE" :: ONE-LINE COMMAND PRINTING True OR False
kind is one of: load, qc, transform, test, interpret, answer.
CHECKKIND is one of: conservation, range, invariance, type.
Everything after :: is your check command, taken verbatim to the end of the line, so
quotes, < and > inside it are safe. Each CHECK must be ONE line -- if you need a
multi-line script, write it to a file in <command> and have the CHECK run that file.
CHECKS ARE RUN BY THE HARNESS, NOT TAKEN ON YOUR WORD. A check must print exactly True
or False as its LAST line. Printing a number, a sequence or a path is malformed and will
be rejected -- write a comparison, not a measurement:
WRONG CHECK range "n reads" :: grep -c '^>' reads.fasta
RIGHT CHECK range "n reads" :: test $(grep -c '^>' reads.fasta) -eq 1042 && echo True || echo False
WRONG CHECK type "sequence" :: python3 -c "print(seq[:50])"
RIGHT CHECK type "starts with ATG" :: python3 -c "print(open('g.fa').readlines()[1].startswith('ATG'))"
Use REAL filenames from your working directory -- never the placeholder word "file".
A STRONG check states an invariant that would FAIL if your analysis were wrong: a total
preserved across a filter, an estimate stable across two subsamples, a value inside its
admissible range. A check that passes no matter what the data says (a file existing, a
tool being installed) is worth nothing and will be scored as worthless.
Your summary is the ONLY thing you will see about this step later -- state the finding
("14,203 of 34,460 cells pass QC"), not the activity ("ran QC"). Do not re-declare a
node you have already recorded.
When you are certain, end a turn with:
FINAL ANSWER: <answer>"""
_COMMANDISH = re.compile(
r"^\s*(?:\$\s*)?(?:ls|cd|cat|head|tail|wc|awk|sed|grep|zcat|gzip|sort|uniq|cut|echo"
r"|python3?|Rscript|conda|pip|samtools|bcftools|blastn|makeblastdb|find|for|while|if)\b"
r"|[|>]\s*\S|&&|\$\(", re.I)
def looks_like_a_command(text: str) -> bool:
"""True if `text` is a shell command rather than an answer to the question.
The forced-answer phase made this necessary. Asked to commit, the model sometimes
replies with the next command it wanted to run, and a naive extractor files that as
the final answer -- turning a run that would have been *excluded* into one that is
*confidently wrong*, which is strictly worse. Observed verbatim:
``awk -F'\t' 'NR>1{print $2}' alcohol.txt | head -5``.
"""
return bool(_COMMANDISH.search(text or ""))
# Fragments that are the scaffolding of an answer rather than an answer. Seen when a
# prefilled continuation comes back empty: the recorded answer was the literal string
# "FINAL ANSWER:", which passed a naive length check and would have been graded as a
# wrong answer instead of an honest exclusion.
_NON_ANSWERS = {"final answer", "final answer:", "answer", "answer:", "n/a", "na",
"unknown", "none", "tbd", "...", "-"}
_TRAILING_MARKUP = re.compile(r"(?:</?(?:command|node|check|think|tool_call)\s*/?>|```+)\s*$",
re.I)
def strip_markup(text: str) -> str:
"""Remove protocol tags and fences the model leaves attached to an answer.
Observed in a real run: the graded answer was ``'Norovirus GII</command>'``. That one
happened to be judged correct, but only by luck -- an answer carrying a closing tag is
a string the grader was never meant to see, and for an exact-match rubric it would
fail. Applied repeatedly, since models stack them (``X</command>```).
"""
out = (text or "").strip()
for _ in range(4):
new = _TRAILING_MARKUP.sub("", out).strip()
if new == out:
break
out = new
return out
def answer_is_usable(text: str) -> bool:
"""Whether an extracted answer may be recorded as the run's conclusion.
Rejects three things, each observed in a real run: a shell command (the model replied
with its next action), an empty or stub emission, and the answer *prefix* itself left
over from a prefill whose continuation was empty.
"""
text = strip_markup(text)
if len(text) < 3 or emission_is_malformed(text):
return False
stripped = text.lower().strip().rstrip(":.").strip()
if stripped in _NON_ANSWERS or not any(c.isalnum() for c in text):
return False
# A prefilled emission that only echoes the prefix carries no content.
if stripped.startswith("final answer") and len(stripped) < len("final answer") + 3:
return False
return not looks_like_a_command(text)
ANSWER_PREFIX = "FINAL ANSWER:"
def _chat(base_url: str, model: str, prompt: str, *, timeout: int, max_tokens: int = 2048,
prefill: str = "") -> str:
"""Call an OpenAI-compatible /chat/completions endpoint and return the message text.
Args:
base_url: Endpoint root, e.g. ``http://host:8404/v1``.
model: Served model id.
prompt: The user turn.
timeout: Wall clock, seconds.
max_tokens: Completion cap.
prefill: If given, the assistant turn is *started* with this text and the model
continues it. This is not a stylistic preference. Asked in plain language to
reply with a single ``FINAL ANSWER:`` line, BigBang-v1 instead emitted
``I need to identify the bacterium ... <tool_call> </think>`` -- it kept
trying to act, so nothing was extractable and the run was recorded as
max_steps with no answer. Prefilling removes the need for compliance: the
model has already "said" the prefix and can only continue it.
Returns:
The message text, with `prefill` prepended so callers see a complete emission.
Raises:
RuntimeError: On a transport error or a malformed response, so the caller can
record a `provider` status rather than mistaking it for a bad answer.
"""
messages = [{"role": "user", "content": prompt}]
payload = {
"model": model,
"messages": messages,
"max_tokens": max_tokens,
"temperature": 0.0,
}
if prefill:
messages.append({"role": "assistant", "content": prefill})
# vLLM extensions: continue the assistant turn rather than starting a new one.
payload["continue_final_message"] = True
payload["add_generation_prompt"] = False
body = json.dumps(payload).encode()
req = urllib.request.Request(
base_url.rstrip("/") + "/chat/completions", data=body,
headers={"Content-Type": "application/json", "Authorization": "Bearer local"},
)
try:
with urllib.request.urlopen(req, timeout=timeout) as resp:
payload_out = json.loads(resp.read().decode(errors="replace"))
except (urllib.error.URLError, TimeoutError, json.JSONDecodeError) as exc:
raise RuntimeError(f"chat call failed: {exc}") from exc
try:
text = payload_out["choices"][0]["message"]["content"] or ""
except (KeyError, IndexError) as exc:
raise RuntimeError(f"malformed chat response: {str(payload_out)[:200]}") from exc
return (prefill + text) if prefill else text
FORCE_ANSWER_RESERVE = 3
def build_forced_prompt(problem: Problem, state: AnalysisState, *, state_budget: int,
reason: str) -> str:
"""Demand a final answer from the analysis so far, with no further commands.
Exists because of the single largest measured loss: on the 73-problem baseline,
**22 of 73 problems (30%) produced no usable answer at all** -- 12 excluded for
exhausting the budget and 10 graded on an empty or stub emission. Those runs had done
the analysis; they simply never committed to a conclusion. A budget that ends without
asking for one converts work already done into a zero.
"""
return "\n".join([
problem.question, "",
"=== YOUR ANALYSIS ===", state.render(state_budget), "",
f"STOP INVESTIGATING. {reason}",
"Give your single best answer from the analysis above, even if you are not "
"certain -- an uncertain answer scores better than none, and no further commands "
"will be run.",
"",
"Reply with exactly one line and nothing else:",
"FINAL ANSWER: <answer>",
])
RECENT_WINDOW = 4
# Total characters the recent window may occupy. Without a cap the window carried four
# tool outputs at `sandbox.MAX_OUTPUT_CHARS` (20k) each, so a step prompt could reach
# ~324 KB -- large enough that the CLI shim returned HTTP 500 (the prompt is passed as a
# command-line argument) and 68 of 70 problems died as provider timeouts. A method whose
# claim is bounded context has no business sending unbounded prompts.
WINDOW_CHARS = 12_000
def _clip_middle(text: str, budget: int) -> str:
"""Trim to `budget` chars keeping both ends.
The head carries what a command produced; the tail carries any traceback. Cutting
either loses the reason the step happened.
"""
text = text or ""
if budget <= 0:
return ""
if len(text) <= budget:
return text
half = max(1, (budget - 40) // 2)
return f"{text[:half]}\n...[{len(text) - 2 * half} chars elided]...\n{text[-half:]}"
def build_step_prompt(problem: Problem, workspace: Path, state: AnalysisState,
recent: Sequence[tuple[str, str]], *, state_budget: int,
nudge: str = "", window: int = RECENT_WINDOW) -> str:
"""Assemble one step's prompt: task, bounded state, and a window of recent history.
Cost is still O(B + window) rather than O(T), so the quadratic blow-up is gone --
but the window is not optional. A first version passed only the state graph plus the
single latest tool output, and it scored 17.6% against the baseline's 37.7%: the
model repeatedly answered "cannot determine from the provided analysis logs", because
node summaries written by the model are lossy and drop the concrete handles
(filenames, column labels, sample ids) the next step needs.
The lesson is that summarisation is not free. Compressing *old* context is affordable;
compressing recent context destroys the analysis.
"""
listing = "\n".join(f"- {Path(n).name}" for n in problem.data_members)
parts = [
problem.question, "", RULES, "",
f"Data files in {workspace}:\n{listing}", "",
PROTOCOL, "",
"=== ANALYSIS SO FAR ===", state.render(state_budget), "",
]
tail = list(recent)[-window:]
if tail:
parts.append("=== YOUR LAST %d COMMANDS AND THEIR OUTPUT ===" % len(tail))
# Spend the window budget newest-first: the latest output is what the next action
# builds on, and older ones are already summarised in the analysis graph.
rendered: list[str] = []
left = WINDOW_CHARS
for cmd, out in reversed(tail):
share = max(600, left // 2) if len(rendered) < 2 * (len(tail) - 1) else left
block = f"$ {cmd}\n{_clip_middle(out, min(share, left))}\n"
if left <= 0:
break
rendered.append(block[:left])
left -= len(block)
parts += list(reversed(rendered))
if nudge:
parts += [f"NOTE: {nudge}", ""]
parts.append("Emit your next block.")
return "\n".join(parts)
def run_vera_attempt(
problem: Problem,
model: str,
base_url: str,
*,
max_steps: int = 50,
state_budget: int = 4000,
step_timeout: int = 900,
chat_timeout: int = 600,
workspace_root: Path | None = None,
transcript_dir: Path | None = None,
) -> Attempt:
"""Run one attempt under VERA and return it ungraded.
Args:
problem: The problem to pose.
model: Model id served at `base_url`.
base_url: OpenAI-compatible endpoint, e.g. ``http://host:8404/v1``.
max_steps: Step ceiling. Defaults to 50 rather than 25 because the point of the
bounded state is to make that affordable.
state_budget: Tokens allowed for the rendered analysis graph.
step_timeout: Per-shell-command wall clock, seconds.
chat_timeout: Per-model-call wall clock, seconds.
workspace_root: Parent for the scratch workspace.
transcript_dir: Where to persist the run, including the final graph.
Returns:
An `Attempt` with the baseline status taxonomy, plus `extra` carrying the
cumulative verification reward, the node count and the mean node rho.
"""
started = time.time()
att = Attempt(problem_id=problem.id, model=f"vera:{model}", status="ok",
human_solvable=problem.human_solvable)
state = AnalysisState()
total_reward = 0.0
log: list[str] = []
with Workspace(problem, root=workspace_root, keep=False) as ws:
assert ws.path is not None
out_dir = Path(transcript_dir).resolve() if transcript_dir else None
if out_dir:
out_dir.mkdir(parents=True, exist_ok=True)
att.transcript_dir = str(out_dir)
recent: list[tuple[str, str]] = []
nudge, step = "", 0
rejections: dict[str, int] = {}
while step < max_steps:
step += 1
forcing = step > max_steps - FORCE_ANSWER_RESERVE
if forcing:
prompt = build_forced_prompt(
problem, state, state_budget=state_budget,
reason=f"You have used {step - 1} of {max_steps} steps.")
else:
prompt = build_step_prompt(problem, ws.path, state, recent,
state_budget=state_budget, nudge=nudge)
nudge = ""
try:
reply = _chat(base_url, model, prompt, timeout=chat_timeout,
prefill=ANSWER_PREFIX + " " if forcing else "")
except RuntimeError as exc:
att.status, att.error = "provider", str(exc)
break
log.append(f"--- step {step} ---\n{reply}\n")
if forcing:
# No commands, no nodes -- only a commitment. Reasoning is stripped first
# because a model that writes "FINAL ANSWER:" inside a think block would
# otherwise have its reasoning mined as the answer.
candidate = extract_answer(strip_reasoning(reply))
if answer_is_usable(candidate):
att.answer, att.status = strip_markup(candidate), "ok"
break
nudge = ("your reply was not an answer. Do not emit a shell command. "
"Name the organism, gene, cell type or value the question asks for.")
continue
emission = parse_emission(reply)
if emission.error:
nudge = f"your last turn was rejected: {emission.error}"
last_output = ""
continue
if emission.command:
res = run_bash(ws.path, emission.command, timeout=step_timeout)
out = res.as_tool_output()
recent.append((emission.command, out))
log.append(f"$ {emission.command}\n{out}\n")
if emission.declares_node:
results = run_checks(emission.checks, ws.path, run_bash)
malformed = [r for r in results if "no boolean verdict" in r.detail]
# A check that printed a measurement rather than a verdict is a protocol
# error, not evidence about the analysis. Scoring it would make rho a
# compliance metric. Ask once for a rewrite; if the model repeats itself,
# accept the failure so a non-complying model cannot stall the run.
if malformed and rejections.get(emission.summary, 0) < 1:
rejections[emission.summary] = rejections.get(emission.summary, 0) + 1
bad = malformed[0]
nudge = (f"check {bad.name!r} printed a measurement, not a verdict "
f"({bad.detail}). Rewrite it as a comparison ending in "
f"True or False, using real filenames, then re-declare the node.")
continue
node = Node(
id=f"n{len(state) + 1}", kind=emission.kind,
summary=emission.summary or "(no summary given)",
artifact=emission.artifact,
parents=tuple(p for p in emission.parents if p in state),
command=emission.command, checks=results,
)
state.add(node)
total_reward += state.reward([node])
log.append(f"[node {node.id}] rho={node.rho:.2f} "
f"({sum(c.passed for c in results)}/{len(results)} checks)\n")
if emission.answer:
# Emission gate: 29% of baseline errors were emission failures, so an
# answer is only released if the analysis behind it verified.
leaves = state.leaves()
gate = rho([c for n in leaves for c in n.checks]) if leaves else 0.0
if gate == 0.0 and step <= max_steps - FORCE_ANSWER_RESERVE and state:
nudge = ("your answer was withheld: no leaf node has a passing check. "
"Add a check that verifies the result you are about to report.")
continue
att.answer = strip_markup(emission.answer)
att.status = "ok"
break
else:
# The budget ran out without a commitment. Ask once more, outside the loop:
# this is exactly the case that produced 12 of the 73 baseline exclusions.
try:
reply = _chat(base_url, model, build_forced_prompt(
problem, state, state_budget=state_budget,
reason="Your step budget is exhausted."), timeout=chat_timeout,
prefill=ANSWER_PREFIX + " ")
candidate = extract_answer(strip_reasoning(reply))
except RuntimeError:
candidate = ""
if answer_is_usable(candidate):
att.answer, att.status = strip_markup(candidate), "ok"
att.extra["answer_forced"] = True
else:
att.status = "max_steps"
att.error = f"no answer within {max_steps} steps"
att.n_steps = step
nodes = state.nodes
att.extra.update({
"verification_reward": round(total_reward, 3),
"n_nodes": len(nodes),
"mean_rho": round(sum(n.rho for n in nodes) / len(nodes), 3) if nodes else 0.0,
"n_checks": sum(len(n.checks) for n in nodes),
})
if out_dir:
(out_dir / "transcript.txt").write_text("\n".join(log))
(out_dir / "graph.txt").write_text(state.render(1_000_000))
(out_dir / "final_answer.txt").write_text(att.answer or "")
if att.status == "ok" and not att.answer:
att.status, att.error = "format", "loop ended with no answer"
att.wall_s = time.time() - started
return att