Lecture 0 — The Pantheon+ fit with one LangGraph agent¶
Multi-Agent Systems for Science · Boris Bolliet, University of Cambridge
We ask one LangGraph agent to fit the matter density \(\Omega_m\) to Pantheon+ data ten times. The agent can write and run Python scripts. We compare its results with an independent fit and record calls, time and cost for Section 5 of the notes.
Setup¶
Set GOOGLE_API_KEY as a Colab secret or an environment variable before starting Jupyter. To trace model calls, also set LANGFUSE_PUBLIC_KEY, LANGFUSE_SECRET_KEY and LANGFUSE_BASE_URL from your Langfuse project. The saved runs were untraced.
Each run has its own working directory. Scripts run in fresh processes with a 120 s limit and no API keys in their environment, but can still access your files. Use Colab or a container to isolate the work.
%pip install -q langgraph langchain langchain-google-genai langfuse numpy scipy pandas
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 ast, threading
from langchain.chat_models import init_chat_model
from langchain_core.messages import HumanMessage, SystemMessage, ToolMessage
from langchain_core.tools import tool
from langgraph.graph import END, START, MessagesState, StateGraph
VERSIONS = {"python": platform.python_version()} | {p: installed(p) for p in [
"langgraph", "langchain", "langchain-core", "langchain-google-genai", "langfuse", "numpy", "scipy", "pandas"]}
print(VERSIONS)
{'python': '3.12.12', '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', 'pandas': '3.1.1'}
Model and run settings¶
MODEL uses LangChain's provider:model form. Changing provider requires its integration package and key. The recorded cost uses gemini-3.1-flash-lite prices of US$0.25 per million input tokens and US$1.50 per million output tokens, including reasoning.
ORGANISATION = "single agent (LangGraph, code-execution tool)"
MODEL = "google_genai:gemini-3.1-flash-lite"
RUNS = 10
PRICE_INPUT, PRICE_OUTPUT = 0.25e-6, 1.50e-6 # US dollars per token, list price of gemini-3.1-flash-lite
EXEC_TIMEOUT = 120 # seconds allowed to one script
OUTPUT_LIMIT = 3000 # characters of script output returned to the model
MAX_TURNS = 10 # model calls of one run
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")
llm = init_chat_model(MODEL, **({"max_retries": 1} if MODEL.startswith("google_genai:") else {}))
CALLBACKS = []
if TRACED:
os.environ.update(LANGFUSE)
from langfuse.langchain import CallbackHandler
CALLBACKS = [CallbackHandler()]
Langfuse tracing: off
Accounting and code execution¶
ask records each completed model call in a Ledger and retries temporary API errors. run_code saves and executes a script, then returns its exit code and output to the model. Long outputs are shortened to OUTPUT_LIMIT characters.
RETRY_ON = ("429", "RESOURCE_EXHAUSTED", "RateLimit", "rate limit", "500", "503", "UNAVAILABLE", "overloaded")
class Ledger:
def __init__(self):
self.start, self.calls, self.lock = time.perf_counter(), [], threading.Lock()
def ask(model, messages, ledger, attempts=6):
t0, waited = time.perf_counter(), 0.0
for attempt in range(attempts):
try:
reply = model.invoke(messages, {"callbacks": CALLBACKS})
break
except Exception as error:
message = f"{type(error).__name__}: {error}"
if attempt == attempts - 1 or not any(marker in message for marker in RETRY_ON):
raise
hint = re.search(r"retry in (\d+(?:\.\d+)?)\s*s", message)
delay = min(float(hint.group(1)) + 1 if hint else 5 * 2**attempt, 90)
time.sleep(delay)
waited += delay
usage = reply.usage_metadata or {}
with ledger.lock:
ledger.calls.append({"t0": t0 - ledger.start, "t1": time.perf_counter() - ledger.start, "wait_s": waited,
"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)})
return reply
SAFE_ENV = {key: os.environ[key] for key in ("PATH", "HOME", "LANG", "PYTHONPATH", "LD_LIBRARY_PATH", "SYSTEMROOT", "TEMP", "TMP")
if key in os.environ}
def clip(text, limit=OUTPUT_LIMIT):
if len(text) <= limit:
return text
return text[: limit // 3] + f"\n[... {len(text) - limit} characters omitted ...]\n" + text[-2 * limit // 3:]
def run_code(code, workdir, ledger):
path = workdir / f"script_{len(list(workdir.glob('script_*.py'))) + 1:02d}.py"
path.write_text(code)
t0 = time.perf_counter()
try:
done = subprocess.run([sys.executable, path.name], cwd=workdir, capture_output=True, text=True,
timeout=EXEC_TIMEOUT, env=SAFE_ENV | {"MPLBACKEND": "Agg"})
returncode, stdout, stderr = done.returncode, done.stdout, done.stderr
except subprocess.TimeoutExpired as error:
stdout = error.stdout.decode() if isinstance(error.stdout, bytes) else (error.stdout or "")
returncode, stderr = -1, f"TimeoutExpired: the script was stopped after {EXEC_TIMEOUT} s."
report = f"{path.name}: exit code {returncode} after {time.perf_counter() - t0:.1f} s\n--- stdout ---\n{clip(stdout)}"
return report + (f"\n--- stderr ---\n{clip(stderr)}" if stderr.strip() else "")
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
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 system prompt describes the code-execution tool and requests a FINAL line for grading.
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
SYSTEM = f'''You are an astrophysicist who analyses data with Python.
Use the run_python tool to execute scripts. Each call starts a fresh Python process in a working directory that
keeps the files written by earlier calls. Available packages: numpy, scipy, pandas, matplotlib.
Scripts are stopped after {EXEC_TIMEOUT} s, and output beyond {OUTPUT_LIMIT} characters is shortened.
When the analysis is complete, reply with a short report whose last line is
FINAL {{"omega_m": <value>, "omega_m_err": <value>, "chi2_min": <value>, "n_sn": <value>, "covariance": "full" or "diagonal"}}'''
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¶
The graph alternates between agent and tools while the model requests code execution. It ends when the model answers without a tool call or reaches MAX_TURNS. We measure the elapsed time of each run.
def make_agent(workdir, ledger):
@tool
def run_python(code: str) -> str:
"Run a Python script in a fresh process and return its exit code and printed output."
return run_code(code, workdir, ledger)
model = llm.bind_tools([run_python])
def agent(state: MessagesState):
return {"messages": [ask(model, state["messages"], ledger)]}
def tools(state: MessagesState):
outputs = []
for call in state["messages"][-1].tool_calls:
try:
content = run_python.invoke(call["args"])
except Exception as error:
content = f"Tool error: {error}"
outputs.append(ToolMessage(content, tool_call_id=call["id"]))
return {"messages": outputs}
def after_agent(state: MessagesState):
return "tools" if state["messages"][-1].tool_calls and len(ledger.calls) < MAX_TURNS else END
graph = StateGraph(MessagesState)
graph.add_node("agent", agent)
graph.add_node("tools", tools)
graph.add_edge(START, "agent")
graph.add_conditional_edges("agent", after_agent, ["tools", END])
graph.add_edge("tools", "agent")
return graph.compile()
def run_once(i):
ledger, workdir = Ledger(), new_workdir("l01_sa_")
state = make_agent(workdir, ledger).invoke({"messages": [SystemMessage(SYSTEM), HumanMessage(TASK)]},
{"recursion_limit": 4 * MAX_TURNS, "callbacks": CALLBACKS})
final = parse_tagged(state["messages"][-1].text, "FINAL") or {}
calls = ledger.calls
input_tokens, output_tokens = sum(c["input_tokens"] for c in calls), sum(c["output_tokens"] for c in calls)
return {"run": i, "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"), "calls": len(calls),
"scripts": len(list(workdir.glob("script_*.py"))), "input_tokens": input_tokens, "output_tokens": output_tokens,
"reasoning_tokens": sum(c["reasoning_tokens"] for c in calls),
"time_s": round(time.perf_counter() - ledger.start, 1),
"cost_usd": round(input_tokens * PRICE_INPUT + output_tokens * PRICE_OUTPUT, 5)}
RUNS_DONE = []
for i in range(1, RUNS + 1):
RUNS_DONE.append(run_once(i))
run = RUNS_DONE[-1]
print(f"run {i}: Omega_m = {run['omega_m']} ± {run['omega_m_err']}, {run['calls']} calls, {run['scripts']} scripts, "
f"{run['time_s']} s, ${run['cost_usd']}")
run 1: Omega_m = 0.3316 ± 0.0182, 5 calls, 4 scripts, 11.0 s, $0.00577
run 2: Omega_m = None ± None, 4 calls, 3 scripts, 12.4 s, $0.00535
run 3: Omega_m = 0.3316 ± 0.0182, 4 calls, 3 scripts, 14.1 s, $0.0055
run 4: Omega_m = 0.3316 ± 0.0182, 3 calls, 2 scripts, 7.4 s, $0.00342
run 5: Omega_m = 0.33158 ± 0.01819, 6 calls, 5 scripts, 14.7 s, $0.00902
run 6: Omega_m = None ± None, 10 calls, 9 scripts, 25.8 s, $0.02213
run 7: Omega_m = 0.3316 ± 0.0182, 3 calls, 2 scripts, 7.3 s, $0.00382
run 8: Omega_m = 0.3316 ± 0.0182, 3 calls, 2 scripts, 7.6 s, $0.00363
run 9: Omega_m = 0.3316 ± 0.0182, 5 calls, 4 scripts, 15.7 s, $0.0076
run 10: Omega_m = 0.3316 ± 0.0185, 6 calls, 5 scripts, 17.0 s, $0.00831
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", "scripts", "time_s", "cost_usd"]
PRIVATE_KEYS = set()
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 | scripts | time_s | cost_usd | |
|---|---|---|---|---|---|---|---|---|---|---|
| 0 | 1 | match | 0.33160 | 0.01820 | 1590.0 | full | 5 | 4 | 11.0 | 0.00577 |
| 1 | 2 | no result | NaN | NaN | NaN | NaN | 4 | 3 | 12.4 | 0.00535 |
| 2 | 3 | match | 0.33160 | 0.01820 | 1590.0 | full | 4 | 3 | 14.1 | 0.00550 |
| 3 | 4 | match | 0.33160 | 0.01820 | 1590.0 | full | 3 | 2 | 7.4 | 0.00342 |
| 4 | 5 | match | 0.33158 | 0.01819 | 1590.0 | full | 6 | 5 | 14.7 | 0.00902 |
| 5 | 6 | no result | NaN | NaN | NaN | NaN | 10 | 9 | 25.8 | 0.02213 |
| 6 | 7 | match | 0.33160 | 0.01820 | 1590.0 | full | 3 | 2 | 7.3 | 0.00382 |
| 7 | 8 | match | 0.33160 | 0.01820 | 1590.0 | full | 3 | 2 | 7.6 | 0.00363 |
| 8 | 9 | match | 0.33160 | 0.01820 | 1590.0 | full | 5 | 4 | 15.7 | 0.00760 |
| 9 | 10 | match | 0.33160 | 0.01850 | 1590.0 | full | 6 | 5 | 17.0 | 0.00831 |
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 the model's list prices; 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": "list price of gemini-3.1-flash-lite: 0.25 USD per M input, 1.50 USD per M output tokens",
"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 / "single_agent.json").write_text(json.dumps(RECORD, indent=1, default=str) + "\n")
print("saved", RESULTS_DIR / "single_agent.json")
single agent (LangGraph, code-execution tool): 8/10 match; calls 4.9 (range [3, 10]); time 13.3 s (range [7.3, 25.8]); cost $0.0075 (range [0.00342, 0.02213]) saved results/table3/single_agent.json