Capstone II: Revisiting Monte Carlo Estimation of Pi¶
Prerequisites: This capstone assumes you've read Chapters 2–9.
Setup Instructions¶
To ensure you have the required dependencies to run this notebook, you'll need to have our llm-agents-from-scratch framework installed on the running Jupyter kernel. To do this, you can launch this notebook with the following command while within the project's root directory:
# we need the notebook-utils and openai extras for this notebook
uv sync --extra notebook-utils --extra openai
# to launch the notebook
uv run --with jupyter jupyter lab
Alternatively, if you just want to use the published version of llm-agents-from-scratch without local development, you can install it from PyPI by uncommenting the cell below.
Setting up the LLM¶
I recommend running these notebooks on Ollama Cloud. It serves much larger models than most laptops can run. The default cloud model is picked by benchmarking candidates on these notebooks, and an automated run checks every notebook against it each week. The notebook status page shows the current model and results.
- Create an API key at https://ollama.com/settings/keys.
- Export it before launching Jupyter:
export OLLAMA_API_KEY=<your key>. - That's all. When a notebook builds its LLM, it detects the key and uses Ollama Cloud.
Prefer to run locally? Install Ollama from https://ollama.com/download
and pull the model with ollama pull qwen3:14b. If no key is set, the
notebook starts the Ollama service for you, so there is no need to run
ollama serve. Local models are smaller, so your outputs will differ from
the recorded ones.
Prefer OpenAI or Anthropic?
- Install the extra:
uv sync --extra openaioruv sync --extra anthropic. - Export
OPENAI_API_KEYorANTHROPIC_API_KEYbefore launching Jupyter. If you forget, you will be prompted for it, which keeps the key out of the saved notebook. - Set
LLM_PROVIDER=openai(oranthropic), or passprovider="openai"tomake_llm(). A key on its own never switches providers, so one exported for unrelated work cannot reroute you.
The switch applies wherever a notebook builds its LLM with make_llm().
A notebook that constructs OllamaLLM directly stays on Ollama. Output on
gpt-5 or Claude will differ from the recorded outputs, and prompt-sensitive
examples (the ch09 evaluator pattern, ch08 supervised trajectories) may
behave noticeably differently.
# Uncomment the line below to install `llm-agents-from-scratch` from PyPI
# !pip install 'llm-agents-from-scratch[notebook-utils,openai]'
Setup¶
import logging
import os
from llm_agents_from_scratch.logger import enable_console_logging
Constants¶
IS_ON_RUNPOD = "RUNPOD_POD_ID" in os.environ
LOGGING_ENABLED = False # 20 concurrent loops make for very long logs
LOGGING_LEVEL = logging.INFO
# the experiment
NUM_ESTIMATES = 20 # K independent estimates of pi per run
MAX_STEPS_PER_ESTIMATE = 20 # Capstone I's budget for a single estimate
MAX_DISPATCHES_PER_STEP = 5 # stays under the provider's concurrency cap
NUM_REPLICATIONS = 3
# Install additional dependencies for notebook
if IS_ON_RUNPOD:
!uv pip install numpy pandas --system
else:
!uv pip install numpy pandas
Using Python 3.13.5 environment at: /home/nerdai/Projects/llm-agents-from-scratch/.venv Audited 2 packages in 1ms
# maybe enable logging
if LOGGING_ENABLED:
enable_console_logging(LOGGING_LEVEL)
The Task: the standard error of Capstone I's algorithm¶
Capstone I's agent produced a point estimate of pi. This capstone asks how
much those estimates vary: what is the standard error of Capstone I's
algorithm? To answer it, we run the whole algorithm NUM_ESTIMATES times,
each time on its own new sample, and compute
$$\text{SE} = \frac{s}{\sqrt{K}}$$
where $s$ is the standard deviation of the $K$ final estimates.
A single agent doing this must track $K$ samples, $K$ doubling schedules and $K$ convergence states in one growing rollout. That is the context sprawl that Chapter 9 sets out to tame with subagents, so we build both systems and compare them.
LLMs¶
from llm_agents_from_scratch.notebook_utils import make_llm
(Listing 1) Measuring the context sent to an LLM¶
To compare how much context each system sends, we wrap the LLM in a
BaseLLM that forwards every call and counts the prompt characters it
sends: the prompt itself, the chat history and any tool results. Because
the wrapper is itself a BaseLLM, agents and subagents use it like any
other LLM.
from collections.abc import Sequence
from typing import Any
from llm_agents_from_scratch.base.llm import BaseLLM
from llm_agents_from_scratch.data_structures import ChatMessage
def history_chars(chat_history: Sequence[ChatMessage]) -> int:
"""Total characters in a chat history."""
return sum(len(m.content) for m in chat_history)
class MeteredLLM(BaseLLM):
"""An LLM wrapper that counts the prompt characters sent to the LLM.
Attributes:
llm (BaseLLM): The wrapped LLM.
prompt_chars (int): Prompt characters sent since the last reset.
"""
def __init__(self, llm: BaseLLM) -> None:
"""Initialize a MeteredLLM.
Args:
llm (BaseLLM): The LLM to wrap.
"""
self.llm = llm
self.prompt_chars = 0
def reset(self) -> None:
"""Reset the prompt character count."""
self.prompt_chars = 0
async def complete(self, prompt: str, **kwargs: Any) -> Any:
"""Count, then forward to the wrapped LLM."""
self.prompt_chars += len(prompt)
return await self.llm.complete(prompt, **kwargs)
async def structured_output(
self,
prompt: str,
mdl: Any,
**kwargs: Any,
) -> Any:
"""Count, then forward to the wrapped LLM."""
self.prompt_chars += len(prompt)
return await self.llm.structured_output(prompt, mdl, **kwargs)
async def chat(
self,
input: str,
chat_history: Sequence[ChatMessage] | None = None,
tools: Sequence[Any] | None = None,
**kwargs: Any,
) -> Any:
"""Count, then forward to the wrapped LLM."""
self.prompt_chars += len(input) + history_chars(chat_history or [])
return await self.llm.chat(
input=input,
chat_history=chat_history,
tools=tools,
**kwargs,
)
async def continue_chat_with_tool_results(
self,
tool_call_results: Sequence[Any],
chat_history: Sequence[ChatMessage],
tools: Sequence[Any] | None = None,
**kwargs: Any,
) -> Any:
"""Count, then forward to the wrapped LLM."""
self.prompt_chars += history_chars(chat_history) + sum(
len(str(r.content)) for r in tool_call_results
)
return await self.llm.continue_chat_with_tool_results(
tool_call_results=tool_call_results,
chat_history=chat_history,
tools=tools,
**kwargs,
)
Build Tools¶
(Listing 2) The Capstone I tools, with one change¶
The three tools are Capstone I's, with one change: monte_carlo_estimate
now also reports whether the estimate is in the target range
[3.1415, 3.1425). In Capstone I the agent made that comparison itself,
and LLMs occasionally get it wrong (declaring 3.1436 "in range", say). That
mistake has nothing to do with context, so here the tool makes the check
and both systems read its answer.
import uuid
import numpy as np
from pydantic import BaseModel, ConfigDict, Field
from llm_agents_from_scratch.tools import PydanticFunctionTool
# sample_id -> (points inside, total points), as in Capstone I
SAMPLE_REGISTRY: dict[str, tuple[int, int]] = {}
# points are drawn this many at a time, so memory stays small for any n
CHUNK_SIZE = 1_000_000
TARGET_LOWER, TARGET_UPPER = 3.1415, 3.1425
def count_inside(n: int) -> int:
"""Draw n random points; return how many land inside the circle."""
inside = 0
for start in range(0, n, CHUNK_SIZE):
size = min(CHUNK_SIZE, n - start)
x, y = np.random.uniform(size=(2, size))
inside += int(np.count_nonzero(x**2 + y**2 < 1))
return inside
def estimate_of(sample_id: str) -> float:
"""The Monte Carlo estimate of pi from a registered sample."""
inside, n = SAMPLE_REGISTRY[sample_id]
return (inside / n) * 4
class RandomSampleParams(BaseModel):
"""Params for generate_random_sample."""
model_config = ConfigDict(extra="forbid")
n: int = Field(description="The number of random points to generate")
class RandomSample(BaseModel):
"""Result from generate_random_sample and add_more_points_to_sample."""
sample_id: str = Field(
description="Pass this sample_id to monte_carlo_estimate",
)
sample_size: int
def __str__(self) -> str:
"""String representation of RandomSample."""
return self.model_dump_json()
def generate_random_sample(params: RandomSampleParams) -> RandomSample:
"""Generate n random points in [0, 1] × [0, 1].
Returns a sample_id. Pass this sample_id directly to monte_carlo_estimate.
"""
sample_id = str(uuid.uuid4())
SAMPLE_REGISTRY[sample_id] = (count_inside(params.n), params.n)
return RandomSample(sample_id=sample_id, sample_size=params.n)
class AddPointsParams(BaseModel):
"""Params for add_more_points_to_sample."""
model_config = ConfigDict(extra="forbid")
sample_id: str = Field(
description="The sample_id of the sample to augment",
)
n: int = Field(description="The number of random points to generate")
def add_more_points_to_sample(params: AddPointsParams) -> RandomSample:
"""Add n more random points to an existing random sample.
Returns a sample_id and the total number of points.
"""
inside, total = SAMPLE_REGISTRY[params.sample_id]
SAMPLE_REGISTRY[params.sample_id] = (
inside + count_inside(params.n),
total + params.n,
)
return RandomSample(
sample_id=params.sample_id,
sample_size=total + params.n,
)
class MonteCarloEstimateParams(BaseModel):
"""Params for monte_carlo_estimate."""
model_config = ConfigDict(extra="forbid")
sample_id: str = Field(
description="The sample_id returned by generate_random_sample",
)
class MonteCarloEstimateResult(BaseModel):
"""Results for monte_carlo_estimate."""
sample_id: str
sample_size: int
estimate: float
in_target_range: bool
def __str__(self) -> str:
"""String representation of MonteCarloEstimateResult."""
return self.model_dump_json()
def monte_carlo_estimate(
params: MonteCarloEstimateParams,
) -> MonteCarloEstimateResult:
"""Estimate pi using Monte Carlo method.
Also reports whether the estimate is in the target range
[3.1415, 3.1425).
"""
estimate = estimate_of(params.sample_id)
return MonteCarloEstimateResult(
sample_id=params.sample_id,
sample_size=SAMPLE_REGISTRY[params.sample_id][1],
estimate=estimate,
in_target_range=TARGET_LOWER <= estimate < TARGET_UPPER,
)
random_sample_tool = PydanticFunctionTool(generate_random_sample)
add_more_points_tool = PydanticFunctionTool(add_more_points_to_sample)
monte_carlo_estimate_tool = PydanticFunctionTool(monte_carlo_estimate)
(Listing 3) Tool: compute_standard_error()¶
import statistics
class StandardErrorParams(BaseModel):
"""Params for compute_standard_error."""
model_config = ConfigDict(extra="forbid")
sample_ids: list[str] = Field(
description="The sample_ids of the independent estimates of pi",
)
class StandardErrorResult(BaseModel):
"""Result of compute_standard_error."""
num_estimates: int
mean: float
standard_error: float
def __str__(self) -> str:
"""String representation of StandardErrorResult."""
return self.model_dump_json()
def compute_standard_error(params: StandardErrorParams) -> StandardErrorResult:
"""Compute the mean and standard error of independent estimates of pi."""
estimates = [estimate_of(s) for s in params.sample_ids]
k = len(estimates)
return StandardErrorResult(
num_estimates=k,
mean=statistics.fmean(estimates),
standard_error=statistics.stdev(estimates) / k**0.5 if k > 1 else 0.0,
)
standard_error_tool = PydanticFunctionTool(compute_standard_error)
algorithm = """
<algorithm>
1. Call generate_random_sample(1000000) to start a NEW sample of 1M points
2. Call monte_carlo_estimate(sample_id) to get the estimate
3. Check in_target_range in the result (True means the estimate is in
[3.1415, 3.1425)):
- True → this estimate is done
- False → Continue to step 4
4. Call add_more_points_to_sample on the SAME sample, doubling the points
each time:
- First add: 1 million
- Second add: 2 million
- Third add: 4 million
- And so on, doubling each iteration
5. After adding points, go back to step 2
</algorithm>
""".strip()
critical_rules = """
<critical_rules>
- If the task is not complete, your response MUST contain a tool call
- Do not just describe what you plan to do—actually call the tool
- NEVER fabricate tool results-only use actual tool responses
- NEVER invent a sample_id
</critical_rules>
""".strip()
final_output = """
<final_output>
When you have the standard error, respond with this exact JSON structure
and nothing else:
{"sample_ids": [<the sample_ids>], "standard_error": <the standard error>}
No explanation, no markdown formatting, no code blocks—just the raw JSON.
</final_output>
""".strip()
single_agent_instruction = f"""
You are tasked with estimating the standard error of a Monte Carlo
algorithm for estimating pi. Run the algorithm below {NUM_ESTIMATES} times,
each time with its own NEW sample, so you end up with {NUM_ESTIMATES}
independent estimates that are each in the target range. Then call
compute_standard_error with the {NUM_ESTIMATES} sample_ids.
{algorithm}
{critical_rules}
{final_output}
""".strip()
(Listing 5) Creating the single agent¶
from llm_agents_from_scratch import LLMAgent
single_agent_llm = MeteredLLM(make_llm())
single_agent = LLMAgent(
llm=single_agent_llm,
tools=[
random_sample_tool,
add_more_points_tool,
monte_carlo_estimate_tool,
standard_error_tool,
],
)
single_agent_max_steps = MAX_STEPS_PER_ESTIMATE * NUM_ESTIMATES
✓ Using Ollama Cloud (deepseek-v4.1-flash)
System 2: A Coordinator and Subagents¶
(Listing 6) The pi-estimator subagent¶
Each pi-estimator dispatch runs Capstone I's algorithm once, on its own
new sample, in a fresh context. The algorithm goes in the subagent's
system message, by overriding the system_message template, so the
coordinator's dispatch can be as short as "Estimate pi."
from llm_agents_from_scratch import LLMAgentBuilder
from llm_agents_from_scratch.agent.templates import default_templates
from llm_agents_from_scratch.subagents import SubAgentSpec
subagents_llm = MeteredLLM(make_llm())
pi_estimator_system_message = (
default_templates["system_message"]
+ "\nWhen asked to estimate pi, follow this algorithm until "
"in_target_range is True, then report the sample_id and the "
"estimate.\n\n" + algorithm + "\n\n" + critical_rules
)
pi_estimator_spec = SubAgentSpec(
name="pi-estimator",
description=(
"Estimates pi with its own new Monte Carlo sample until the "
"estimate is in the target range [3.1415, 3.1425). Returns the "
"sample_id and the estimate."
),
builder=LLMAgentBuilder(
llm=subagents_llm,
tools=[
random_sample_tool,
add_more_points_tool,
monte_carlo_estimate_tool,
],
templates={
**default_templates,
"system_message": pi_estimator_system_message,
},
),
max_steps=MAX_STEPS_PER_ESTIMATE,
)
✓ Using Ollama Cloud (deepseek-v4.1-flash)
(Listing 7) The coordinator¶
The coordinator holds only compute_standard_error. It dispatches the
estimates in batches, since dispatches in the same response run
concurrently and a cloud provider caps how many requests it serves at
once.
coordinator_instruction = f"""
You are tasked with estimating the standard error of a Monte Carlo
algorithm for estimating pi. You need {NUM_ESTIMATES} independent
estimates of pi.
1. Dispatch the pi-estimator subagent {NUM_ESTIMATES} times in total, in
batches of at most {MAX_DISPATCHES_PER_STEP} dispatches per response
(dispatches in the same response run concurrently). Each dispatch's
task is simply: "Estimate pi."
2. Collect the {NUM_ESTIMATES} sample_ids from the results.
3. Call compute_standard_error with the {NUM_ESTIMATES} sample_ids.
{critical_rules}
{final_output}
""".strip()
coordinator = LLMAgent(
llm=subagents_llm,
tools=[standard_error_tool],
subagents=[pi_estimator_spec],
)
coordinator_max_steps = MAX_STEPS_PER_ESTIMATE
Evaluation¶
(Listing 8) Evaluating Task Success¶
Success is checked against ground truth, the sample registry. The final
response must name exactly NUM_ESTIMATES distinct, real samples, every
one of them in the target range, and report the standard error that those
samples give, to within 1% (enough for an agent that rounds the tool's
value). Unlike Capstone I, we pick the JSON out of the final response
instead of requiring it verbatim. Chapter 4's LLMAgent returns its
deciding step's response as the final answer, which often adds a sentence
before the JSON, and this capstone is about context, not formatting.
import json
import math
def final_json(content: str) -> dict | None:
"""The last JSON object in `content` that has a `sample_ids` key."""
decoder = json.JSONDecoder()
found = None
for i, char in enumerate(content):
if char != "{":
continue
try:
obj, _ = decoder.raw_decode(content, i)
except json.JSONDecodeError:
continue
if isinstance(obj, dict) and "sample_ids" in obj:
found = obj
return found
def is_task_success(
handler: LLMAgent.TaskHandler,
verbose: bool = False,
) -> bool:
"""Determines task success against the sample registry.
Args:
handler (LLMAgent.TaskHandler): The handler containing the
result or exception of the task execution
verbose (bool): Whether to print out details of the
determination. Defaults to False.
Returns:
bool: True if task was successful. False, otherwise.
"""
if handler.exception():
if verbose:
print(handler.exception())
return False
output = final_json(handler.result().content)
sample_ids = output.get("sample_ids") if output else None
reported_se = output.get("standard_error") if output else None
if (
not isinstance(sample_ids, list)
or len(sample_ids) != NUM_ESTIMATES
or not all(isinstance(s, str) for s in sample_ids)
or len(set(sample_ids)) != NUM_ESTIMATES
):
if verbose:
print(f"Expected {NUM_ESTIMATES} distinct sample_ids: {output}")
return False
real = [s for s in sample_ids if s in SAMPLE_REGISTRY]
in_range = [
s for s in real if TARGET_LOWER <= estimate_of(s) < TARGET_UPPER
]
se_ok = False
if len(real) == NUM_ESTIMATES and isinstance(reported_se, int | float):
params = StandardErrorParams(sample_ids=sample_ids)
true_se = compute_standard_error(params).standard_error
se_ok = math.isclose(reported_se, true_se, rel_tol=0.01)
if verbose:
print(
f"{len(real)} real, {len(in_range)} in range, "
f"standard_error {reported_se} correct: {se_ok}",
)
return len(in_range) == NUM_ESTIMATES and se_ok
(Listing 9) Running a task and measuring its context¶
Each run records task success alongside four measures of the context it
took: wall time, the number of steps and the size of the agent's own
rollout, and the prompt characters sent to the LLM. For the coordinator,
the prompt characters include every subagent's calls, since they share
the coordinator's MeteredLLM. Divide by about four for a rough count of
tokens.
import contextlib
import time
from llm_agents_from_scratch.data_structures import Task
async def run_and_measure(
agent: LLMAgent,
metered_llm: MeteredLLM,
instruction: str,
max_steps: int,
) -> tuple[LLMAgent.TaskHandler, dict[str, Any]]:
"""Run a task to completion and measure the context it took."""
metered_llm.reset()
start = time.perf_counter()
handler = agent.run(Task(instruction=instruction), max_steps=max_steps)
# a failed run is recorded through handler.exception()
with contextlib.suppress(Exception):
await handler
return handler, {
"task_success": is_task_success(handler),
"wall_seconds": round(time.perf_counter() - start),
"steps": handler.rollout.count("=== Task Step Start ==="),
"rollout_chars": len(handler.rollout),
"prompt_chars": metered_llm.prompt_chars,
}
Perform the Task¶
single_handler, single_metrics = await run_and_measure(
single_agent,
single_agent_llm,
single_agent_instruction,
single_agent_max_steps,
)
single_metrics
{'task_success': True,
'wall_seconds': 117,
'steps': 22,
'rollout_chars': 112178,
'prompt_chars': 5006179}
is_task_success(single_handler, verbose=True)
20 real, 20 in range, standard_error 6.957700784858352e-05 correct: True
True
coordinator_handler, coordinator_metrics = await run_and_measure(
coordinator,
subagents_llm,
coordinator_instruction,
coordinator_max_steps,
)
coordinator_metrics
{'task_success': True,
'wall_seconds': 212,
'steps': 6,
'rollout_chars': 24425,
'prompt_chars': 3940373}
is_task_success(coordinator_handler, verbose=True)
20 real, 20 in range, standard_error 6.730785030765195e-05 correct: True
True
The coordinator's rollout shows the whole run: each batch of dispatches,
the pi-estimator results, and the final compute_standard_error call.
The single agent's rollout is several times longer, so we print only its
final answer.
print(coordinator_handler.rollout)
=== Task Step Start ===
💬 assistant: My current instruction is 'You are tasked with estimating the standard error of a Monte Carlo
algorithm for estimating pi. You need 20 independent
estimates of pi.
1. Dispatch the pi-estimator subagent 20 times in total, in
batches of at most 5 dispatches per response
(dispatches in the same response run concurrently). Each dispatch's
task is simply: "Estimate pi."
2. Collect the 20 sample_ids from the results.
3. Call compute_standard_error with the 20 sample_ids.
<critical_rules>
- If the task is not complete, your response MUST contain a tool call
- Do not just describe what you plan to do—actually call the tool
- NEVER fabricate tool results-only use actual tool responses
- NEVER invent a sample_id
</critical_rules>
<final_output>
When you have the standard error, respond with this exact JSON structure
and nothing else:
{"sample_ids": [<the sample_ids>], "standard_error": <the standard error>}
No explanation, no markdown formatting, no code blocks—just the raw JSON.
</final_output>'
💬 assistant: I need to make the following tool call(s):
{
"id_": "63398296-dc84-4f26-95ab-764cfa811c49",
"tool_name": "from_scratch__use_subagent",
"arguments": {
"name": "pi-estimator",
"task": "Estimate pi."
}
}
{
"id_": "d3642d59-e0ff-487b-b05f-4769a1cbb760",
"tool_name": "from_scratch__use_subagent",
"arguments": {
"name": "pi-estimator",
"task": "Estimate pi."
}
}
{
"id_": "f452aea6-b430-428b-821b-ae59f203d7e8",
"tool_name": "from_scratch__use_subagent",
"arguments": {
"name": "pi-estimator",
"task": "Estimate pi."
}
}
{
"id_": "2c202b1b-5f3b-4a1d-9a87-e41a370fa3d8",
"tool_name": "from_scratch__use_subagent",
"arguments": {
"name": "pi-estimator",
"task": "Estimate pi."
}
}
{
"id_": "bf1b65b0-183f-434b-bec5-53a28e581611",
"tool_name": "from_scratch__use_subagent",
"arguments": {
"name": "pi-estimator",
"task": "Estimate pi."
}
}.
🔧 tool: {
"tool_call_id": "63398296-dc84-4f26-95ab-764cfa811c49",
"content": "The estimate is now in the target range, so the task is complete.\n\n**Result:**\n- **Sample ID:** `b5132d63-9cc5-494f-a3d1-15613e815368`\n- **Sample size:** 16,000,000 points\n- **Estimated π:** **3.14198425** (in target range [3.1415, 3.1425) ✓)\n\nThis converged after the initial 1M sample plus four doublings (1M → 2M → 4M → 8M → 16M points).",
"error": false
}
🔧 tool: {
"tool_call_id": "d3642d59-e0ff-487b-b05f-4769a1cbb760",
"content": "The estimate is now in the target range, so the task is complete.\n\n**Result:**\n- Sample ID: `97b0a2b6-90fd-47e4-b9fd-00db2def57c1`\n- Sample size: 4,000,000 points\n- Estimate of π: **3.141965**\n- In target range [3.1415, 3.1425): **True** ✓\n\nThe progression was:\n1. 1,000,000 points → 3.140012 (below range)\n2. 2,000,000 points → 3.141192 (below range)\n3. 4,000,000 points → **3.141965** (in range) ✓",
"error": false
}
🔧 tool: {
"tool_call_id": "f452aea6-b430-428b-821b-ae59f203d7e8",
"content": "The estimate is now in the target range, so the algorithm terminates.\n\n**Result:**\n- **sample_id:** `dfd075ed-8399-4003-bd00-1ac828df8d59`\n- **Final sample size:** 24,000,000 points\n- **Pi estimate:** **3.1415253333**\n- **in_target_range:** True (falls within [3.1415, 3.1425))\n\nFor reference, the progression was:\n\n| Sample size | Estimate | In range |\n|---|---|---|\n| 1,000,000 | 3.139196 | No |\n| 2,000,000 | 3.138826 | No |\n| 4,000,000 | 3.139938 | No |\n| 8,000,000 | 3.140741 | No |\n| 16,000,000 | 3.141446 | No |\n| 24,000,000 | 3.141525 | **Yes** |",
"error": false
}
🔧 tool: {
"tool_call_id": "2c202b1b-5f3b-4a1d-9a87-e41a370fa3d8",
"content": "{\"error_type\": \"MaxStepsReachedError\", \"subagent\": \"pi-estimator\", \"message\": \"Max steps reached.\"}",
"error": true
}
🔧 tool: {
"tool_call_id": "bf1b65b0-183f-434b-bec5-53a28e581611",
"content": "The estimate came back as **3.141792**, and `in_target_range` is **true** — it falls within [3.1415, 3.1425), so no additional points are needed.\n\n- **sample_id:** a82b891b-14d3-451f-b7e7-48ed7500a09c\n- **Estimate of pi:** 3.141792 (from 1,000,000 points)",
"error": false
}
💬 assistant: I need to make the following tool call(s):
{
"id_": "fdae8be3-f8b3-4eb2-98a5-cc6bd99e686e",
"tool_name": "from_scratch__use_subagent",
"arguments": {
"name": "pi-estimator",
"task": "Estimate pi."
}
}
{
"id_": "aa6dfb2e-a380-423f-b407-69c2027433fc",
"tool_name": "from_scratch__use_subagent",
"arguments": {
"name": "pi-estimator",
"task": "Estimate pi."
}
}
{
"id_": "75f437b6-6c5c-494e-a300-cff65bf93af5",
"tool_name": "from_scratch__use_subagent",
"arguments": {
"name": "pi-estimator",
"task": "Estimate pi."
}
}
{
"id_": "8ea57c5e-1e5a-40eb-abe7-dfe0479fecaa",
"tool_name": "from_scratch__use_subagent",
"arguments": {
"name": "pi-estimator",
"task": "Estimate pi."
}
}
{
"id_": "91b58955-95d4-40f1-bbfb-416c4be66522",
"tool_name": "from_scratch__use_subagent",
"arguments": {
"name": "pi-estimator",
"task": "Estimate pi."
}
}.
=== Task Step End ===
=== Task Step Start ===
💬 assistant: My current instruction is 'Execute the 5 dispatched tool calls to the pi-estimator subagent (IDs fdae8be3-f8b3-4eb2-98a5-cc6bd99e686e, aa6dfb2e-a380-423f-b407-69c2027433fc, 75f437b6-6c5c-494e-a300-cff65bf93af5, 8ea57c5e-1e5a-40eb-abe7-dfe0479fecaa, 91b58955-95d4-40f1-bbfb-416c4be66522) with task 'Estimate pi.' to collect more sample_ids toward the 20 independent estimates.'
💬 assistant: I need to make the following tool call(s):
{
"id_": "6fadcbab-ae5e-4b20-8ad7-494edeb731ef",
"tool_name": "from_scratch__use_subagent",
"arguments": {
"name": "pi-estimator",
"task": "Estimate pi."
}
}
{
"id_": "e61256d8-9729-4090-8069-662cd1003c6d",
"tool_name": "from_scratch__use_subagent",
"arguments": {
"name": "pi-estimator",
"task": "Estimate pi."
}
}
{
"id_": "f84ff9e9-0073-406f-8893-660b95396ed9",
"tool_name": "from_scratch__use_subagent",
"arguments": {
"name": "pi-estimator",
"task": "Estimate pi."
}
}
{
"id_": "bec5eef5-ce7b-435f-af3d-b220b753e3d7",
"tool_name": "from_scratch__use_subagent",
"arguments": {
"name": "pi-estimator",
"task": "Estimate pi."
}
}
{
"id_": "21fb0cd0-b1d4-4ca7-986d-d45832f4ff4d",
"tool_name": "from_scratch__use_subagent",
"arguments": {
"name": "pi-estimator",
"task": "Estimate pi."
}
}.
🔧 tool: {
"tool_call_id": "6fadcbab-ae5e-4b20-8ad7-494edeb731ef",
"content": "The estimate is in the target range.\n\n- **sample_id:** 47bcfd5a-d9ea-445d-8526-544240a4f057\n- **sample_size:** 1,000,000\n- **estimate of pi:** 3.141804\n- **in_target_range:** True (within [3.1415, 3.1425))\n\nThe task is complete with no additional points needed.",
"error": false
}
🔧 tool: {
"tool_call_id": "e61256d8-9729-4090-8069-662cd1003c6d",
"content": "The estimate came back as **3.141748** with `in_target_range: true`, so the task is complete on the first round.\n\n**Result:**\n- Sample ID: `0b01762e-af2d-4a32-83d8-ffd7923a868e`\n- Sample size: 1,000,000 points\n- Estimate of π: **3.141748** (within the target range [3.1415, 3.1425))\n- No additional points needed.",
"error": false
}
🔧 tool: {
"tool_call_id": "f84ff9e9-0073-406f-8893-660b95396ed9",
"content": "The estimate is now in the target range, so the task is complete.\n\n- **Sample ID:** `6be44a04-45c3-4bbc-98e7-3db51bf826ca`\n- **Final sample size:** 256,000,000 points\n- **Estimate of π:** **3.1416671875**\n- **In target range [3.1415, 3.1425):** True ✅\n\nThe sample was grown progressively (1M → 2M → 4M → 8M → 16M → 32M → 64M → 128M → 256M) until the Monte Carlo estimate fell within the required tolerance.",
"error": false
}
🔧 tool: {
"tool_call_id": "bec5eef5-ce7b-435f-af3d-b220b753e3d7",
"content": "The estimate is in range on the first try.\n\n- **Sample ID:** fbebad74-9bb4-435c-ae50-08f85d9edcf3\n- **Sample size:** 1,000,000 points\n- **Estimate of π:** 3.142244\n- **In target range [3.1415, 3.1425):** Yes ✓\n\nNo additional points were needed.",
"error": false
}
🔧 tool: {
"tool_call_id": "21fb0cd0-b1d4-4ca7-986d-d45832f4ff4d",
"content": "The estimate is now in the target range.\n\n- **sample_id:** `1a9aac58-68e0-45dc-a19e-d05d6b3d4586`\n- **sample_size:** 4,000,000 points\n- **estimate of π:** **3.142456**\n- **in_target_range:** True ✓ (falls within [3.1415, 3.1425))\n\nThe estimate converged as the sample grew: 3.141128 (1M) → 3.14268 (2M) → 3.142456 (4M). Task complete.",
"error": false
}
💬 assistant: I need to make the following tool call(s):
{
"id_": "7e95e6bd-c559-40fe-ae86-09143c1ad32d",
"tool_name": "from_scratch__use_subagent",
"arguments": {
"name": "pi-estimator",
"task": "Estimate pi."
}
}
{
"id_": "33331407-7fa4-4cd9-be09-d3baa22ca73c",
"tool_name": "from_scratch__use_subagent",
"arguments": {
"name": "pi-estimator",
"task": "Estimate pi."
}
}
{
"id_": "172ca093-688b-4a91-9dc3-d2999e5ef113",
"tool_name": "from_scratch__use_subagent",
"arguments": {
"name": "pi-estimator",
"task": "Estimate pi."
}
}
{
"id_": "ef0b04da-9b44-4a18-8282-fc9e0a8b673c",
"tool_name": "from_scratch__use_subagent",
"arguments": {
"name": "pi-estimator",
"task": "Estimate pi."
}
}
{
"id_": "a3a14772-2f1a-4523-a168-c0b146939ac5",
"tool_name": "from_scratch__use_subagent",
"arguments": {
"name": "pi-estimator",
"task": "Estimate pi."
}
}.
=== Task Step End ===
=== Task Step Start ===
💬 assistant: My current instruction is 'Execute the 5 remaining dispatched tool calls to the pi-estimator subagent (IDs 7e95e6bd-c559-40fe-ae86-09143c1ad32d, 33331407-7fa4-4cd9-be09-d3baa22ca73c, 172ca093-688b-4a91-9dc3-d2999e5ef113, ef0b04da-9b44-4a18-8282-fc9e0a8b673c, a3a14772-2f1a-4523-a168-c0b146939ac5) with task 'Estimate pi.' to collect the final sample_ids needed to reach 20 total independent estimates.'
💬 assistant: I need to make the following tool call(s):
{
"id_": "288733fc-ca31-413c-b6c4-7541b44c299e",
"tool_name": "from_scratch__use_subagent",
"arguments": {
"name": "pi-estimator",
"task": "Estimate pi."
}
}
{
"id_": "f17887a2-99aa-464d-9861-b83bf87e3f71",
"tool_name": "from_scratch__use_subagent",
"arguments": {
"name": "pi-estimator",
"task": "Estimate pi."
}
}
{
"id_": "e6377814-3c1b-4903-aa0e-09d519399a60",
"tool_name": "from_scratch__use_subagent",
"arguments": {
"name": "pi-estimator",
"task": "Estimate pi."
}
}
{
"id_": "503b2c8e-5be4-4aa4-922c-b950ed71493a",
"tool_name": "from_scratch__use_subagent",
"arguments": {
"name": "pi-estimator",
"task": "Estimate pi."
}
}
{
"id_": "cc35bd75-8af1-486d-b81d-f6eb8bf432a3",
"tool_name": "from_scratch__use_subagent",
"arguments": {
"name": "pi-estimator",
"task": "Estimate pi."
}
}.
🔧 tool: {
"tool_call_id": "288733fc-ca31-413c-b6c4-7541b44c299e",
"content": "The estimate is now in the target range. \n\n**Final result:**\n- Sample ID: `da634c49-1bd2-4e02-9e22-6817bf37c9ae`\n- Sample size: 8,000,000 points\n- **Estimate of π: 3.141974** ✅ (in target range [3.1415, 3.1425))\n\nThe estimation converged after four sample expansions (1M → 2M → 4M → 8M points).",
"error": false
}
🔧 tool: {
"tool_call_id": "f17887a2-99aa-464d-9861-b83bf87e3f71",
"content": "{\"error_type\": \"MaxStepsReachedError\", \"subagent\": \"pi-estimator\", \"message\": \"Max steps reached.\"}",
"error": true
}
🔧 tool: {
"tool_call_id": "e6377814-3c1b-4903-aa0e-09d519399a60",
"content": "The estimate is now in the target range.\n\n**Result:**\n- **Sample ID:** `3aace0c3-f803-4dfb-aab0-d6a81695b961`\n- **Sample size:** 2,000,000 points\n- **Estimate of π:** **3.141544**\n- **In target range [3.1415, 3.1425):** ✅ True\n\nAfter the first estimate at 1M points (3.143348) fell outside the target range, I added 1 million more points to the same sample, and the 2M-point estimate of π = 3.141544 landed within the target range, so the task is complete.",
"error": false
}
🔧 tool: {
"tool_call_id": "503b2c8e-5be4-4aa4-922c-b950ed71493a",
"content": "The estimate came back inside the target range on the first pass, so no additional points are needed.\n\n**Result:**\n- Sample ID: `14ae5bd1-61eb-44c3-b8c9-33beba1e4822`\n- Sample size: 1,000,000 points\n- Estimate of π: **3.141532**\n- In target range [3.1415, 3.1425): **True** ✓\n\nThe algorithm terminated after step 3 since the estimate was already in range.",
"error": false
}
🔧 tool: {
"tool_call_id": "cc35bd75-8af1-486d-b81d-f6eb8bf432a3",
"content": "The estimate is now in the target range.\n\n- **sample_id:** `1d853348-fa48-4e71-86a4-6db658a40105`\n- **sample_size:** 2,000,000 points\n- **estimate of π:** **3.14167**\n- **in_target_range:** True (falls within [3.1415, 3.1425))\n\nThe process: started with 1M points (estimate 3.141252, out of range), then added 1M more points (doubling to 2M), and the re-estimate landed at 3.14167 — within target. Task complete.",
"error": false
}
💬 assistant: I need to make the following tool call(s):
{
"id_": "657936eb-cd60-4cc0-8d43-437bb4b371d8",
"tool_name": "from_scratch__use_subagent",
"arguments": {
"name": "pi-estimator",
"task": "Estimate pi."
}
}
{
"id_": "7a438d44-1cc6-40f7-8eaa-c5c3772a6177",
"tool_name": "from_scratch__use_subagent",
"arguments": {
"name": "pi-estimator",
"task": "Estimate pi."
}
}
{
"id_": "4d27ac96-789f-4fb2-88d5-daa5ec8fb6d3",
"tool_name": "from_scratch__use_subagent",
"arguments": {
"name": "pi-estimator",
"task": "Estimate pi."
}
}
{
"id_": "523664be-b72b-4ec8-8da6-98ef5fe16cba",
"tool_name": "from_scratch__use_subagent",
"arguments": {
"name": "pi-estimator",
"task": "Estimate pi."
}
}
{
"id_": "c919bff3-c7ac-4b11-b9b7-f43acfdd7d17",
"tool_name": "from_scratch__use_subagent",
"arguments": {
"name": "pi-estimator",
"task": "Estimate pi."
}
}.
=== Task Step End ===
=== Task Step Start ===
💬 assistant: My current instruction is 'Execute the dispatched tool calls to the pi-estimator subagent (IDs 657936eb-cd60-4cc0-8d43-437bb4b371d8, 7a438d44-1cc6-40f7-8eaa-c5c3772a6177, 4d27ac96-789f-4fb2-88d5-daa5ec8fb6d3, 523664be-b72b-4ec8-8da6-98ef5fe16cba, c919bff3-c7ac-4b11-b9b7-f43acfdd7d17) with task 'Estimate pi.' to collect more sample_ids toward the 20 independent estimates.'
💬 assistant: I need to make the following tool call(s):
{
"id_": "7eb68a18-e828-4a00-8601-165641b5f876",
"tool_name": "from_scratch__use_subagent",
"arguments": {
"name": "pi-estimator",
"task": "Estimate pi."
}
}
{
"id_": "c7ce90a3-a88b-4974-8ecc-9e1bfbb75e1f",
"tool_name": "from_scratch__use_subagent",
"arguments": {
"name": "pi-estimator",
"task": "Estimate pi."
}
}
{
"id_": "76d558f0-d215-43ac-b7a6-ddf453390f0e",
"tool_name": "from_scratch__use_subagent",
"arguments": {
"name": "pi-estimator",
"task": "Estimate pi."
}
}
{
"id_": "16f3a24f-c737-4388-920b-b398bd41da73",
"tool_name": "from_scratch__use_subagent",
"arguments": {
"name": "pi-estimator",
"task": "Estimate pi."
}
}
{
"id_": "aa57b875-d872-41e9-ae69-04b41564f922",
"tool_name": "from_scratch__use_subagent",
"arguments": {
"name": "pi-estimator",
"task": "Estimate pi."
}
}.
🔧 tool: {
"tool_call_id": "7eb68a18-e828-4a00-8601-165641b5f876",
"content": "The estimate came back as 3.142296 with `in_target_range: true`, so the task is complete on the first pass—no additional points needed.\n\n**Result:**\n- Sample ID: `a033b6ac-7d8c-4a3e-b745-93c2e300186d`\n- Sample size: 1,000,000 points\n- π estimate: **3.142296**\n- In target range [3.1415, 3.1425): **Yes** ✓",
"error": false
}
🔧 tool: {
"tool_call_id": "c7ce90a3-a88b-4974-8ecc-9e1bfbb75e1f",
"content": "The estimate came back as **3.141648** with 1,000,000 points, and `in_target_range` is **True** (it falls within [3.1415, 3.1425)). No additional points are needed.\n\n**Result:**\n- Sample ID: `b0e4232d-a95d-4340-a988-3e0f21a9076a`\n- Sample size: 1,000,000\n- π estimate: **3.141648**\n- In target range: ✅ True",
"error": false
}
🔧 tool: {
"tool_call_id": "76d558f0-d215-43ac-b7a6-ddf453390f0e",
"content": "The estimate is now in the target range, so the process is complete.\n\n**Final answer:**\n- **sample_id:** `8a9b6ca8-5292-45d0-a638-24f6797d69da`\n- **sample_size:** 136,000,000 points\n- **π estimate:** **3.1415412647**\n- **in_target_range:** True (within [3.1415, 3.1425))\n\nThe sample was grown from 1M points through successive doublings (1M → 2M → 4M → 8M → 16M → 24M → 40M → 72M → 136M) until the Monte Carlo estimate landed inside the target range.",
"error": false
}
🔧 tool: {
"tool_call_id": "16f3a24f-c737-4388-920b-b398bd41da73",
"content": "The estimate is in range on the first try.\n\n- **sample_id:** `2e0f3435-7363-4375-bb35-08ebd38bc206`\n- **sample_size:** 1,000,000 points\n- **estimate of pi:** 3.141996\n- **in_target_range:** True (within [3.1415, 3.1425))\n\nDone — no additional points needed.",
"error": false
}
🔧 tool: {
"tool_call_id": "aa57b875-d872-41e9-ae69-04b41564f922",
"content": "The estimate on the 16,000,000-point sample is **3.141851**, and `in_target_range` is **true** — it falls within [3.1415, 3.1425).\n\n**Done:**\n- Sample ID: `a27c153d-bc00-47b4-beb5-a2b849e84008`\n- Final sample size: 16,000,000 points\n- Pi estimate: **3.141851** ✓ in target range\n\nProgression: 1M → 3.139256, 2M → 3.140148, 4M → 3.140713, 8M → 3.1411095, 16M → 3.141851 (in range).",
"error": false
}
💬 assistant: I need to make the following tool call(s):
{
"id_": "99684103-2873-4a16-b2a3-a12fcfdb44a4",
"tool_name": "from_scratch__use_subagent",
"arguments": {
"name": "pi-estimator",
"task": "Estimate pi."
}
}
{
"id_": "e5bc079f-104e-43eb-af94-99b2c93adca0",
"tool_name": "from_scratch__use_subagent",
"arguments": {
"name": "pi-estimator",
"task": "Estimate pi."
}
}.
=== Task Step End ===
=== Task Step Start ===
💬 assistant: My current instruction is 'Execute the dispatched tool calls to the pi-estimator subagent (IDs 99684103-2873-4a16-b2a3-a12fcfdb44a4 and e5bc079f-104e-43eb-af94-99b2c93adca0) with task 'Estimate pi.' by calling from_scratch__use_subagent for each, then collect the resulting sample_ids.'
💬 assistant: I need to make the following tool call(s):
{
"id_": "8d21413d-c38e-4e23-9926-24ce5b7a6eb1",
"tool_name": "from_scratch__use_subagent",
"arguments": {
"name": "pi-estimator",
"task": "Estimate pi."
}
}
{
"id_": "9fe93aa1-92f7-4dc2-a202-c1fb1efd6664",
"tool_name": "from_scratch__use_subagent",
"arguments": {
"name": "pi-estimator",
"task": "Estimate pi."
}
}.
🔧 tool: {
"tool_call_id": "8d21413d-c38e-4e23-9926-24ce5b7a6eb1",
"content": "The estimate at 2,000,000 points is **3.142498**, which falls within the target range [3.1415, 3.1425) — `in_target_range` is **True**.\n\n**Result:**\n- sample_id: `ee22d9a3-8950-4def-9f4a-36b8cf1e3b1f`\n- sample_size: 2,000,000 points\n- π estimate: **3.142498** ✓ (in target range)\n\nThe task is complete — no further iterations needed.",
"error": false
}
🔧 tool: {
"tool_call_id": "9fe93aa1-92f7-4dc2-a202-c1fb1efd6664",
"content": "The estimate is now in the target range.\n\n- **sample_id:** 6162f413-0d54-4b86-b0d8-f79f3a312e2c\n- **sample_size:** 4,000,000 points\n- **estimate:** 3.141995\n- **in_target_range:** True\n\nDone. After starting at 1M points (estimate 3.144952), then doubling to 2M (3.14418), then to 4M points, the Monte Carlo estimate converged to **3.141995**, which falls within the target range [3.1415, 3.1425).",
"error": false
}
💬 assistant: I need to make the following tool call(s):
{
"id_": "8db0d9f4-19ad-4bee-bc2d-0f249eb9cca0",
"tool_name": "compute_standard_error",
"arguments": {
"sample_ids": [
"b5132d63-9cc5-494f-a3d1-15613e815368",
"97b0a2b6-90fd-47e4-b9fd-00db2def57c1",
"dfd075ed-8399-4003-bd00-1ac828df8d59",
"a82b891b-14d3-451f-b7e7-48ed7500a09c",
"47bcfd5a-d9ea-445d-8526-544240a4f057",
"0b01762e-af2d-4a32-83d8-ffd7923a868e",
"6be44a04-45c3-4bbc-98e7-3db51bf826ca",
"fbebad74-9bb4-435c-ae50-08f85d9edcf3",
"1a9aac58-68e0-45dc-a19e-d05d6b3d4586",
"da634c49-1bd2-4e02-9e22-6817bf37c9ae",
"3aace0c3-f803-4dfb-aab0-d6a81695b961",
"14ae5bd1-61eb-44c3-b8c9-33beba1e4822",
"1d853348-fa48-4e71-86a4-6db658a40105",
"a033b6ac-7d8c-4a3e-b745-93c2e300186d",
"b0e4232d-a95d-4340-a988-3e0f21a9076a",
"8a9b6ca8-5292-45d0-a638-24f6797d69da",
"2e0f3435-7363-4375-bb35-08ebd38bc206",
"a27c153d-bc00-47b4-beb5-a2b849e84008",
"ee22d9a3-8950-4def-9f4a-36b8cf1e3b1f",
"6162f413-0d54-4b86-b0d8-f79f3a312e2c"
]
}
}.
=== Task Step End ===
=== Task Step Start ===
💬 assistant: My current instruction is 'Execute the compute_standard_error tool call with the 20 collected sample_ids to obtain the standard error, then respond with the final JSON output.'
💬 assistant: I need to make the following tool call(s):
{
"id_": "bd2759ca-d40e-42cc-829a-909e8f0b9dbf",
"tool_name": "compute_standard_error",
"arguments": {
"sample_ids": [
"b5132d63-9cc5-494f-a3d1-15613e815368",
"97b0a2b6-90fd-47e4-b9fd-00db2def57c1",
"dfd075ed-8399-4003-bd00-1ac828df8d59",
"a82b891b-14d3-451f-b7e7-48ed7500a09c",
"47bcfd5a-d9ea-445d-8526-544240a4f057",
"0b01762e-af2d-4a32-83d8-ffd7923a868e",
"6be44a04-45c3-4bbc-98e7-3db51bf826ca",
"fbebad74-9bb4-435c-ae50-08f85d9edcf3",
"1a9aac58-68e0-45dc-a19e-d05d6b3d4586",
"da634c49-1bd2-4e02-9e22-6817bf37c9ae",
"3aace0c3-f803-4dfb-aab0-d6a81695b961",
"14ae5bd1-61eb-44c3-b8c9-33beba1e4822",
"1d853348-fa48-4e71-86a4-6db658a40105",
"a033b6ac-7d8c-4a3e-b745-93c2e300186d",
"b0e4232d-a95d-4340-a988-3e0f21a9076a",
"8a9b6ca8-5292-45d0-a638-24f6797d69da",
"2e0f3435-7363-4375-bb35-08ebd38bc206",
"a27c153d-bc00-47b4-beb5-a2b849e84008",
"ee22d9a3-8950-4def-9f4a-36b8cf1e3b1f",
"6162f413-0d54-4b86-b0d8-f79f3a312e2c"
]
}
}.
🔧 tool: {
"tool_call_id": "bd2759ca-d40e-42cc-829a-909e8f0b9dbf",
"content": "{\"num_estimates\":20,\"mean\":3.1418865517769605,\"standard_error\":0.00006730785030765195}",
"error": false
}
💬 assistant: {"sample_ids": ["b5132d63-9cc5-494f-a3d1-15613e815368", "97b0a2b6-90fd-47e4-b9fd-00db2def57c1", "dfd075ed-8399-4003-bd00-1ac828df8d59", "a82b891b-14d3-451f-b7e7-48ed7500a09c", "47bcfd5a-d9ea-445d-8526-544240a4f057", "0b01762e-af2d-4a32-83d8-ffd7923a868e", "6be44a04-45c3-4bbc-98e7-3db51bf826ca", "fbebad74-9bb4-435c-ae50-08f85d9edcf3", "1a9aac58-68e0-45dc-a19e-d05d6b3d4586", "da634c49-1bd2-4e02-9e22-6817bf37c9ae", "3aace0c3-f803-4dfb-aab0-d6a81695b961", "14ae5bd1-61eb-44c3-b8c9-33beba1e4822", "1d853348-fa48-4e71-86a4-6db658a40105", "a033b6ac-7d8c-4a3e-b745-93c2e300186d", "b0e4232d-a95d-4340-a988-3e0f21a9076a", "8a9b6ca8-5292-45d0-a638-24f6797d69da", "2e0f3435-7363-4375-bb35-08ebd38bc206", "a27c153d-bc00-47b4-beb5-a2b849e84008", "ee22d9a3-8950-4def-9f4a-36b8cf1e3b1f", "6162f413-0d54-4b86-b0d8-f79f3a312e2c"], "standard_error": 0.00006730785030765195}
=== Task Step End ===
print(single_handler.result().content)
{"sample_ids": ["ba8a331d-0c68-4953-b72d-837987b415d2", "85341b40-ecbe-48c2-a2fe-3f9fadaa31ce", "6602d020-b262-40ea-a2fc-983f40b91f55", "cfc1196f-39a9-4184-af3b-14b382e45891", "8612eac5-c6fe-4a1d-96c3-f387bb5bf67c", "e7ba67a0-1f4d-4ade-b09b-a32466e2123b", "f43c3815-73b3-44d1-b883-7df75e4ef7eb", "d3ebdec6-b8e2-44fc-8baf-a25fb9fc32a3", "1428df19-ac76-44f5-b680-ee53afa4986f", "04f9ff50-bdc1-4917-98c1-cf39b1be5a43", "c68f6c55-2423-41e6-a450-bd41b8e27cf6", "7351a9c2-b081-4919-8670-809f5d600891", "9cc335a5-c847-43a3-9188-057bfb454761", "3bcae115-e9fc-45e9-999e-89b9e100e437", "eaa57ecf-2d69-4133-bdd4-5362ee060da2", "7df70aaf-3fba-4c57-9bce-60e952887bbe", "c0958083-60ea-457c-8620-5c884edd994e", "f7889bbf-619e-4859-bfaf-82ae4818f12d", "546becfb-dd0a-4d31-933d-fb4acfbc361d", "8e663074-6375-4171-b263-1d8f9d89acbe"], "standard_error": 0.00006957700784858352}
Trajectory Analysis¶
As in Capstone I, an LLM judge reads each trajectory, here for the failures that the ground-truth check cannot see.
trajectory_judge = make_llm(role="judge")
✓ Using Ollama Cloud (deepseek-v4.1-flash)
(Listing 10) Rubric for LLM judge¶
class TrajectoryEvalRubric(BaseModel):
"""Rubric for evaluating an execution trajectory."""
no_fabricated_results: bool = Field(
description=(
"True if every estimate, sample_id and standard error the agent "
"used came from an actual tool or subagent result"
),
)
followed_doubling_schedule: bool = Field(
description=(
"True if every sample that needed more points was grown by "
"doubling the points added each time. For a coordinator, judge "
"from what the subagent results report."
),
)
followed_output_format: bool = Field(
description=(
"True if agent's final response contained only the JSON, "
"with no additional text or explanation."
),
)
summary: str = Field(
description="One sentence summary of trajectory quality",
)
(Listing 11) LLM judge instruction prompt¶
The prompt adds one rule to Capstone I's. A step often ends by announcing its next tool call, which the following step then makes. Without the rule, a judge counts an announced call and the call itself as two calls.
judge_prompt_template = """Evaluate this trajectory of an agent estimating
the standard error of a Monte Carlo algorithm for estimating pi.
The task: produce {num_estimates} independent estimates of pi, each on its
own new sample and each in the range [3.1415, 3.1425), growing a sample by
doubling the points added each time (1M, 2M, 4M, ...), then compute the
standard error of the estimates with compute_standard_error.
The agent is one of two kinds:
- a single agent that calls generate_random_sample,
add_more_points_to_sample, monte_carlo_estimate and
compute_standard_error itself
- a coordinator that dispatches pi-estimator subagents with
`from_scratch__use_subagent` (each result is that subagent's final
answer; its own tool calls are not part of the trajectory) and calls
compute_standard_error itself
COUNTING TOOL CALLS: a step often ends with "I need to make the following
tool call(s)", announcing a call that the next step then makes. Count only
calls that are followed by a "🔧 tool:" result.
Note: If final_response is "Max steps error", the agent failed to complete
the task within the allowed number of steps.
<final_response>
{result}
</final_response>
<trajectory>
{trajectory}
</trajectory>
Evaluate and submit your judgment.""".strip()
async def judge(handler: LLMAgent.TaskHandler) -> TrajectoryEvalRubric:
"""Have the judge LLM evaluate a task's trajectory."""
return await trajectory_judge.structured_output(
prompt=judge_prompt_template.format(
num_estimates=NUM_ESTIMATES,
result=str(handler.exception() or handler.result()),
trajectory=handler.rollout,
),
mdl=TrajectoryEvalRubric,
)
single_eval = await judge(single_handler)
print(single_eval.model_dump_json(indent=4))
{
"no_fabricated_results": true,
"followed_doubling_schedule": true,
"followed_output_format": true,
"summary": "The agent correctly ran 20 independent samples, doubled sample sizes as required, obtained all estimates in range, and returned the exact JSON output with the standard error from the tool."
}
coordinator_eval = await judge(coordinator_handler)
print(coordinator_eval.model_dump_json(indent=4))
{
"no_fabricated_results": true,
"followed_doubling_schedule": false,
"followed_output_format": true,
"summary": "The coordinator correctly dispatched 20 subagents and computed the standard error from real results, but several subagents violated the doubling schedule (e.g., 1M→2M→4M→8M→16M→24M, or adding 1M to 1M instead of doubling, or growing 1M→2M→4M→8M→16M→24M→40M→72M→136M), so the doubling requirement was not consistently followed."
}
single_runs = []
for _ in range(NUM_REPLICATIONS):
handler, metrics = await run_and_measure(
single_agent,
single_agent_llm,
single_agent_instruction,
single_agent_max_steps,
)
single_runs.append((handler, metrics))
print(metrics)
{'task_success': True, 'wall_seconds': 97, 'steps': 21, 'rollout_chars': 107862, 'prompt_chars': 4476117}
{'task_success': True, 'wall_seconds': 473, 'steps': 157, 'rollout_chars': 272338, 'prompt_chars': 60445621}
{'task_success': True, 'wall_seconds': 123, 'steps': 23, 'rollout_chars': 99516, 'prompt_chars': 4829283}
coordinator_runs = []
for _ in range(NUM_REPLICATIONS):
handler, metrics = await run_and_measure(
coordinator,
subagents_llm,
coordinator_instruction,
coordinator_max_steps,
)
coordinator_runs.append((handler, metrics))
print(metrics)
{'task_success': True, 'wall_seconds': 133, 'steps': 5, 'rollout_chars': 24333, 'prompt_chars': 2450276}
{'task_success': True, 'wall_seconds': 129, 'steps': 5, 'rollout_chars': 24209, 'prompt_chars': 2113298}
{'task_success': False, 'wall_seconds': 31, 'steps': 1, 'rollout_chars': 5115, 'prompt_chars': 642594}
(Listing 13) Trajectory evaluations of individual runs¶
single_evals = []
for handler, _ in single_runs:
single_evals.append(await judge(handler))
coordinator_evals = []
for handler, _ in coordinator_runs:
coordinator_evals.append(await judge(handler))
Evaluation Summary¶
import pandas as pd
from llm_agents_from_scratch.notebook_utils import set_dataframe_display_options
# sets display options for pd.DataFrame in notebooks
set_dataframe_display_options()
def summarize(
runs: list[tuple[LLMAgent.TaskHandler, dict[str, Any]]],
evals: list[TrajectoryEvalRubric],
) -> pd.DataFrame:
"""Shape a system's runs and evaluations into a pd.DataFrame."""
df = pd.DataFrame(
[
{**metrics, **e.model_dump(exclude={"summary"})}
for (_, metrics), e in zip(runs, evals, strict=True)
],
)
return pd.concat(
[df, pd.DataFrame([df.sum(), df.mean()], index=["TOTAL", "AVG"])],
)
single_df = summarize(single_runs, single_evals)
single_df
| task_success | wall_seconds | steps | rollout_chars | prompt_chars | no_fabricated_results | followed_doubling_schedule | followed_output_format | |
|---|---|---|---|---|---|---|---|---|
| 0 | True | 97.0 | 21.0 | 107862.000000 | 4.476117e+06 | True | True | True |
| 1 | True | 473.0 | 157.0 | 272338.000000 | 6.044562e+07 | True | True | True |
| 2 | True | 123.0 | 23.0 | 99516.000000 | 4.829283e+06 | True | False | True |
| TOTAL | 3.0 | 693.0 | 201.0 | 479716.000000 | 6.975102e+07 | 3.0 | 2.0 | 3.0 |
| AVG | 1.0 | 231.0 | 67.0 | 159905.333333 | 2.325034e+07 | 1.0 | 0.666667 | 1.0 |
coordinator_df = summarize(coordinator_runs, coordinator_evals)
coordinator_df
| task_success | wall_seconds | steps | rollout_chars | prompt_chars | no_fabricated_results | followed_doubling_schedule | followed_output_format | |
|---|---|---|---|---|---|---|---|---|
| 0 | True | 133.000000 | 5.000000 | 24333.000000 | 2.450276e+06 | True | False | True |
| 1 | True | 129.000000 | 5.000000 | 24209.000000 | 2.113298e+06 | True | True | True |
| 2 | False | 31.000000 | 1.000000 | 5115.000000 | 6.425940e+05 | True | True | False |
| TOTAL | 2.0 | 293.000000 | 11.000000 | 53657.000000 | 5.206168e+06 | 3.0 | 2.0 | 2.0 |
| AVG | 0.666667 | 97.666667 | 3.666667 | 17885.666667 | 1.735389e+06 | 1.0 | 0.666667 | 0.666667 |
summary_df = pd.DataFrame(
{
"single agent": [e.summary for e in single_evals],
"coordinator + subagents": [e.summary for e in coordinator_evals],
},
)
summary_df
| single agent | coordinator + subagents | |
|---|---|---|
| 0 | The agent correctly generated 20 independent samples, doubled points on those not in range, re-estimated until all were in target range, and computed the standard error, returning only the required JSON. | The agent correctly dispatched 20 subagents in batches of 5 (plus a 5-id top-up after a miscount), used only real sample_ids and the returned standard error, and output exactly the JSON — but some subagent results violate the doubling schedule (e.g., going from 8M to 12M to 20M and 16M to 24M to 40M, and adding 1M after 1M). |
| 1 | The agent correctly generated 20 independent samples, doubled points as required until each estimate fell in the target range, and computed the standard error with a properly formatted JSON output using only real tool results. | The coordinator dispatched subagents in batches, gathered 20 valid sample_ids, correctly computed the standard error from real tool results, and followed the doubling schedule and output format. |
| 2 | The agent eventually reached a valid final answer, but it botched the doubling schedule—its initial add on each out-of-range sample was 1M, then it doubled to 4M, but the actual applied increments became non-power-of-two sizes (e.g., 6M→14M→30M and 62M→126M→254M→510M→1.022B→2.046B) because it double-counted earlier adds, so the 'doubling the points added each time' rule was violated. | The coordinator successfully dispatched 10 of 20 required subagents with valid results and correct doubling schedules, but the trajectory ended with a JSON validation error before collecting all 20 estimates and computing the standard error, so the task was not completed. |
(Listing 14) Comparing the two systems¶
The AVG rows side by side. The last column divides the subagent
system's value by the single agent's: below 1 means the subagent system
used less.
comparison_df = pd.DataFrame(
{
"single agent": single_df.loc["AVG"],
"coordinator + subagents": coordinator_df.loc["AVG"],
},
)
comparison_df["ratio"] = (
comparison_df["coordinator + subagents"] / comparison_df["single agent"]
)
comparison_df
| single agent | coordinator + subagents | ratio | |
|---|---|---|---|
| task_success | 1.0 | 0.666667 | 0.666667 |
| wall_seconds | 231.0 | 97.666667 | 0.422799 |
| steps | 67.0 | 3.666667 | 0.054726 |
| rollout_chars | 159905.333333 | 17885.666667 | 0.111852 |
| prompt_chars | 23250340.333333 | 1735389.333333 | 0.074639 |
| no_fabricated_results | 1.0 | 1.0 | 1.0 |
| followed_doubling_schedule | 0.666667 | 0.666667 | 1.0 |
| followed_output_format | 1.0 | 0.666667 | 0.666667 |
On a per-token API, the prompt_chars ratio is roughly the ratio of the
two systems' input bills. On a flat plan like Ollama Cloud, it is how
much of the plan's usage limits each system consumes.
def reported_se(handler: LLMAgent.TaskHandler) -> float | None:
"""The standard_error in a run's final answer, if it has one."""
if handler.exception():
return None
output = final_json(handler.result().content)
se = output.get("standard_error") if output else None
return se if isinstance(se, int | float) else None
se_df = pd.DataFrame(
{
"single agent": [reported_se(h) for h, _ in single_runs],
"coordinator + subagents": [
reported_se(h) for h, _ in coordinator_runs
],
},
)
se_df.style.format("{:.2e}", na_rep="no answer")
| single agent | coordinator + subagents | |
|---|---|---|
| 0 | 6.41e-05 | 7.06e-05 |
| 1 | 5.85e-05 | 6.05e-05 |
| 2 | 6.90e-05 | no answer |
(Listing 16) Simulating the algorithm without an LLM¶
To judge these numbers we need the algorithm's true standard error. The
algorithm is only arithmetic on random draws, so we can run it ourselves
many times. We don't even need the points: the number of points that
land inside the quarter circle, out of n, follows a binomial
distribution with probability π/4, so one rng.binomial() call stands in
for each generate_random_sample or add_more_points_to_sample call.
NUM_SIMULATIONS = 10_000
rng = np.random.default_rng(42)
def simulate_algorithm() -> tuple[float, int]:
"""One run of the algorithm. Returns the estimate and sample size."""
n = 1_000_000
inside = rng.binomial(n, math.pi / 4)
to_add = 1_000_000
while not TARGET_LOWER <= 4 * inside / n < TARGET_UPPER:
inside += rng.binomial(to_add, math.pi / 4)
n += to_add
to_add *= 2
return 4 * inside / n, n
simulated = np.array([simulate_algorithm() for _ in range(NUM_SIMULATIONS)])
sim_estimates, sim_sizes = simulated[:, 0], simulated[:, 1]
(Listing 17) Comparing the reported standard errors with the truth¶
The simulation gives the true standard error for NUM_ESTIMATES
estimates. It also shows how much a standard error computed from only
NUM_ESTIMATES estimates varies by chance: we draw NUM_ESTIMATES
simulated estimates many times and compute the standard error of each
draw. A reported standard error is as good as NUM_ESTIMATES estimates
allow when it falls inside the middle 95% of those.
true_se = sim_estimates.std(ddof=1) / math.sqrt(NUM_ESTIMATES)
k_estimate_ses = np.array(
[
rng.choice(sim_estimates, NUM_ESTIMATES).std(ddof=1)
/ math.sqrt(NUM_ESTIMATES)
for _ in range(NUM_SIMULATIONS)
],
)
low, high = np.percentile(k_estimate_ses, [2.5, 97.5])
print(f"True standard error: {true_se:.2e}")
print(f"Middle 95% of {NUM_ESTIMATES}-estimate SEs: [{low:.2e}, {high:.2e}]")
se_check_df = se_df.copy()
for system in se_df.columns:
se_check_df[f"{system} percentile"] = [
None if pd.isna(se) else round(100 * (k_estimate_ses < se).mean())
for se in se_df[system]
]
percentile_columns = [c for c in se_check_df.columns if "percentile" in c]
se_check_df.style.format(
"{:.2e}",
subset=list(se_df.columns),
na_rep="no answer",
).format("{:.0f}", subset=percentile_columns, na_rep="")
True standard error: 6.59e-05 Middle 95% of 20-estimate SEs: [4.96e-05, 7.94e-05]
| single agent | coordinator + subagents | single agent percentile | coordinator + subagents percentile | |
|---|---|---|---|---|
| 0 | 6.41e-05 | 7.06e-05 | 41 | 75 |
| 1 | 5.85e-05 | 6.05e-05 | 18 | 24 |
| 2 | 6.90e-05 | no answer | 66 |
(Listing 18) What the standard error does and doesn't tell us¶
The simulation also shows two properties of Capstone I's algorithm that its standard error hides.
median_size = np.median(sim_sizes)
print(f"Spread of one estimate: {sim_estimates.std(ddof=1):.2e}")
print(f"Even spread over the window: {0.001 / math.sqrt(12):.2e}")
print(
f"Plain Monte Carlo spread at the median sample size "
f"({median_size / 1e6:.0f}M): "
f"{math.sqrt(math.pi * (4 - math.pi) / median_size):.2e}",
)
print()
bias = sim_estimates.mean() - math.pi
print(f"Mean estimate: {sim_estimates.mean():.6f}")
print(f"Bias: {bias:+.2e} ({bias / true_se:.1f} standard errors)")
Spread of one estimate: 2.95e-04 Even spread over the window: 2.89e-04 Plain Monte Carlo spread at the median sample size (4M): 8.21e-04 Mean estimate: 3.141890 Bias: +2.97e-04 (4.5 standard errors)
First, the stopping rule sets the standard error, not the sample size. Every final estimate has to land in a window 0.001 wide, so the estimates spread almost evenly across it, and the spread of one estimate is close to that of an even spread, 0.001/√12. A plain Monte Carlo estimate with the same number of points would spread out about three times more. The algorithm looks this precise only because it stops once it is near the value of π it already knows.
Second, the estimates are biased, and the standard error can't show it.
The window [3.1415, 3.1425) is centred on 3.1420, not on π, so the
estimates average about 3.1419. That bias is several times the standard
error. A standard error measures how much the estimates vary, not how
close they are to the truth.
# write results to json
single_df.to_json("single_agent_df.json")
coordinator_df.to_json("coordinator_df.json")
summary_df.to_json("summary_df.json")
se_check_df.to_json("standard_error_df.json")