Lecture 0 — The Pantheon+ fit with OpenCode¶
Multi-Agent Systems for Science · Boris Bolliet, University of Cambridge
We give OpenCode the Pantheon+ fitting task twice. Its build agent can read and write files, run commands and consult a reviewer subagent. The prompt requires that review. We compare the results with an independent fit and read calls, time and cost from the session records.
Setup¶
Set GOOGLE_API_KEY as a Colab secret or an environment variable before starting Jupyter.
The setup cell uses npm to install OpenCode 1.19.5 in opencode/, unless that version is already available. A local environment needs Node.js and npm.
For tracing, set LANGFUSE_PUBLIC_KEY, LANGFUSE_SECRET_KEY and LANGFUSE_BASE_URL from your Langfuse project. The OpenCode plugin records model and tool calls, including the reviewer's work. The server receives prompts, scripts and outputs.
Each run has fresh working and configuration directories and a time limit. Permission rules restrict commands and file tools, but generated code can still access your files and inherited credentials. Use Colab or a container to isolate the work.
%pip install -q numpy scipy pandas matplotlib
Note: you may need to restart the kernel to use updated packages.
%matplotlib inline
import json, os, platform, re, shutil, subprocess, sys, tempfile, time, urllib.request, warnings
from datetime import datetime, timezone
from importlib.metadata import version
from pathlib import Path
warnings.filterwarnings("ignore", category=SyntaxWarning) # emitted by google-genai when it is first compiled
import numpy as np
import pandas as pd
from IPython.display import display
from scipy.integrate import cumulative_trapezoid
from scipy.linalg import cho_factor, cho_solve
from scipy.optimize import brentq, minimize_scalar
pd.set_option("display.width", 160)
pd.set_option("display.max_columns", 30)
RESULTS_DIR = Path("results/table3")
RESULTS_DIR.mkdir(parents=True, exist_ok=True)
def installed(package):
try:
return version(package)
except Exception:
return None
OPENCODE_VERSION = "1.19.5"
OPENCODE_DIR = Path(os.environ.get("OPENCODE_DIR", "opencode")).resolve()
def opencode_version(binary):
try:
return subprocess.run([str(binary), "--version"], capture_output=True, text=True, timeout=60).stdout.strip()
except (OSError, subprocess.SubprocessError):
return None
candidates = [OPENCODE_DIR / "node_modules/.bin/opencode", shutil.which("opencode")]
OC = next((Path(c) for c in candidates if c and opencode_version(c) == OPENCODE_VERSION), None)
if OC is None:
assert shutil.which("npm"), "OpenCode is installed with npm, which needs Node.js."
subprocess.run(["npm", "install", "--prefix", str(OPENCODE_DIR), "--no-audit", "--no-fund", "--loglevel=error",
f"opencode-ai@{OPENCODE_VERSION}"], check=True)
OC = OPENCODE_DIR / "node_modules/.bin/opencode"
VERSIONS = {"python": platform.python_version(), "opencode": opencode_version(OC)} | {
p: installed(p) for p in ["numpy", "scipy", "pandas"]}
print(VERSIONS)
{'python': '3.12.12', 'opencode': '1.19.5', 'numpy': '2.5.4', 'scipy': '1.18.1', 'pandas': '3.1.1'}
The helper cell below prepares each run's sandbox, starts and stops the OpenCode server, exports the sessions and reads calls, tokens, cost and session time from them.
# @title Helpers: sandbox, server and session export { display-mode: "form" }
import ast, contextlib, socket
from collections import Counter
SANDBOX_FLAGS = {"OPENCODE_DISABLE_AUTOUPDATE": "1", "OPENCODE_DISABLE_CLAUDE_CODE": "1",
"OPENCODE_DISABLE_EXTERNAL_SKILLS": "1", "OPENCODE_DISABLE_LSP_DOWNLOAD": "1",
"OPENCODE_DISABLE_MODELS_FETCH": "1", "PIP_NO_INDEX": "1", "MPLBACKEND": "Agg", "TERM": "dumb"}
def sandbox(config, reviewer):
# A fresh working directory outside the home folder (data, task.md, opencode.json, the reviewer) and a fresh
# home directory. The environment holds PATH, the home and XDG directories and the flags above, and no keys.
work, home = new_workdir("l01_oc_"), Path(tempfile.mkdtemp(prefix="l01_oc_home_"))
xdg = {"XDG_CONFIG_HOME": home / ".config", "XDG_DATA_HOME": home / ".local/share",
"XDG_STATE_HOME": home / ".local/state", "XDG_CACHE_HOME": home / ".cache"}
for path in xdg.values():
path.mkdir(parents=True)
(work / "task.md").write_text(TASK + "\n")
(work / "opencode.json").write_text(json.dumps(config, indent=1) + "\n")
(work / ".opencode/agents").mkdir(parents=True)
(work / ".opencode/agents/reviewer.md").write_text(reviewer + "\n")
env = {"PATH": os.pathsep.join([str(Path(sys.executable).parent), "/usr/local/bin", "/usr/bin", "/bin"]),
"HOME": str(home), **{name: str(path) for name, path in xdg.items()}, **SANDBOX_FLAGS}
return work, home, env
def free_port():
with socket.socket() as probe:
probe.bind(("127.0.0.1", 0))
return probe.getsockname()[1]
@contextlib.contextmanager
def opencode_server(work, home, env):
# `opencode serve` on a free local port; only the server receives the keys. The Langfuse plugin runs in the
# server and sends its spans when the session goes idle, so the server stays up 15 s longer when tracing.
keys = {"GOOGLE_GENERATIVE_AI_API_KEY": GOOGLE_API_KEY} | (LANGFUSE | {"LANGFUSE_FLUSH_AT": "1"} if TRACED else {})
port = free_port()
url = f"http://127.0.0.1:{port}"
with open(home / "server.log", "w") as log:
server = subprocess.Popen([str(OC), "serve", "--port", str(port), "--hostname", "127.0.0.1", "--print-logs"],
cwd=work, env=env | keys, stdin=subprocess.DEVNULL, stdout=log, stderr=subprocess.STDOUT)
try:
for _ in range(240): # wait until the server answers
try:
urllib.request.urlopen(url + "/config", timeout=2)
break
except OSError:
time.sleep(0.5)
yield url
if TRACED:
time.sleep(15)
finally:
server.terminate()
try:
server.wait(timeout=30)
except subprocess.TimeoutExpired:
server.kill()
def opencode(args, work, env, **kwargs):
return subprocess.run([str(OC), *args], cwd=work, env=env, stdin=subprocess.DEVNULL, **kwargs)
def export_sessions(work, home, env):
# The root session, then the child sessions that its export names, each written to a file:
# OpenCode truncates a large export written to a pipe.
listed = opencode(["session", "list", "--format", "json"], work, env, capture_output=True, text=True, timeout=120).stdout
queue, exports = sorted(set(re.findall(r"ses_[A-Za-z0-9]+", listed))), {}
while queue:
sid = queue.pop(0)
if sid in exports:
continue
target = home / f"export_{sid}.json"
with open(target, "w") as handle:
opencode(["export", sid], work, env, stdout=handle, stderr=subprocess.DEVNULL, timeout=120)
text = target.read_text()
exports[sid] = json.loads(text[text.find("{"):])
queue += sorted(set(re.findall(r"ses_[A-Za-z0-9]+", text)) - set(exports))
return exports
def parse_tagged(text, tag):
for candidate in reversed(re.findall(re.escape(tag) + r"\W*?(\{[^{}]*\})", text or "", flags=re.S)):
for parse in (json.loads, ast.literal_eval):
try:
return parse(candidate)
except (ValueError, SyntaxError):
pass
return None
def number(value):
try:
return float(value)
except (TypeError, ValueError):
return None
def measure(exports):
# Model calls (one assistant message per call), tokens, tools, OpenCode's cost and the session time.
calls, tokens, tools, times, cost = Counter(), Counter(), Counter(), [], 0.0
for export in exports.values():
for message in export.get("messages", []):
info = message["info"]
times += [t for t in ((info.get("time") or {}).get("created"), (info.get("time") or {}).get("completed")) if t]
if info.get("role") != "assistant":
continue
calls[info.get("agent") or "?"] += 1
cost += info.get("cost") or 0
used = info.get("tokens") or {}
tokens.update({"input": used.get("input", 0), "cache_read": (used.get("cache") or {}).get("read", 0),
"output": used.get("output", 0), "reasoning": used.get("reasoning", 0)})
tools.update(part.get("tool") for part in message.get("parts", []) if part.get("type") == "tool")
return {"calls": sum(calls.values()), "calls_by_agent": dict(calls), "sessions": len(exports),
"tokens": dict(tokens), "tools": dict(tools), "cost_usd": round(cost, 5),
"time_s": round((max(times) - min(times)) / 1000, 1) if times else None}
def record(i, work, home, env, status, process_time):
# The record of run i: the FINAL line of report.md, the root session and the measures of all its sessions.
exports = export_sessions(work, home, env)
report = (work / "report.md").read_text() if (work / "report.md").exists() else ""
final = parse_tagged(report, "FINAL") or {}
root = next((sid for sid, export in exports.items() if not export["info"].get("parentID")), None)
return {"run": i, "status": status, "omega_m": number(final.get("omega_m")), "omega_m_err": number(final.get("omega_m_err")),
"n_sn": final.get("n_sn"), "covariance_reported": final.get("covariance"), "process_time_s": process_time,
"scripts": sorted(p.name for p in work.glob("*.py")), "root_session": root,
**measure(exports), "work_dir": work, "home_dir": home}
Model and run settings¶
OpenCode uses the form provider/model. We set gemini-3.1-flash-lite for the build agent, reviewer and session-title model.
ORGANISATION = "OpenCode build agent with a reviewer subagent"
MODEL = "google/gemini-3.1-flash-lite"
RUNS = 2
RUN_TIMEOUT = 1200 # seconds allowed to one run
PLUGIN = "@langfuse/opencode-observability-plugin@0.7.0"
def secret(name):
# A Colab secret if one exists, else an environment variable, else None.
try:
from google.colab import userdata
try:
return userdata.get(name)
except Exception:
return os.environ.get(name)
except ImportError:
return os.environ.get(name)
GOOGLE_API_KEY = secret("GOOGLE_API_KEY") or ""
assert GOOGLE_API_KEY, "Set GOOGLE_API_KEY as a Colab secret or as an environment variable."
os.environ["GOOGLE_API_KEY"] = GOOGLE_API_KEY
os.environ.pop("GEMINI_API_KEY", None) # the client prints a notice when both variables are set
LANGFUSE = {name: secret(name) for name in ("LANGFUSE_PUBLIC_KEY", "LANGFUSE_SECRET_KEY", "LANGFUSE_BASE_URL")}
TRACED = all(LANGFUSE.values())
print("Langfuse tracing:", "on" if TRACED else "off")
if TRACED: # wrong keys or URL: the traces would be lost silently
import base64
token = base64.b64encode(f"{LANGFUSE['LANGFUSE_PUBLIC_KEY']}:{LANGFUSE['LANGFUSE_SECRET_KEY']}".encode()).decode()
try:
urllib.request.urlopen(urllib.request.Request(LANGFUSE["LANGFUSE_BASE_URL"].rstrip("/") + "/api/public/projects",
headers={"Authorization": f"Basic {token}"}), timeout=60)
except Exception as error:
TRACED = False
print("Langfuse check failed:", type(error).__name__)
print("Langfuse keys accepted:", TRACED)
Langfuse tracing: on Langfuse keys accepted: True
1. Data¶
Pantheon+ contains 1701 light curves of Type Ia supernovae from 18 surveys (Scolnic et al. 2022; Brout et al. 2022). Some supernovae have more than one light curve.
We use zHD for the Hubble-diagram redshift, zHEL for the heliocentric redshift, and m_b_corr for the standardised peak magnitude. The full statistical and systematic covariance is in Pantheon+SH0ES_STAT+SYS.cov. We cache both files in data/ and select rows with \(z_\mathrm{HD}>0.01\).
DATA_URL = "https://raw.githubusercontent.com/PantheonPlusSH0ES/DataRelease/main/Pantheon%2B_Data/4_DISTANCES_AND_COVAR/"
DATA_DIR = Path("data")
DATA_DIR.mkdir(exist_ok=True)
TABLE_PATH = (DATA_DIR / "Pantheon+SH0ES.dat").resolve()
COV_PATH = (DATA_DIR / "Pantheon+SH0ES_STAT+SYS.cov").resolve()
for path, remote in [(TABLE_PATH, "Pantheon%2BSH0ES.dat"), (COV_PATH, "Pantheon%2BSH0ES_STAT%2BSYS.cov")]:
if not path.exists():
partial = path.with_suffix(".part")
urllib.request.urlretrieve(DATA_URL + remote, partial)
partial.rename(path)
table = pd.read_csv(TABLE_PATH, sep=r"\s+")
values = np.loadtxt(COV_PATH)
cov = values[1:].reshape(int(values[0]), int(values[0]))
selected = table[table.zHD > 0.01]
print(f"{len(table)} light curves; zHD > 0.01 keeps {len(selected)} light curves of {selected.CID.nunique()} supernovae")
1701 light curves; zHD > 0.01 keeps 1590 light curves of 1473 supernovae
2. Reference fit¶
We compute an independent reference fit for grading. The model magnitude is
We then minimise over \(\Omega_m\) and find the interval with \(\Delta\chi^2\leq1\). Half its width gives the quoted uncertainty. The agents receive the analysis requirements, but not this reference result.
C_KM_S, H0 = 299792.458, 70.0
def reference_fit():
keep = (table.zHD > 0.01).to_numpy()
m, z, z_hel = (table.loc[keep, c].to_numpy() for c in ("m_b_corr", "zHD", "zHEL"))
C = cov[np.ix_(keep, keep)]
factor = cho_factor(C)
ones = np.ones(len(m))
ones_C_ones = ones @ cho_solve(factor, ones)
def chi2(omega_m):
grid = np.linspace(0.0, z.max() * 1.001, 20001)
D_C = cumulative_trapezoid(1 / np.sqrt(omega_m * (1 + grid) ** 3 + 1 - omega_m), grid, initial=0) * C_KM_S / H0
r = m - 5 * np.log10((1 + z_hel) * np.interp(z, grid, D_C)) - 25
C_r = cho_solve(factor, r)
return r @ C_r - (ones @ C_r) ** 2 / ones_C_ones
best = minimize_scalar(chi2, bounds=(0.01, 0.99), method="bounded", options={"xatol": 1e-6})
lower = brentq(lambda x: chi2(x) - best.fun - 1, 0.001, best.x)
upper = brentq(lambda x: chi2(x) - best.fun - 1, best.x, 0.999)
return {"omega_m": best.x, "omega_m_err": (upper - lower) / 2, "chi2_min": best.fun, "n_sn": int(keep.sum())}
REFERENCE = reference_fit()
print(f"full covariance: Omega_m = {REFERENCE['omega_m']:.4f} ± {REFERENCE['omega_m_err']:.4f} (chi2 = {REFERENCE['chi2_min']:.1f}, N = {REFERENCE['n_sn']})")
full covariance: Omega_m = 0.3316 ± 0.0182 (chi2 = 1402.9, N = 1590)
3. Task¶
All three notebooks use the same task statement. It specifies the data selection, model, full covariance and fitting procedure. Each run receives the data in a fresh working directory. We test whether the agents implement this prescribed analysis reliably.
The prompt also asks OpenCode to write report.md and consult the reviewer before finishing. We grade the report's FINAL line. The reviewer reads the requirements from task.md.
TASK = '''Measure the matter density Omega_m of a flat LCDM cosmology from the Pantheon+ type Ia supernovae.
Data
- Table: data/Pantheon+SH0ES.dat (in the working directory)
Whitespace-separated with one header row; columns include zHD, zHEL, zCMB, m_b_corr, m_b_corr_err_DIAG, RA, DEC.
- Covariance: data/Pantheon+SH0ES_STAT+SYS.cov (in the working directory)
Statistical plus systematic covariance of m_b_corr. The first line is N = 1701; the N*N entries follow,
one per line, in row-major order; rows and columns follow the rows of the table.
Requirements
1. Use the light curves (table rows) with zHD > 0.01.
2. Model: m_b_corr = 5 log10(d_L / Mpc) + 25 + M, with d_L = (1 + zHEL) D_C(zHD) and D_C the comoving distance of a flat LCDM cosmology with H0 = 70 km/s/Mpc.
3. M is a free offset: minimise chi^2 over M analytically at each Omega_m.
4. Weight the residuals with the full statistical and systematic covariance matrix, restricted to the rows and columns of the selected supernovae.
5. Report Omega_m, its 1-sigma uncertainty from Delta chi^2 = 1, chi^2 at the minimum and the number of light curves (table rows) used.'''
print(TASK)
def new_workdir(prefix):
# A fresh working directory holding only data/ with the two Pantheon+ files.
work = Path(tempfile.mkdtemp(prefix=prefix))
(work / "data").mkdir()
for path in (TABLE_PATH, COV_PATH):
shutil.copy(path, work / "data" / path.name)
return work
REPORT_STEP = '''
Then write report.md in this directory with the result and the method. Its last line must be
FINAL {"omega_m": <value>, "omega_m_err": <value>, "chi2_min": <value>, "n_sn": <value>, "covariance": "full" or "diagonal"}
Use Python with numpy, scipy, pandas and matplotlib; they are installed. Work only in this directory.'''
REVIEW_STEP = '''
Before you finish, ask the reviewer subagent to check the analysis and report.md against the task requirements and the printed outputs of your scripts, and fix every problem it reports.'''
MESSAGE = TASK + REPORT_STEP + REVIEW_STEP
Measure the matter density Omega_m of a flat LCDM cosmology from the Pantheon+ type Ia supernovae. Data - Table: data/Pantheon+SH0ES.dat (in the working directory) Whitespace-separated with one header row; columns include zHD, zHEL, zCMB, m_b_corr, m_b_corr_err_DIAG, RA, DEC. - Covariance: data/Pantheon+SH0ES_STAT+SYS.cov (in the working directory) Statistical plus systematic covariance of m_b_corr. The first line is N = 1701; the N*N entries follow, one per line, in row-major order; rows and columns follow the rows of the table. Requirements 1. Use the light curves (table rows) with zHD > 0.01. 2. Model: m_b_corr = 5 log10(d_L / Mpc) + 25 + M, with d_L = (1 + zHEL) D_C(zHD) and D_C the comoving distance of a flat LCDM cosmology with H0 = 70 km/s/Mpc. 3. M is a free offset: minimise chi^2 over M analytically at each Omega_m. 4. Weight the residuals with the full statistical and systematic covariance matrix, restricted to the rows and columns of the selected supernovae. 5. Report Omega_m, its 1-sigma uncertainty from Delta chi^2 = 1, chi^2 at the minimum and the number of light curves (table rows) used.
4. Runs¶
.opencode/agents/reviewer.md defines a reviewer that can inspect the analysis but cannot edit files. The build agent calls it through the task tool, which starts a child session with the delegation prompt as context.
REVIEWER = '''---
description: Checks a data analysis and its report against the task requirements and the printed outputs of the scripts. Use it after the fit and after writing report.md.
mode: subagent
model: google/gemini-3.1-flash-lite
permission:
edit: deny
---
You review a data analysis in the current directory. Read task.md, the Python scripts, their printed output
(re-run a script if you need its output) and report.md. Check every requirement of task.md, and check that
every number in report.md appears in the printed output of a script. Reply with APPROVED, or with a numbered
list of concrete problems. Do not modify files.'''
opencode.json sets the models, permissions and tracing plugin.
def config(i):
settings = {"$schema": "https://opencode.ai/config.json", "model": MODEL, "small_model": MODEL,
"autoupdate": False, "share": "disabled",
"permission": {"edit": "allow",
"bash": {"*": "allow", "pip *": "deny", "pip3 *": "deny", "python -m pip *": "deny",
"python3 -m pip *": "deny", "curl *": "deny", "wget *": "deny",
"git *": "deny", "ssh *": "deny"},
"webfetch": "deny", "external_directory": "deny", "doom_loop": "deny"}}
if TRACED:
settings["plugin"] = [[PLUGIN, {"tags": ["lecture01", "table3", f"run{i}"]}]]
return settings
We keep opencode serve running until the session finishes so the plugin can send its traces, and run each session with one opencode run command. opencode export then saves both sessions. Their records provide model calls, tokens, catalogue costs and elapsed session time. With tracing on, each run is a Langfuse trace whose session id is the root session printed below.
RUNS_DONE = []
for i in range(1, RUNS + 1):
work, home, env = sandbox(config(i), REVIEWER)
with opencode_server(work, home, env) as server, open(home / "events.jsonl", "w") as events:
t0 = time.perf_counter()
try:
done = subprocess.run([OC, "run", "--attach", server, "--dir", work, "--model", MODEL, "--format", "json",
"--title", f"pantheon-run{i}", MESSAGE],
cwd=work, env=env, stdin=subprocess.DEVNULL, stdout=events, stderr=subprocess.STDOUT,
timeout=RUN_TIMEOUT)
status = f"exit code {done.returncode}"
except subprocess.TimeoutExpired:
status = f"stopped after {RUN_TIMEOUT} s"
process_time = round(time.perf_counter() - t0, 1)
run = record(i, work, home, env, status, process_time)
RUNS_DONE.append(run)
print(f"run {i}: {status}; Omega_m = {run['omega_m']} ± {run['omega_m_err']}; {run['calls']} calls "
f"{run['calls_by_agent']}; session time {run['time_s']} s; ${run['cost_usd']}; session {run['root_session']}")
run 1: exit code 0; Omega_m = 0.3316 ± 0.0182; 22 calls {'build': 15, 'reviewer': 7}; session time 47.9 s; $0.04171; session ses_e19547bcbffelIudGQDbfY23Ew
run 2: exit code 0; Omega_m = 0.3316 ± 0.0182; 16 calls {'build': 10, 'reviewer': 6}; session time 26.2 s; $0.02403; session ses_e19535baaffel6B4uIrhvkgEBA
5. Grading¶
A run matches when its estimate and uncertainty are each within 0.005 of the reference: \(|\Omega_m-0.3316|\leq0.005\) and \(|\sigma-0.0182|\leq0.005\). This tolerance is about a quarter of the statistical uncertainty. The grade checks numerical agreement; it does not verify the method described in a report.
ROW_COLUMNS = ["run", "grade", "omega_m", "omega_m_err", "n_sn", "covariance_reported", "calls", "calls_by_agent", "time_s", "cost_usd"]
PRIVATE_KEYS = {"work_dir", "home_dir"}
TOLERANCE = 0.005
def grade(omega_m, omega_m_err):
if omega_m is None:
return "no result"
if abs(omega_m - REFERENCE["omega_m"]) > TOLERANCE:
return "wrong"
if omega_m_err is None or abs(omega_m_err - REFERENCE["omega_m_err"]) > TOLERANCE:
return "wrong uncertainty"
return "match"
for run in RUNS_DONE:
run["grade"] = grade(run["omega_m"], run["omega_m_err"])
display(pd.DataFrame([{k: run.get(k) for k in ROW_COLUMNS} for run in RUNS_DONE]))
| run | grade | omega_m | omega_m_err | n_sn | covariance_reported | calls | calls_by_agent | time_s | cost_usd | |
|---|---|---|---|---|---|---|---|---|---|---|
| 0 | 1 | match | 0.3316 | 0.0182 | 1590 | full | 22 | {'build': 15, 'reviewer': 7} | 47.9 | 0.04171 |
| 1 | 2 | match | 0.3316 | 0.0182 | 1590 | full | 16 | {'build': 10, 'reviewer': 6} | 26.2 | 0.02403 |
6. Results¶
We summarise the matches, calls, time and cost for the comparison in Section 5 of the notes. The summary and individual run records are saved in results/table3/.
Costs use OpenCode's catalogue, including cached-input discounts; times cover sessions.
ROW = {
"organisation": ORGANISATION,
"runs": len(RUNS_DONE),
"matches": sum(run["grade"] == "match" for run in RUNS_DONE),
"calls_mean": round(float(np.mean([run["calls"] for run in RUNS_DONE])), 1),
"calls_range": [min(run["calls"] for run in RUNS_DONE), max(run["calls"] for run in RUNS_DONE)],
"time_s_mean": round(float(np.mean([run["time_s"] for run in RUNS_DONE])), 1),
"time_s_range": [min(run["time_s"] for run in RUNS_DONE), max(run["time_s"] for run in RUNS_DONE)],
"cost_usd_mean": round(float(np.mean([run["cost_usd"] for run in RUNS_DONE])), 4) if all(run["cost_usd"] is not None for run in RUNS_DONE) else None,
"cost_usd_range": [min(run["cost_usd"] for run in RUNS_DONE), max(run["cost_usd"] for run in RUNS_DONE)] if all(run["cost_usd"] is not None for run in RUNS_DONE) else None,
"cost": "OpenCode catalogue cost, with the discount for cached input tokens",
"time": "session time from the exports",
}
print(f"{ROW['organisation']}: {ROW['matches']}/{ROW['runs']} match; calls {ROW['calls_mean']} (range {ROW['calls_range']}); "
f"time {ROW['time_s_mean']} s (range {ROW['time_s_range']}); cost ${ROW['cost_usd_mean']} (range {ROW['cost_usd_range']})")
RECORD = {"meta": {"date_utc": datetime.now(timezone.utc).isoformat(timespec="seconds"), "model": MODEL, "versions": VERSIONS,
"traced": TRACED, "tolerance": TOLERANCE,
"reference": {"full": REFERENCE}},
"row": ROW, "runs": [{k: v for k, v in run.items() if k not in PRIVATE_KEYS} for run in RUNS_DONE]}
(RESULTS_DIR / "opencode.json").write_text(json.dumps(RECORD, indent=1, default=str) + "\n")
print("saved", RESULTS_DIR / "opencode.json")
OpenCode build agent with a reviewer subagent: 2/2 match; calls 19.0 (range [16, 22]); time 37.0 s (range [26.2, 47.9]); cost $0.0329 (range [0.02403, 0.04171]) saved results/table3/opencode.json