spiderpilot89's picture
protocol company
Release v0.15.3 free evaluation sample
fd8b1ae
Raw History Blame Contribute Delete
9.8 kB
"""An agent with no model in it: answer every environment from its reference, through the harness proxy.
python3 run_reference.py --engine ENGINE --environments F --out DIR [--only id,id] [--direct]
For a tradeoff or chain_design environment it sends the reference passing and failing runs to the
verifier, hands each run to its solve through the task's coupling where the task has one, and writes
the card with the seals this verifier gives. For a budget environment it sends the two reference
requests. For a forensics table it puts the table to the verifier (each row's request as sent, up to
the task's budget) and names the false rows the build recorded.
Every call goes through harness/mcp_log_proxy.py, started in an empty working folder, so the
authoritative call record is DIR/<id>.harness.jsonl, as in a pass@k attempt. The same calls are also
written beside the reply, DIR/<id>.calls.jsonl. --direct talks to ENGINE with no proxy and writes the
reply-side log only.
python3 score.py DIR --engine ENGINE --environments F --calls-from harness
Licence: Apache-2.0.
"""
import argparse
import copy
import json
import os
import subprocess
import sys
import tempfile
HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, HERE)
import chainlib # noqa: E402
from score import (FREE_TOOLS, NOT_STOPPED, build_stage_request, close_verifier, continuation_of, design_shape, # noqa: E402
file_sha256, get_path, load_environments, open_verifier)
from ztp_mcp import McpError, StdioVerifier # noqa: E402
PROXY = os.path.join(HERE, "..", "harness", "mcp_log_proxy.py")
class ProxiedVerifier(StdioVerifier):
"""The engine behind the logging proxy, the proxy started in its own empty working folder."""
def __init__(self, engine, log, cwd=None, **kwargs):
self.cwd = cwd or tempfile.mkdtemp(prefix="ztp_ref_cwd_")
if engine.startswith("http://") or engine.startswith("https://"):
# an MCP address: the proxy runs the stdio bridge to it (ztp_open_bridge.py, beside this file)
child = [sys.executable, os.path.join(HERE, "ztp_open_bridge.py"), engine]
else:
child = [os.path.abspath(engine)]
command = [sys.executable, os.path.abspath(PROXY), "--log", os.path.abspath(log), "--"] + child
super(StdioVerifier, self).__init__(url="stdio: " + " ".join(command), timeout_s=600, **kwargs)
self.proc = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, cwd=self.cwd)
self.binary_sha256 = None if len(child) > 1 else file_sha256(engine)
def close(self):
try:
self.proc.stdin.close()
except OSError:
pass
try:
self.proc.wait(timeout=60)
except subprocess.TimeoutExpired:
self.proc.kill()
def proxied(engine, log, cwd=None):
if os.path.exists(log):
os.remove(log)
verifier = ProxiedVerifier(engine, log, cwd)
try:
verifier.connect()
except McpError as problem:
sys.exit("the proxied verifier failed: %s" % problem)
return verifier
class Logged:
def __init__(self, verifier):
self.verifier, self.calls, self.seen = verifier, [], {}
def call(self, tool, arguments, refused_ok=False):
# the same request twice is one call: a chain with its value in the next run has one first run for both designs
key = json.dumps([tool, arguments], sort_keys=True)
if key in self.seen and not self.seen[key][1]:
return self.seen[key][0]
self.calls.append({"tool": tool, "arguments": arguments})
body, is_error = self.verifier.call_json(tool, arguments)
self.seen[key] = (body, is_error)
if is_error and not refused_ok:
raise SystemExit("the reference request was refused: %s %s" % (tool, str(body)[:300]))
return body
def design_staged(env, ref, agent):
"""A staged design: each stage sent in order, handed values and continuations built from this verifier's answers."""
spec = env["check"]["design"]
answers, requests, out = {}, {}, {}
for stage in spec["stages"]:
q = build_stage_request(spec, stage, ref["x"], answers, requests)
body = agent.call(stage["tool"], q, refused_ok=True)
stopped = body.get("outcome") not in NOT_STOPPED
answers[stage["key"]] = {"body": body, "proof": body.get("run_seal") or body.get("solution_seal"),
"outcome": body.get("outcome"), "stop": body.get("reject") if stopped else None, "stopped": stopped}
requests[stage["key"]] = q
out[stage["key"]] = {"request": {"tool": stage["tool"], "arguments": q}, "proof": answers[stage["key"]]["proof"]}
return out
def design(env, ref, agent):
spec = env["check"]["design"]
shape = design_shape(spec)
if shape == "staged":
return design_staged(env, ref, agent)
if shape == "solve":
solved = agent.call("solve", ref["solve"], refused_ok=True)
return {"solve": {"request": {"tool": "solve", "arguments": ref["solve"]}, "proof": solved["solution_seal"]}}
run_args = ref["run"]
run = agent.call("run_trajectory", run_args)
out = {"run": {"request": {"tool": "run_trajectory", "arguments": run_args}, "proof": run["run_seal"]}}
if shape == "continued":
# the run that continues this design's own sealed run: the reference's next run, its start fields and from
# set from this verifier's answer to the first run
_, carried, _, _ = continuation_of(spec)
next_args = copy.deepcopy(ref["next"])
next_args["initial"] = {name: get_path(run, source) for name, source in carried.items()}
next_args["from"] = {"request": run_args, "run_seal": run["run_seal"]}
nxt = agent.call("run_trajectory", next_args, refused_ok=True)
out["next"] = {"request": {"tool": "run_trajectory", "arguments": next_args}, "proof": nxt["run_seal"]}
elif spec.get("chain"):
overrides = {}
if spec["variable"]["kind"] == "path" and spec["variable"].get("on") == "solve":
overrides[spec["variable"]["path"].split(".", 1)[1]] = ref["x"]
solve_args = chainlib.chained_solve(spec["chain"], run_args, run, overrides)
solved = agent.call("solve", solve_args)
out["solve"] = {"request": {"tool": "solve", "arguments": solve_args}, "proof": solved["solution_seal"]}
return out
def reference_reply(env, verifier):
"""(reply text, calls [{"tool", "arguments"}])."""
agent = Logged(verifier)
family, ref = env["family"], env["reference"]
if family in ("tradeoff", "chain_design"):
card = {"passing": design(env, ref["passing"], agent), "failing": design(env, ref["failing"], agent), "binding": ref["binding"]}
if ref["failing"].get("stopped"):
card["failing"]["stopped"] = ref["failing"]["stopped"]
if ref["failing"].get("steps_landed") is not None:
card["failing"]["step"] = ref["failing"]["steps_landed"]
words = "The boundary lies between the two designs below; %s binds." % ref["binding"]
elif family == "budget":
card = {}
for side in ("holds", "stops"):
request = ref[side]["request"]
answer = agent.call(request["tool"], request["arguments"])
card[side] = {"request": request, "proof": answer.get("run_seal") or answer.get("solution_seal")}
card["stops"]["stopped"] = env["check"]["stop"]
words = "The stop %s lies between the two requests below." % env["check"]["stop"]
else:
agent.call("list_cards", {}, refused_ok=True)
rows = env["check"]["rows"]
budget = env["check"].get("budget") or len(rows)
computing = 0
for row in rows:
request = row["request"]
if computing >= budget:
break
if request["tool"] in FREE_TOOLS:
continue
agent.call(request["tool"], request["arguments"], refused_ok=True)
computing += 1
card = {"false_rows": ref["false_rows"]}
words = "%d of the %d rows are false." % (len(ref["false_rows"]), len(rows))
return words + "\n\n" + json.dumps(card), agent.calls
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--engine", required=True)
parser.add_argument("--environments", required=True)
parser.add_argument("--out", required=True)
parser.add_argument("--only")
parser.add_argument("--direct", action="store_true", help="no proxy: the reply-side log only")
args = parser.parse_args()
environments = load_environments(args.environments)
if args.only:
wanted = set(args.only.split(","))
environments = [e for e in environments if e["id"] in wanted]
os.makedirs(args.out, exist_ok=True)
shared = open_verifier(args.engine) if args.direct else None
try:
for env in environments:
verifier = shared or proxied(args.engine, os.path.join(args.out, env["id"] + ".harness.jsonl"))
try:
reply, calls = reference_reply(env, verifier)
finally:
if not shared:
close_verifier(verifier)
with open(os.path.join(args.out, env["id"] + ".txt"), "w", encoding="utf-8") as f:
f.write(reply + "\n")
with open(os.path.join(args.out, env["id"] + ".calls.jsonl"), "w", encoding="utf-8") as f:
for c in calls:
f.write(json.dumps(c) + "\n")
print("%-60s %d calls" % (env["id"], len(calls)), flush=True)
finally:
if shared:
close_verifier(shared)
if __name__ == "__main__":
main()