Lecture 0 — The Pantheon+ fit with CMBAgent¶
Multi-Agent Systems for Science · Boris Bolliet, University of Cambridge
We give CMBAgent the Pantheon+ fitting task twice. Its planning graph writes a plan and its execution graph carries it out, as in Denario's analysis stage. We compare the results with an independent fit and use Langfuse to record model calls and costs.
Setup¶
Set GOOGLE_API_KEY as a Colab secret or an environment variable before starting Jupyter.
The installation cell installs the cmbagent_lg package from CMBAgent's main branch. requirements_lg.txt records dependencies for the saved runs.
For tracing, set these secrets or environment variables from your Langfuse project:
| Name | Value |
|---|---|
LANGFUSE_PUBLIC_KEY |
the public key, pk-lf-… |
LANGFUSE_SECRET_KEY |
the secret key, sk-lf-… |
LANGFUSE_BASE_URL |
https://cloud.langfuse.com (EU region) or https://us.cloud.langfuse.com (US region) |
Langfuse receives prompts, scripts, outputs and replies. Use a tracing server authorised to hold that data.
Generated scripts inherit the kernel's environment, including API keys. Run this notebook on Colab or in a container with only the required credentials. Each saved run took about ten minutes.
%pip install -q "cmbagent_lg @ git+https://github.com/CMBAgents/cmbagent@main" langfuse 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
import base64, threading, urllib.parse
from datetime import timedelta
from langchain_core.callbacks import BaseCallbackHandler
from cmbagent_lg import PlanContext, deep_research_graph, graph as planning_graph, prepare_work_dir
from cmbagent_lg.tracing import langfuse_callbacks
VERSIONS = {"python": platform.python_version()} | {p: installed(p) for p in [
"cmbagent_lg", "langgraph", "langchain", "langchain-core", "langchain-google-genai", "langfuse", "numpy", "scipy"]}
print(VERSIONS)
{'python': '3.12.12', 'cmbagent_lg': '0.0.1', 'langgraph': '1.2.22', 'langchain': '1.5.0', 'langchain-core': '1.8.1', 'langchain-google-genai': '4.5.0', 'langfuse': '5.2.0', 'numpy': '2.5.4', 'scipy': '1.18.1'}
Model and run settings¶
PlanContext sets the task, models and limits. Every role uses gemini-3.1-flash-lite here; two environment variables also set this model for adaptive review and replanning. The engineer retains its default high thinking level, which PlanContext does not expose as a setting.
ORGANISATION = "cmbagent_lg (planning and deep research)"
MODEL = "gemini-3.1-flash-lite"
os.environ["ADAPTIVE_REVIEWER_MODEL"] = MODEL # default gemini-3.1-pro-preview
os.environ["ADAPTIVE_PLANNER_MODEL"] = MODEL # default gemini-3.6-flash
RUNS = 2 # complete runs (planning and execution)
MAX_STEPS = 4 # maximum number of steps in a plan
MAX_ATTEMPTS = 3 # engineer attempts per step
EXEC_TIMEOUT = 120 # seconds allowed to one script
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:
os.environ.update(LANGFUSE)
os.environ["LANGFUSE_HOST"] = LANGFUSE["LANGFUSE_BASE_URL"] # read by cmbagent-lg-cost
try:
from langfuse import get_client
TRACED = get_client().auth_check() # wrong keys or URL: the traces would be lost silently
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.
CMBAgent receives the task as main_task. The engineer must print a RESULT line after computing the fit. We grade the last such line in a successful script log.
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
RESULT_LINE = ('Use only numpy, scipy, pandas and matplotlib. When a script computes Omega_m, its last printed line must be '
'RESULT {"omega_m": <value>, "omega_m_err": <value>, "chi2_min": <value>, "n_sn": <value>}')
def make_context():
return PlanContext(
main_task=TASK, maximum_number_of_steps_in_plan=MAX_STEPS, num_rounds=1, max_n_attempts=MAX_ATTEMPTS,
code_execution_timeout=EXEC_TIMEOUT, vlm_enabled=False, enable_escalation=False,
planner_model=MODEL, plan_reviewer_model=MODEL, engineer_model=MODEL, researcher_model=MODEL,
evaluator_model=MODEL, formatter_model=MODEL, engineer_append_instructions=RESULT_LINE)
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¶
run_once invokes planning_graph, then passes its plan to deep_research_graph. Each engineer step writes and executes code. Two evaluators check execution and whether the step met its goal. A failed attempt returns to the engineer, with at most MAX_ATTEMPTS attempts in total. Adaptive review can rewrite unfinished steps.
CallLedger records calls and tokens locally. When tracing is enabled, a Langfuse callback records the same calls. CMBAgent's progress messages are saved in engine_output.txt; the notebook prints the usage of each call and the elapsed time of each run.
AGENTS = ("planner", "plan_reviewer", "format_plan", "format_review", "intent_gate", "input_sourced_classifier",
"engineer", "format_engineer", "execution_evaluator", "step_evaluator", "data_fixer", "escalation",
"researcher", "react_researcher", "researcher_step_evaluator", "researcher_claim_auditor",
"researcher_view_image", "image_reviewer", "adaptive_review", "format_adaptive_review", "replan_tail",
"format_tail")
def agent_of(tags, metadata=None):
return next((t for t in tags or [] if t in AGENTS), (metadata or {}).get("langgraph_node") or "other")
class CallLedger(BaseCallbackHandler):
# Model calls of one run: agent, start and end in seconds from the start of the run, tokens.
def __init__(self):
self.start, self.calls, self.pending = time.perf_counter(), [], {}
self.lock, self.out = threading.Lock(), sys.stdout # sys.stdout before any redirection
def on_chat_model_start(self, serialized, messages, *, run_id, tags=None, metadata=None, **kwargs):
with self.lock:
self.pending[run_id] = (agent_of(tags, metadata), time.perf_counter() - self.start)
def on_llm_end(self, response, *, run_id, **kwargs):
agent, t0 = self.pending.pop(run_id, ("other", None))
generation = response.generations[0][0] if response.generations and response.generations[0] else None
usage = getattr(getattr(generation, "message", None), "usage_metadata", None) or {}
call = {"agent": agent, "t0": t0, "t1": time.perf_counter() - self.start,
"input_tokens": usage.get("input_tokens", 0), "output_tokens": usage.get("output_tokens", 0),
"reasoning_tokens": (usage.get("output_token_details") or {}).get("reasoning", 0)}
with self.lock:
self.calls.append(call)
print(f"{call['t1']:7.1f} s {agent:26s} in {call['input_tokens']:>7,} out {call['output_tokens']:>7,}"
f" (reasoning {call['reasoning_tokens']:,})", file=self.out, flush=True)
def on_llm_error(self, error, *, run_id, **kwargs):
self.pending.pop(run_id, None)
SESSION = "lecture01-table3-cmbagent-lg-" + datetime.now(timezone.utc).strftime("%Y%m%d-%H%M%S")
def last_result(work_dir):
# The last RESULT line printed by a successful script (codebase/step_N.log).
found = None
for log in sorted((work_dir / "codebase").glob("step_*.log"), key=lambda p: p.stat().st_mtime):
if "failure" in log.name:
continue
for match in re.finditer(r"RESULT\s*(\{[^{}]*\})", log.read_text(errors="replace")):
try:
found = json.loads(match.group(1))
except json.JSONDecodeError:
pass
return found or {}
def run_once(i):
work_dir = prepare_work_dir(new_workdir("l01_lg_"), clear=False)
ledger = CallLedger()
tracing = langfuse_callbacks() if TRACED else []
config = {"callbacks": tracing + [ledger], "tags": ["lecture01", "table3", f"run{i}"],
"metadata": {"langfuse_session_id": f"{SESSION}-run{i}", "langfuse_tags": ["lecture01", "table3", f"run{i}"]}}
context, trace_ids = make_context(), []
with open(work_dir / "engine_output.txt", "w") as log, contextlib.redirect_stdout(log), contextlib.redirect_stderr(log):
plan = planning_graph.invoke({}, context=context, config=config | {"run_name": f"lecture01 run{i} planning"})["current_plan"]
trace_ids.append(getattr(tracing[0], "last_trace_id", None) if tracing else None)
state = deep_research_graph.invoke({"plan": plan, "work_dir": str(work_dir)}, context=context,
config=config | {"run_name": f"lecture01 run{i} execution"})
trace_ids.append(getattr(tracing[0], "last_trace_id", None) if tracing else None)
result = last_result(work_dir)
outcomes = state.get("step_outcomes", [])
return {
"run": i, "omega_m": float(result["omega_m"]) if "omega_m" in result else None,
"omega_m_err": float(result["omega_m_err"]) if "omega_m_err" in result else None,
"result": result, "calls": len(ledger.calls),
"input_tokens": sum(c["input_tokens"] for c in ledger.calls),
"output_tokens": sum(c["output_tokens"] for c in ledger.calls),
"reasoning_tokens": sum(c["reasoning_tokens"] for c in ledger.calls),
"time_s": round(time.perf_counter() - ledger.start, 1), "cost_usd": None, "trace_ids": trace_ids,
"plan": [f"{s.sub_task_agent}: {s.sub_task}" for s in plan.sub_tasks],
"executed_plan": [f"{s.sub_task_agent}: {s.sub_task}" for s in state["plan"].sub_tasks],
"outcomes": [{k: o.get(k) for k in ("step_number", "fulfilled", "attempts")} for o in outcomes],
"retries": sum(max((o.get("attempts") or 1) - 1, 0) for o in outcomes),
"engineer_calls": sum(c["agent"] == "engineer" for c in ledger.calls), "work_dir": work_dir,
}
import contextlib
RUNS_DONE = []
for i in range(1, RUNS + 1):
print(f"--- run {i} ---")
RUNS_DONE.append(run_once(i))
for run in RUNS_DONE:
print(f"run {run['run']}: plan {run['plan']}; executed {len(run['executed_plan'])} steps; outcomes {run['outcomes']}; "
f"RESULT Omega_m = {run['omega_m']} ± {run['omega_m_err']}; {run['calls']} calls, {run['time_s']} s")
--- run 1 ---
2.8 s planner in 1,120 out 748 (reasoning 132)
4.5 s format_plan in 658 out 639 (reasoning 0)
11.6 s plan_reviewer in 1,737 out 2,135 (reasoning 1,745)
12.7 s format_review in 432 out 190 (reasoning 0)
16.5 s planner in 1,920 out 1,309 (reasoning 536)
18.5 s format_plan in 815 out 788 (reasoning 0)
142.2 s engineer in 5,111 out 63,689 (reasoning 62,913)
144.6 s format_engineer in 826 out 833 (reasoning 0)
145.9 s execution_evaluator in 2,240 out 136 (reasoning 99)
147.5 s step_evaluator in 3,972 out 330 (reasoning 111)
271.4 s engineer in 3,937 out 63,758 (reasoning 62,912)
274.0 s format_engineer in 896 out 909 (reasoning 0)
276.6 s execution_evaluator in 2,443 out 306 (reasoning 114)
402.3 s engineer in 4,044 out 63,789 (reasoning 62,913)
404.8 s format_engineer in 926 out 918 (reasoning 0)
407.5 s execution_evaluator in 2,289 out 119 (reasoning 82)
408.9 s step_evaluator in 4,172 out 158 (reasoning 103)
410.3 s adaptive_review in 2,098 out 262 (reasoning 120)
411.1 s format_adaptive_review in 192 out 48 (reasoning 0)
536.1 s engineer in 6,405 out 64,440 (reasoning 62,913)
540.3 s format_engineer in 1,577 out 1,593 (reasoning 0)
542.3 s execution_evaluator in 2,557 out 138 (reasoning 101)
543.3 s step_evaluator in 4,730 out 160 (reasoning 105)
545.6 s adaptive_review in 2,502 out 469 (reasoning 179)
546.6 s format_adaptive_review in 340 out 143 (reasoning 0)
548.4 s replan_tail in 3,282 out 402 (reasoning 191)
550.2 s format_tail in 265 out 189 (reasoning 0)
552.0 s react_researcher in 5,005 out 461 (reasoning 113)
553.1 s researcher_step_evaluator in 5,796 out 172 (reasoning 117)
558.0 s researcher_claim_auditor in 5,797 out 1,574 (reasoning 1,166)
--- run 2 ---
2.9 s planner in 1,120 out 838 (reasoning 197)
4.9 s format_plan in 683 out 633 (reasoning 0)
11.9 s plan_reviewer in 1,741 out 1,952 (reasoning 1,537)
13.2 s format_review in 457 out 166 (reasoning 0)
18.5 s planner in 1,899 out 1,688 (reasoning 949)
20.6 s format_plan in 781 out 730 (reasoning 0)
145.4 s engineer in 5,149 out 63,832 (reasoning 62,913)
147.9 s format_engineer in 969 out 976 (reasoning 0)
150.1 s execution_evaluator in 2,326 out 370 (reasoning 333)
154.5 s step_evaluator in 4,123 out 1,325 (reasoning 1,175)
278.5 s engineer in 3,985 out 63,975 (reasoning 62,913)
281.7 s format_engineer in 1,112 out 1,101 (reasoning 0)
284.0 s execution_evaluator in 2,382 out 513 (reasoning 476)
285.0 s step_evaluator in 4,307 out 166 (reasoning 111)
286.6 s adaptive_review in 2,181 out 242 (reasoning 130)
287.3 s format_adaptive_review in 162 out 48 (reasoning 0)
414.9 s engineer in 6,634 out 64,602 (reasoning 62,912)
419.7 s format_engineer in 1,740 out 1,793 (reasoning 0)
422.7 s execution_evaluator in 2,551 out 180 (reasoning 143)
426.8 s step_evaluator in 4,941 out 1,327 (reasoning 1,197)
560.8 s engineer in 5,328 out 64,755 (reasoning 62,913)
565.6 s format_engineer in 1,892 out 1,924 (reasoning 0)
568.3 s execution_evaluator in 2,569 out 115 (reasoning 88)
570.0 s step_evaluator in 5,162 out 165 (reasoning 110)
572.1 s adaptive_review in 2,652 out 345 (reasoning 99)
573.1 s format_adaptive_review in 296 out 133 (reasoning 0)
575.1 s replan_tail in 3,598 out 433 (reasoning 107)
576.8 s format_tail in 380 out 260 (reasoning 0)
578.9 s react_researcher in 5,561 out 562 (reasoning 107)
581.7 s researcher_step_evaluator in 6,766 out 754 (reasoning 699)
587.6 s researcher_claim_auditor in 6,767 out 2,212 (reasoning 1,539)
run 1: plan ['engineer: Data ingestion and filtering', 'engineer: Matrix inversion and definition of the objective function', 'engineer: Numerical optimization for Omega_m and uncertainty estimation', 'researcher: Results reporting']; executed 3 steps; outcomes [{'step_number': 1, 'fulfilled': True, 'attempts': 3}, {'step_number': 2, 'fulfilled': True, 'attempts': 1}, {'step_number': 3, 'fulfilled': True, 'attempts': 1}]; RESULT Omega_m = 0.331574 ± 0.018195; 30 calls, 558.1 s
run 2: plan ['engineer: Data loading, filtering, and covariance sub-matrix extraction', 'engineer: Likelihood computation and grid search for Omega_m', 'researcher: Results analysis and reporting']; executed 3 steps; outcomes [{'step_number': 1, 'fulfilled': True, 'attempts': 2}, {'step_number': 2, 'fulfilled': True, 'attempts': 2}, {'step_number': 3, 'fulfilled': True, 'attempts': 1}]; RESULT Omega_m = 0.3285714285714286 ± 0.01844270823188901; 31 calls, 587.6 s
Cost from the trace¶
Each run has a planning trace and an execution trace. After flushing the callback, we retrieve their model calls through the Langfuse API and sum the estimated costs. Without tracing, the cost remains unset.
def langfuse_get(path, params):
token = base64.b64encode(f"{LANGFUSE['LANGFUSE_PUBLIC_KEY']}:{LANGFUSE['LANGFUSE_SECRET_KEY']}".encode()).decode()
request = urllib.request.Request(f"{LANGFUSE['LANGFUSE_BASE_URL'].rstrip('/')}{path}?{urllib.parse.urlencode(params)}",
headers={"Authorization": f"Basic {token}"})
return json.loads(urllib.request.urlopen(request, timeout=60).read())
def generations(trace_id):
now = datetime.now(timezone.utc)
stamp = lambda t: t.strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3] + "Z"
params = {"traceId": trace_id, "fromStartTime": stamp(now - timedelta(days=1)), "toStartTime": stamp(now + timedelta(minutes=5)),
"limit": 1000, "fields": "core,basic,usage,model"}
found = []
while True:
page = langfuse_get("/api/public/v2/observations", params)
found += [o for o in page.get("data") or [] if o.get("type") == "GENERATION"]
cursor = (page.get("meta") or {}).get("cursor")
if not page.get("data") or not cursor:
return found
params["cursor"] = cursor
if TRACED:
from langfuse import get_client
get_client().flush()
for run in RUNS_DONE:
deadline = time.time() + 120
while True:
gens = [g for tid in run["trace_ids"] if tid for g in generations(tid)]
if len(gens) >= run["calls"] or time.time() > deadline:
break
time.sleep(5)
run["cost_usd"] = round(sum(float(g.get("totalCost") or 0) for g in gens), 4)
run["trace_generations"] = len(gens)
print(f"run {run['run']}: {len(gens)} generations in the trace (ledger {run['calls']} calls), cost ${run['cost_usd']}; "
f"trace ids {', '.join(t for t in run['trace_ids'] if t)}")
else:
print("Tracing is off: no cost from Langfuse.")
run 1: 30 generations in the trace (ledger 30 calls), cost $0.4257; trace ids dc37ce85d6d9f225531a43941dfe42b7, bef930fa537c665edf3c5fdb736002fb
run 2: 31 generations in the trace (ledger 31 calls), cost $0.4397; trace ids c6c3bd7a7fa3128409dce2cd9d828065, b15310994ce0679c91a9dc399595daa3
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", "calls", "engineer_calls", "retries", "time_s", "cost_usd"]
PRIVATE_KEYS = {"work_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 | calls | engineer_calls | retries | time_s | cost_usd | |
|---|---|---|---|---|---|---|---|---|---|
| 0 | 1 | match | 0.331574 | 0.018195 | 30 | 4 | 2 | 558.1 | 0.4257 |
| 1 | 2 | match | 0.328571 | 0.018443 | 31 | 4 | 2 | 587.6 | 0.4397 |
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 are Langfuse estimates; times cover complete runs.
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": "Langfuse estimate from its price for the model",
"time": "recorded wall time of a run",
}
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 / "cmbagent_lg.json").write_text(json.dumps(RECORD, indent=1, default=str) + "\n")
print("saved", RESULTS_DIR / "cmbagent_lg.json")
cmbagent_lg (planning and deep research): 2/2 match; calls 30.5 (range [30, 31]); time 572.9 s (range [558.1, 587.6]); cost $0.4327 (range [0.4257, 0.4397]) saved results/table3/cmbagent_lg.json