Sam Adeyemi wants to know which model the research assistant should run on. That's the capstone agent Chapter 14 (pending) designs. Priya Nair wants to know what one answered question will cost. A model's reputation can't answer either question, and neither can a public leaderboard. No leaderboard has called Kestrel's order and shipment tools, chosen between two similar tools, or had to finish inside Kestrel's run budget.
So this chapter chooses models the way you'd choose any dependency you have to run: by measuring candidates on your own tasks. The research assistant's tools don't exist yet, so six Kestrel operations tasks stand in for them. Chapter 16 (pending) re-runs the comparison on the capstone's own golden tasks before the final choice.
By the end of the chapter you'll be able to:
- name the six selection criteria that matter for agents and say which are gates and which are measurements;
- add a second ModelClient adapter, built on httpx, for any OpenAI-compatible endpoint, hosted or on your own server;
- run a harness that compares configured models on six Kestrel tasks by success, latency, tokens and cost;
- weigh open-weight against hosted without assuming either one always wins.
The chapter builds on Chapter 2 (tokens, cost, reasoning models), Chapter 3 (ModelClient and Settings), Chapter 4 (versioned prompt files), Chapter 5 (structured outputs), Chapter 6 (tool calling), Chapter 7 (run_agent, the run budget and StopCause), Chapter 8 (the redesigned operations tools and registry.py) and Chapter 9 (render_tool_result and count_tokens).
Model names, base URLs, keys and prices are configuration, so the prose says "a current model from your provider". Every output shown is fake-model output, labelled as such. The code is in books-code/agentic-ai-foundations/ch11-choosing-a-model/. Runs need the Kestrel mock API: uv run kestrel up serves it at http://127.0.0.1:8700.
1. Why a model's reputation tells you little about your agent
A chat model answers once. An agent calls the model on every step, so a model that picks the wrong tool now and then looks fine in a chat window, while in a seven-step run one wrong pick can derail every step after it.
The loop depends on a few specific behaviours. It needs tool calls whose arguments match the schema, the right choice between similar tools, a stop when the work is done rather than when the budget runs out, and a final answer that passes pydantic validation. Public leaderboards rarely test any of these on tools like yours, and this chapter quotes no public leaderboard scores.
On the autonomy spectrum, the agent under test stays at point 4: an agent with narrow tools and a tight budget, with read-only reach into orders, shipments, stock, tickets and policies. The comparison changes the model, not the agent's freedom. Sampling variability (Chapter 2) adds one rule: a single successful run proves little, so every task runs several times.
flowchart TD
A["Candidate configurations"] --> B{"Gates: data handling<br/>(incl. licence), context size"}
B -->|fails| X["Rejected"]
B -->|passes| C["Measure on Kestrel tasks"]
C --> D["Cheapest per success, above the<br/>per-task minimum, inside the time limit"]
D --> E["Re-measure when a<br/>model or price changes"]
E --> CThe harness is deliberately small: six tasks, a few runs each. Its tasks.py is a first form of golden tasks; Chapter 13 (pending) builds it into an eval with traces.
2. Six criteria that decide whether a model suits an agent
Tool-calling reliability. Are the arguments valid against the schema, and does the model pick the right tool when two look similar? OpenAI's chat completions reference (as of November 2026) warns that the model does not always generate valid JSON for function arguments, may invent parameters, and that you should validate arguments in code. The tool registry does that, and the harness counts its invalid-argument errors on every run.
Reasoning. For an agent, reasoning means succeeding on tasks that need more than one step of thought, such as combining a shipment record with the current policy. Measure it by the success rate on the harder tasks; simple lookups don't separate candidates.
Context size. The context window is a hard limit shared by input and output. Chapter 9's inspector shows what your requests take (system prompt, tool definitions, history, tool results), with provider counts where the adapter has them and a character estimate otherwise, so treat it as approximate for compatible endpoints. Add the output reserve and some headroom, and compare the total with the window the model's documentation states. A bigger window earns no extra credit if your runs never come close.
Latency. Measure wall-clock time per run and record the median and the slowest, because the slowest is the one that ends in time_limit. Latency is noisy (cold starts, hosted load through the day), so the harness runs sequentially and holds the prompt, tools and run budget constant. Sampling settings stay at each provider's defaults, so what's compared is the whole configuration.
Cost. Tokens multiplied by configured prices, summed per run rather than per call. A model that is cheap per call but needs twice the steps can cost more per answered question. Tokenizers differ, so read usage from each response and never reuse one token estimate across models.
Data handling. Where do prompts and tool results go, who stores them, for how long, under which terms, and, for open-weight models, under which licence? In production, Kestrel's tool results would carry real customer and commercial data. A configuration that fails this gate is out, whatever its numbers.
| Criterion | How to check it | Gate or measurement |
|---|---|---|
| Tool-calling reliability | Invalid-argument errors; required tools in the step log | Measurement |
| Reasoning | Success rate on the multi-step tasks | Measurement |
| Context size | Inspector counts plus reserve, against the documented window | Gate |
| Latency | Median and slowest run | Measurement |
| Cost | Usage × configured prices, summed per run | Measurement |
| Data handling | Provider terms, licence, company policy | Gate |
3. A second adapter: any OpenAI-compatible endpoint, over httpx
Chapter 3 put the Anthropic SDK behind ModelClient, and run_agent never imports a provider. But one adapter proves nothing about neutrality. A second one shows whether the interface really hides the provider.
The second adapter targets the OpenAI-compatible chat completions format, which many hosted providers and inference servers expose, including servers for open-weight models (models whose weights you can download and run yourself). As of November 2026, OpenAI's reference documents the shape this section uses: a tool result is a message with role tool and a tool_call_id; finish_reason is stop, length, tool_calls or content_filter; usage reports prompt_tokens and completion_tokens; reasoning_effort constrains reasoning; and a call's arguments are model-generated JSON. The test fixtures are hand-written to that shape, not recorded from any server, and compatible servers implement it with varying fidelity, so record your own server's responses before you rely on it (Exercise 4).
I'd write it against the HTTP endpoint with httpx, which the book already pins, rather than a second SDK: every request stays visible, tests swap the network for httpx.MockTransport, and the translation is the part worth understanding.
The important design point is what doesn't change. The adapter maps everything onto Chapter 7's shapes: the stop reasons finished, tool_call, truncated and other, Usage with input and output tokens, and ModelError with Chapter 3's five kinds (timeout, rate_limited, auth, bad_request, provider_error). model_client.py is copied from Chapter 9 untouched, so run_agent and its StopCause names work as they are. Like the fake model, the adapter's count_tokens returns Chapter 9's local estimate (provider_counts = False).
Configurations, not settings
The harness compares several candidates at once, so each one is a configuration in models.toml rather than a flat setting. A configuration names a provider, the environment variables holding its model name, key and base URL, an optional reasoning effort, and its price. Model names and keys stay in .env.
class Price(BaseModel):
currency: str = "USD"
input_per_mtok: Decimal = Field(ge=0) # strings in the file, parsed straight to Decimal
output_per_mtok: Decimal = Field(ge=0)
as_of: date # the day you read the seller's pricing page
source_url: str # that page
class ModelConfig(BaseModel):
name: str
provider: Literal["anthropic", "openai_compatible"]
model_env: str # the environment variable holding the model name
api_key_env: str
base_url_env: str | None = None # openai_compatible only
reasoning_effort: str | None = None # openai_compatible only; values depend on the model
max_tokens_param: str = "max_tokens" # openai_compatible: the output-limit field's name
price: Price | None = None # None: reported as unpriced, never as free
def make_client(
config: ModelConfig, settings: Settings, env: Mapping[str, str] = os.environ
) -> ModelClient:
if missing := missing_env(config, env):
raise ConfigError(f"not configured ({', '.join(missing)} empty)")
if config.provider == "anthropic":
if config.reasoning_effort: # fail at startup rather than drop the setting silently
raise ConfigError("reasoning_effort is only wired for openai_compatible here")
return AnthropicAdapter(
settings.model_copy(
update={
"model": env[config.model_env],
"api_key": SecretStr(env[config.api_key_env]),
}
)
)
if not config.base_url_env:
raise ConfigError("openai_compatible needs base_url_env")
return OpenAICompatibleAdapter(
settings,
base_url=env[config.base_url_env],
api_key=env[config.api_key_env],
model=env[config.model_env],
reasoning_effort=config.reasoning_effort,
max_tokens_param=config.max_tokens_param,
)Failures are loud on purpose. An empty variable raises ConfigError, which the harness reports as "not configured" instead of crashing. Reasoning effort is wired only into the compatible adapter here, so an Anthropic configuration that sets it fails at startup rather than having the setting silently dropped.
flowchart LR
subgraph internal["ModelClient shapes (Chapter 7)"]
S["system prompt"]
M["tool calls and tool results"]
T["tool definitions"]
R["stop reason and usage"]
end
subgraph wire["Chat completions wire format"]
WS["leading system-role message"]
WM["assistant tool_calls, one tool message per result"]
WT["function tools with JSON Schema parameters"]
WR["finish_reason and usage"]
end
S --> WS
M --> WM
T --> WT
WR -->|map| ROutbound: our shapes to the wire
The system prompt becomes a leading system message. Each tool definition is wrapped as a function tool with Chapter 6's pydantic-generated JSON Schema as parameters. Each tool result becomes its own tool message carrying the call id it answers, so parallel results go back as consecutive messages.
That tool message has no field for Chapter 6's is_error flag, which Chapters 6 and 7 rely on to steer the model towards recovery. Dropping it would make "provider-neutral" false, so the adapter prefixes error content with ERROR: .
def to_wire_messages(system: str, messages: Sequence[Message]) -> list[dict[str, Any]]:
wire: list[dict[str, Any]] = [{"role": "system", "content": system}] if system else []
for m in messages:
if m.tool_results: # one tool-role message per result, in order
for r in m.tool_results:
# The tool message has no error flag, so the flag travels in the text.
content = f"ERROR: {r.content}" if r.is_error else r.content
wire.append({"role": "tool", "tool_call_id": r.tool_call_id, "content": content})
continue
if not m.tool_calls:
wire.append({"role": m.role, "content": m.content})
continue
wire.append(
{
"role": "assistant",
"content": m.content or None,
"tool_calls": [
{
"id": c.id,
"type": "function",
"function": {"name": c.name, "arguments": json.dumps(c.arguments)},
}
for c in m.tool_calls
],
}
)
return wireInbound: the wire back to our shapes
Tool-call arguments arrive as a JSON string that, per the reference, may not be valid JSON or may include invented parameters. The adapter never drops a call and never crashes the run. A string that isn't a JSON object becomes a single arguments_not_json field, and an empty string means no arguments.
_STOP_REASONS: dict[str, StopReason] = {
"stop": "finished",
"tool_calls": "tool_call",
"length": "truncated",
} # anything else becomes "other", which the loop reports as unexpected_stop
def parse_arguments(raw: object) -> dict[str, Any]:
"""Arguments should be a JSON string. Never raise: a bad one becomes a field the registry
rejects, so the model gets an error result it can act on and the call is not lost."""
if isinstance(raw, dict): # tolerated: some servers send an object, not a string
return raw
if raw is None or (isinstance(raw, str) and not raw.strip()):
return {} # a tool with no parameters
try:
value = json.loads(raw) if isinstance(raw, str) else None
except json.JSONDecodeError:
value = None
return value if isinstance(value, dict) else {NOT_JSON: str(raw)}
def from_wire(body: dict[str, Any], request_id: str | None = None) -> ModelResponse:
choice = body["choices"][0]
message = choice["message"]
calls = [
ToolCall(
id=c["id"],
name=c["function"]["name"],
arguments=parse_arguments(c["function"].get("arguments")),
)
for c in message.get("tool_calls") or []
]
finish = choice.get("finish_reason") or ""
# Trust the content over the label: calls under "stop" are still calls. Calls cut off
# by the output limit stay "truncated", because their arguments are probably incomplete.
stop = "tool_call" if calls and finish != "length" else _STOP_REASONS.get(finish, "other")
usage = body.get("usage") or {}
return ModelResponse(
text=message.get("content") or "",
stop_reason=stop,
usage=Usage(
input_tokens=usage.get("prompt_tokens", 0),
output_tokens=usage.get("completion_tokens", 0),
),
tool_calls=calls,
request_id=request_id,
) try:
# Chapter 11: unknown fields are errors, not silently dropped
args = tool.args_model.model_validate(call.arguments, extra="forbid")
except ValidationError as exc:
message = validation_message(tool.name, exc, tool.hints)
return ToolResult(tool_call_id=call.id, content=message, is_error=True)Why an odd field rather than an error? Because Chapter 8's registry.py already turns bad arguments into error results, one line per field. This chapter changes one thing in it: dispatch validates with model_validate(call.arguments, extra="forbid"). In Chapter 8, pydantic silently ignored unknown fields. Once you compare weaker models, an invented parameter is a real failure that dropping it would hide; now it comes back as an error result the model can read and correct, and the harness counts it. The arguments_not_json field fails the same way. The capstone starter copies this registry, strictness included.
The adapter doesn't trust finish_reason alone: if a server reports stop while the message carries tool calls, the calls win, rather than being silently dropped. The exception is length: calls cut off by the output limit are probably incomplete, so they count as truncation. Anything unrecognised becomes other, which Chapter 7's loop already reports as unexpected_stop.
Usage keeps Chapter 3's rule: input_tokens counts all input. The adapter assumes prompt_tokens does too; check your server's documentation, and fix any difference here, never in the cost code.
The request and its retries
def _post(self, body: dict[str, Any], timeout: float | None) -> httpx.Response:
"""Like the SDK adapter: up to MAX_RETRIES extra attempts on rate limits, server errors
and connection failures, each with the same timeout. Retries are immediate here."""
extra = {"timeout": timeout} if timeout is not None else {}
for attempt in range(1 + self._settings.max_retries):
last = attempt == self._settings.max_retries
try:
response = self._http.post("/chat/completions", json=body, **extra)
response.raise_for_status()
return response
except httpx.HTTPStatusError as exc:
if last or exc.response.status_code not in RETRY_STATUSES:
raise to_model_error(exc) from exc
except httpx.TransportError as exc: # timeouts and connection failures
if last:
raise to_model_error(exc) from exc
raise AssertionError("unreachable")The timeout follows the Chapter 7 decision. complete() passes the loop's per-call timeout to httpx for each attempt, None keeps the client-wide MODEL_TIMEOUT_S, and MAX_RETRIES defaults to 1, matching the Anthropic adapter, where the SDK applies the same two settings. A rejected request (400, 401, 404) fails at once; rate limits, server errors and connection failures get the one retry, immediately. An immediate retry after a 429 often fails again; it is acceptable here only because there is exactly one, bounded by the run's time budget. When to back off and for how long is Chapter 16's subject (pending). The output-limit field's name comes from the configuration (max_tokens_param), because endpoints document different spellings.
Verifying the adapter
The tests replay the hand-written fixtures through httpx.MockTransport: plain answers, single and parallel calls, malformed and invented arguments, odd finish_reason values, an unreadable body, the retry rule and the ERROR: prefix. Two of them:
def test_invented_parameter_is_a_validation_error() -> None:
call = ask(Server(fixture("invented_parameter.json"))).tool_calls[0]
result = registry().dispatch(call)
assert result.is_error
assert "include_history: Extra inputs are not permitted; got True" in result.content
def test_run_agent_over_the_compatible_adapter() -> None:
server = Server(fixture("one_tool_call.json"), fixture("plain_answer.json"))
result = run_agent(adapter_with(server), "Be brief.", "Status of O-0000042?",
registry(), BUDGET, LIMITS) # fmt: skip
assert result.cause is StopCause.FINISHED
assert [m["role"] for m in server.requests[1]["messages"]][-1] == "tool"
assert result.steps[0].tool_calls[0].name == "get_order"The second test runs Chapter 7's run_agent, unchanged, over the new adapter: one tool step, a tool-role message in the next request, StopCause finished.
cd books-code/agentic-ai-foundations/ch11-choosing-a-model
uv run pytest -q tests/test_openai_compatible_adapter.py4. Pointing the adapter at a local open-weight server
The adapter doesn't care whether the endpoint is hosted or on your machine. The local-server configuration reads LOCAL_COMPAT_BASE_URL, LOCAL_COMPAT_API_KEY and LOCAL_COMPAT_MODEL. Use a placeholder key if your server ignores keys, because an empty variable counts as not configured.
Tool calling changes once you self-host. A model emits a tool call as text in its own format, and something has to turn that text into structured tool_calls. A hosted provider usually does it; a self-hosted server has to be configured to do it, and your server's own tool-calling documentation, for the version you run, is the place to check how.
A secondary write-up of a community thread about vLLM (not vLLM's documentation) reports that a misconfiguration fails in two shapes: missing tool-calling options produce a loud HTTP 400, and a parser that doesn't match the model is silent, returning the call as plain text with empty tool_calls.
Take that as an illustrative scenario rather than documented behaviour. In our loop the silent shape looks like success: a natural stop, zero tool calls, StopCause finished, and an answer never grounded in a tool result. Only a check against the task's expectations catches it.
The fixture empty_tool_calls.json pins down the adapter's half of that chain (it must report finished with no calls), and the harness catches the rest with its required-tool check, shown with the tasks below.
5. Prices as configuration and the cost of one run
Chapter 2 estimated cost as tokens times a configured price. The harness needs a price for every candidate, as does the capstone's money budget, so from this chapter a configuration's price lives with it in models.toml. Chapter 2's estimator keeps its own two settings for one-off estimates; the capstone's money budget takes its prices from models.toml.
# Copy to models.toml and replace every SET-ME. Each [[config]] is one candidate.
# Model names, keys and base URLs stay in .env; these entries only name the variables.
# A price is per million tokens, as strings, with the date you read it and the page you read.
# Loading fails while a SET-ME is left in a price. Delete a [config.price] table to run that
# candidate unpriced (a self-hosted server has no per-token price).
[[config]]
name = "hosted-sdk"
provider = "anthropic"
model_env = "MODEL"
api_key_env = "ANTHROPIC_API_KEY"
[config.price]
input_per_mtok = "SET-ME"
output_per_mtok = "SET-ME"
as_of = "SET-ME" # e.g. 2026-11-16
source_url = "SET-ME" # the seller's official pricing page
[[config]]
name = "hosted-compat-low-effort"
provider = "openai_compatible"
model_env = "OPENAI_COMPAT_MODEL"
api_key_env = "OPENAI_COMPAT_API_KEY"
base_url_env = "OPENAI_COMPAT_BASE_URL"
reasoning_effort = "low" # allowed values depend on the model; check its docs
max_tokens_param = "max_tokens" # set the name your endpoint's reference documents
[config.price]
input_per_mtok = "SET-ME"
output_per_mtok = "SET-ME"
as_of = "SET-ME"
source_url = "SET-ME"Prices are strings, parsed straight into Decimal, and SET-ME fails to parse, so the harness won't start with a placeholder price. A configuration with no price table, such as a self-hosted server, shows as unpriced, never free. Prices change, which is why as_of and source_url travel with every price.
"""The cost of a call and of a run, from the usage a provider reports and a configured price."""
from decimal import Decimal
from ch11.agent import RunResult
from ch11.configs import Price
from ch11.model_client import Usage
MTOK = Decimal(1_000_000)
def cost_of(usage: Usage, price: Price | None) -> Decimal | None:
"""None means unpriced. Callers show it as unpriced, never as zero."""
if price is None:
return None
return (
usage.input_tokens * price.input_per_mtok + usage.output_tokens * price.output_per_mtok
) / MTOK
def run_cost(result: RunResult, price: Price | None) -> Decimal | None:
"""Every model call in Chapter 7's step log, summed: cost per run, not per call."""
used = Usage(
input_tokens=sum(s.input_tokens for s in result.steps),
output_tokens=sum(s.output_tokens for s in result.steps),
)
return cost_of(used, price)
def next_call_ceiling(input_tokens: int, max_output_tokens: int, price: Price) -> Decimal:
"""What the next call can cost if it uses its whole output limit. A money budget
checks spend so far plus this before each call (Chapter 16 wires that in)."""
return (input_tokens * price.input_per_mtok + max_output_tokens * price.output_per_mtok) / MTOKcost_of prices every input token at the input rate. If you turn on a provider's prompt caching, which bills cached input differently, this figure overestimates; this book doesn't use caching.
That is the capstone contribution: a second adapter that makes the loop provider-neutral in practice, and a priced cost per run for its money budget to enforce.
6. Six Kestrel tasks and a harness that compares models
compare_models.py runs a fixed set of tasks against every candidate in models.toml. It never names a model. The unit being compared is a configuration: the same model at two reasoning efforts counts as two candidates, and hosted and self-hosted endpoints sit side by side.
The tools and the six tasks
ch11/tools.py registers a read-only tool set: Chapter 8's redesigned get_delivery_status, list_shipments, get_ticket and get_policy (descended from Chapter 7's operations agent), plus a new get_stock written to the same conventions. Chapter 8's create_return_authorisation is left out, because the harness runs each task several times and must never create records. Every task answers with one JSON object:
- Order status. The status of order O-0000042. One lookup.
- Late count. How many late Tallpine Logistics shipments are there? An aggregate, read from
list_shipments' total. - Most stock. Which of SKU-00042 and SKU-00043 has more units across both warehouses? Two independent lookups, so a model can make them as parallel calls.
- Ticket triage. The linked order, priority and status of ticket T-000042.
- Outdated policy. The standard delivery promise in working days.
/policiesalso holds a superseded shipping policy with a different number. - Shipment plus policy. Is the carrier of O-0000107's shipment one the current shipping policy lists, and was the shipment late? The superseded policy lists fewer carriers, so the answer depends on reading the right document and combining it with the shipment record.
Each task has an answer model and an expected function that reads the mock API when the check runs, so no status, stock level or policy number is hard-coded. Task 6's:
def expect_shipment_policy(api: httpx.Client) -> dict[str, Any]:
s = _get(api, "/orders/O-0000107/shipment")
carriers = re.search(r"Carriers in use[^:]*: (.+?)\.\s", current_shipping_policy(api))
assert carriers, "the current shipping policy no longer lists its carriers"
listed = [c.strip() for c in carriers.group(1).split(",")]
return {
"order_id": "O-0000107",
"carrier": s["carrier"],
"late": s["late"],
"carrier_in_current_policy": s["carrier"] in listed,
}Success is defined in one place:
@dataclass(frozen=True)
class Task:
task_id: str
prompt: str
required_tools: frozenset[str]
answer: type[BaseModel] # the JSON shape the final answer must have
expected: Callable[[httpx.Client], dict[str, Any]] # field values a correct answer has
def tools_called(result: RunResult) -> set[str]:
return {call.name for step in result.steps for call in step.tool_calls}
def failure_label(task: Task, result: RunResult, api: httpx.Client) -> str | None:
"""None means success; otherwise the label written to the results file."""
if result.cause is not StopCause.FINISHED:
return result.cause.value # step_limit, time_limit, model_error, ...
if task.required_tools - tools_called(result):
return "no required tool call" # a right answer without the lookup is a guess
try:
answer = task.answer.model_validate_json(result.final_text) # strict: no fence stripping
except ValidationError:
return "invalid structured output"
expected = task.expected(api)
return None if all(getattr(answer, k) == v for k, v in expected.items()) else "wrong answer"A run succeeds when it ends finished, every required tool appears in the step log, and the answer validates and matches. The middle condition matters more than it looks. A model that answers the order-status question correctly without calling the order tool has guessed, and it fails even when the guess is right. The same condition catches the silent parser mismatch.
The harness reuses Chapter 5's idea, pydantic models for the answer, but deliberately leaves out Chapter 5's validate-and-retry loop and any stripping of markdown fences. The capstone consumes these answers as JSON, so I'd rather the comparison penalise a fenced answer now. Strictness measures formatting discipline alongside capability; the "invalid structured output" label keeps the two apart in the results. Neither adapter uses a provider's native structured-output feature, so every configuration is judged by the same rule.
The system prompt is ch11/prompts/compare_v1.md, in Chapter 4's six sections. Its output-format section asks for exactly one JSON object with no code fences, and its don't-know rule asks for the NEEDS INFO marker instead of a guess.
Running and recording
cd books-code/agentic-ai-foundations/ch11-choosing-a-model
uv run kestrel up # terminal 1: http://127.0.0.1:8700
cp models.example.toml models.toml # then fill in the prices
uv run python -m ch11.compare_models # terminal 2: every configuration
uv run python -m ch11.compare_models --fake # scripted fakes; doesn't read models.tomlFor each configuration, the harness first checks the variables and lists any configuration it skips as "not configured". Then it makes one small preflight call:
def preflight(client: ModelClient) -> None:
"""One tiny call before any task. A rejected request (wrong model name, an effort value
the model doesn't accept, a bad key) is a configuration error, not a column of failures."""
try:
client.complete("", [Message(role="user", content="Reply with OK.")], max_tokens=64)
except ModelError as exc:
if exc.kind in ("auth", "bad_request"):
raise ConfigError(f"preflight rejected: {exc}") from exc
# timeouts and server errors: carry on; the runs record them as model_errorA rejected request is a configuration problem, such as a wrong model name or an effort value the model doesn't accept, so the configuration is skipped with the reason. Without the check, a typo would look like a model that can't answer anything. A timeout or server error doesn't skip it; those runs show up in the model_error column, kept apart from task failures so a flaky connection isn't read as a weak model.
Every task then runs COMPARE_RUNS times (default 3) through run_agent with the same run budget, so a model that never stops is cut off like any other. Each run writes one row to results/results.csv: configuration, task, success and label, StopCause, steps, tokens, cost, wall time and invalid-argument errors. (Traces, which record each step in full, are Chapter 13's.) The summary goes to results/summary.txt.
Here is the --fake run. It is fake-model output: the scripts' answers, token counts and prices are invented, and only the tool results come from the mock API. fake-correct makes the right calls; fake-wrong-tool calls a tool that doesn't exist, then gives the right answer anyway.
[fake model: scripted replies and token counts; tool results from Kestrel]
fake-correct
success 18/18 finished 18 model_error 0 invalid args 0
per task order-status 3/3 late-count 3/3 most-stock 3/3 ticket-triage 3/3 outdated-policy 3/3 shipment-plus-policy 3/3
wall s - (fake model: timing means nothing)
tokens mean 3140 per run
cost total 0.0666 USD per success 0.0037 USD
fake-wrong-tool
success 0/18 finished 18 model_error 0 invalid args 0
per task order-status 0/3 late-count 0/3 most-stock 0/3 ticket-triage 0/3 outdated-policy 0/3 shipment-plus-policy 0/3
wall s - (fake model: timing means nothing)
tokens mean 3140 per run
cost total 0.0666 USD per success n/a
failures no required tool call
local-server
skipped: not configured (LOCAL_COMPAT_MODEL, LOCAL_COMPAT_API_KEY, LOCAL_COMPAT_BASE_URL empty)
36 rows written to results/results.csv (expected 36)Judged on StopCause alone, both look perfect, and their total cost is identical. Only success and cost per success, the column that answers Priya, tell them apart.
7. Reasoning models on the same tasks: paying for reasoning tokens
Chapter 2 described a reasoning model as one that generates intermediate reasoning tokens before it answers. This section measures what that costs.
reasoning_effort is per configuration, and the compatible adapter sends it only when set. As of November 2026, OpenAI's reasoning guide says effort values are model-dependent and can include none, minimal, low, medium, high, xhigh and max, with lower effort favouring speed and lower token usage. Because the allowed set depends on the model, effort can't be one global setting.
Reasoning has a cost you never see in the response text. According to the same guide, the reasoning isn't visible through the API, but it occupies context-window space and is billed as output tokens. A community forum answer adds that there is no separate reasoning-token price. If that holds for your endpoint, the output count already includes the reasoning and cost_of needs no extra price. For any other endpoint, check whether its reported completion tokens include reasoning tokens; if they don't, cost and the future money budget undercount.
It matters for the output limit too. A limit sized for a short answer can be spent on reasoning before the answer starts, and the run ends truncated after paying for a call that produced nothing usable. tests/test_reasoning_cost.py shows both effects with the fake model:
def test_same_answer_more_reasoning_costs_more() -> None:
plain = run(answered(output_tokens=40)) # the answer alone
reasoning = run(answered(output_tokens=3_040)) # the same answer after hidden reasoning
assert plain.final_text == reasoning.final_text
assert run_cost(plain, PRICE) == Decimal("0.0012")
assert run_cost(reasoning, PRICE) == Decimal("0.0162") # input unchanged, output x76
def test_reasoning_can_spend_the_output_limit_before_the_answer() -> None:
result = run(answered(output_tokens=4_000, stop="truncated", text=""))
assert result.cause is StopCause.TRUNCATED
assert result.final_text == ""
assert run_cost(result, PRICE) == Decimal("0.021") # paid for, nothing usableWith a live compatible endpoint, configure one model twice, at low and high effort, and compare success on tasks 5 and 6 with tasks 1 to 4. I'd expect extra reasoning to pay off on the policy tasks and be wasted on the lookups. That's analysis, not a promised result; your table decides. Re-tune the run budget whenever you change configuration: reasoning inflates tokens and latency on every step, so a limit tuned for a non-reasoning model can stop good runs with token_limit or time_limit.
8. Open-weight or hosted: a trade-off, not a team you join
An open-weight model publishes its weights, so you can run it on your own hardware under licence terms that vary by model. As general background rather than a sourced claim: licences differ, and some restrict commercial use or particular applications, so read the one for the model you pick, and don't call a model open source unless its licence qualifies. A hosted model is one you reach only through a provider's API.
Data handling is the criterion people reach for first. Self-hosting keeps prompts and tool results on your infrastructure. A hosted provider processes them under its terms: retention, logging, region and permitted use. Neither is compliant by default. A self-hosted model still has a licence to read and infrastructure to secure, and a hosted one has terms your company must accept.
Operations are where self-hosting gets underestimated. Hardware, serving, tool-call parsing, upgrades and on-call become your team's work, and cost becomes fixed capacity, paid whether or not anyone sends a request. My reading is that self-hosting looks cheap only at sufficient, steady volume. If the research assistant answers a few dozen questions a day (an assumption, not a measured figure), expensive hardware sits idle most of the time.
Hosted models change prices, versions and deprecations on the provider's schedule; as_of shows how old a price is, and re-running the harness catches behaviour changes. Capability and latency don't follow from the category: "open-weight" doesn't mean weaker, and "hosted" doesn't mean faster. Hosting providers also serve open-weight models through compatible endpoints; for data handling, that's a hosted option.
| Open-weight, self-hosted | Hosted | |
|---|---|---|
| Data handling | Stays on your infrastructure; check the licence | Provider's terms; check them against company policy |
| Operations | Your team runs hardware, serving, parsing and upgrades | Provider runs it; you track its changes |
| Cost shape | Fixed capacity | Per-token price from models.toml |
| Change control | You choose when to upgrade | Provider's schedule |
| Capability and latency | Measure the configuration | Measure the configuration |
For Kestrel's capstone I would start with a hosted configuration, on stated assumptions. The research questions are read-only and the file tool reads synthetic exports. The web search tool sends queries to a search provider too, so check both sets of terms. If Priya's finance data or real customer records started appearing in tool results, I would reopen the data-handling gate first, then re-run the comparison with a self-hosted candidate.
9. Reading the results without fooling yourself
Read in a fixed order. Drop every configuration that fails a gate before looking at a single success count, or a fast, cheap model can talk you out of asking where its prompts go. Next, set a minimum success rate per task, not one average across six. Then, among the survivors, compare cost per success and the slowest run against the time limit. Read the model_error column separately: a cluster on one configuration is a reason to re-run, not a verdict.
Here is that procedure on an illustrative table, not a measured one:
| Configuration (illustrative) | Per-task minimum | Slowest run vs time limit | Cost per success |
|---|---|---|---|
| A | Fails task 5 on every run | Well inside | Lowest |
| B | Meets it everywhere | Some runs ended time_limit | Middle |
| C | Meets it everywhere | Well inside | Highest |
A has the lowest cost, and it's out: task 5 is the outdated-policy question, and failing it every time means quoting customers a superseded promise. B's time_limit runs say real questions will cross the limit; raise the limit and re-run, or treat B as failing. C costs most per success but clears every check, so C wins until a re-run says otherwise.
Six tasks at a few runs each is a small sample: treat configurations that differ by one success as tied, and re-run before reading anything into the gap. Write the choice down with the configuration, the date, the prompt version (compare_v1.md), the results file and a sentence of reasoning, so the next person who asks Sam's question can re-run it instead of taking your word for it.
10. Exercises
Exercise 1: a malformed call through the loop. Run run_agent over the compatible adapter with malformed_arguments.json followed by plain_answer.json. Expected: the registry returns an Invalid arguments error result, the second request carries it as a tool message starting ERROR: , and the run ends finished. Common mistake: handling the error in the adapter and dropping the call. The adapter translates; the registry decides.
Exercise 2: a seventh Kestrel task. Add "how many of the first 20 late Harbour Express shipments are still in transit?" with an answer model and an expected function computed from /shipments. Verify with two scripted fake-model runs, one that calls list_shipments and one that doesn't, which should fail with no required tool call.
Exercise 3: a missing price. In ch11/scripted.py, remove the price from fake-wrong-tool and re-run --fake. Expected: its cost shows unpriced and cost per success n/a, never zero.
Exercise 4 (needs your own endpoint). Point local-server or hosted-compat-low-effort at a real endpoint, run the harness, and save a few raw responses as fixtures beside the hand-written ones. If task 1 reports no required tool call, look for the silent parser mismatch. Then write Sam two paragraphs from results/summary.txt, leading with cost per success and the slowest run against the time limit.
11. Summary and what comes next
For an agent, choosing a model means gates first, then measurement. Data handling (including licence) and context size remove candidates. Tool-calling reliability, reasoning, latency and cost are numbers you collect on your own tasks, several runs each, before anyone says "this one".
The OpenAI-compatible adapter maps a second wire format onto Chapter 7's unchanged shapes. It keeps malformed calls for the registry to reject, derives the stop reason from what the response contains, and carries is_error across a format with no flag for it. Prices live with each configuration in models.toml, and cost_of reports unpriced rather than zero. Together they make the capstone provider-neutral and give its money budget a number to enforce. Reasoning effort is a configuration setting, and the reasoning it buys is billed as output. Open-weight versus hosted stays a trade-off, weighed per configuration.
Chapter 12 (pending) looks one layer up: when a library that runs the loop for you earns its place over the book's own loop.
