Observability & Cost
What did that run do, where did the time go, and what did it cost? Three questions, two tables.
What you will be able to do
- Record one event per model call and per tool call, and read a run back as a waterfall
- Price a run from its four kinds of token, and know why an unknown price must never print as zero
- Turn on prompt caching in a hand-written loop and measure what it saves, cold and warm
- Read a stats table for failures, p50 and p95 without being fooled by a small sample
lesson-90. New: dayflow/observe.py, the events table, dayflow trace, dayflow stats,tests/test_observe.py. Changed: the loop times every call and sends cache markers; the brief footer shows dollars.What the footer was hiding
Since lesson 81 every brief has ended with a line like this:
[3 steps ยท 8 tool calls ยท 10885 in / 1828 out ยท run 8f21885c1f06]
It answers "how many tokens?" and nothing else. It does not say which step was slow, whether a tool failed, what the run cost, or whether today looks like yesterday. Lesson 89 ended on a question it could not answer: Haiku used 60% more output tokens than Sonnet for the same job, so is it actually cheaper? You need prices next to the counts.
Observability for an agent comes down to recording a small, boring fact every time something happens, in a place you can query later. Dayflow already has the place: the SQLite store from lesson 83.
One table: events
CREATE TABLE IF NOT EXISTS events ( run_id TEXT NOT NULL, step INTEGER NOT NULL, kind TEXT NOT NULL, -- model | tool name TEXT NOT NULL, -- model id, or tool name ms INTEGER NOT NULL, -- wall time of this call input_tokens INTEGER NOT NULL DEFAULT 0, -- uncached input output_tokens INTEGER NOT NULL DEFAULT 0, cache_read INTEGER NOT NULL DEFAULT 0, -- input served from the prompt cache cache_write INTEGER NOT NULL DEFAULT 0, -- input written to it ok INTEGER, -- tool rows: 1/0 code TEXT -- tool rows: refusal or error code. model rows: stop_reason ... );
The loop writes a row after each messages.create and after each tool call. That is the whole instrumentation: two time.perf_counter() pairs and two inserts. In a larger system these rows would be spans sent to a tracing backend. The shape is the same: who, what, how long, how it ended.
$ dayflow trace
run 8f21885c1f06 ยท brief ยท done ยท 2026-11-13T05:41:13+00:00
step what ms in cached write out cost outcome
1 claude-sonnet-5-5 1876 2217 0 0 212 $0.0066 tool_use
-> read_inbox 0 ok
-> read_calendar 0 ok
-> read_calendar 0 ok
-> read_tasks 0 ok
2 claude-sonnet-5-5 4953 3718 0 0 796 $0.0154 tool_use
-> create_task 0 pending_approval
-> create_task 0 pending_approval
-> draft_reply 1 pending_approval
-> draft_reply 0 pending_approval
3 claude-sonnet-5-5 5610 4950 0 0 820 $0.0181 end_turn
total 12440 10885 0 0 1828 $0.0401
model time 12439 ms (99%) ยท tool time 1 msFour things this one run makes obvious that the footer did not:
- All the time is the model. 99%, on fixtures. Against real Gmail the tool rows will not be zero, and this is the screen that tells you whether to optimise the prompt or the adapter.
- Latency follows output tokens. Step 1 writes 212 tokens in 1.9 s; step 3 writes 820 in 5.6 s. Input size barely matters. A shorter brief is a faster brief.
- Input is paid for three times. 2,217, then 3,718, then 4,950: each step re-reads everything before it. The inbox the model read at step 1 is billed again at steps 2 and 3. That is the thing caching fixes.
- The four writes were proposed, not made.
pending_approvalon each. The gate from lesson 86 is visible in the trace without reading a line of the brief.
Pricing a run
PRICES: dict[str, Price] = { # USD per million tokens: input, output, cache read, cache write
"claude-sonnet-5-5": Price(2.00, 10.00, 0.10, 2.50),
"claude-haiku-5-5": Price(0.10, 0.50, 0.01, 0.125),
"claude-opus-5-5": Price(4.00, 20.00, 0.20, 5.00),
}
def cost(model, *, input_tokens=0, output_tokens=0, cache_read=0, cache_write=0) -> float | None:
p = PRICES.get(model)
if p is None:
return None # an unknown cost must never print as $0.00
return (input_tokens * p.input + output_tokens * p.output
+ cache_read * p.cache_read + cache_write * p.cache_write) / 1_000_000Output tokens cost five times input on every model in the table. In the run above, 1,828 output tokens are $0.018 and 10,885 input tokens are $0.022: a sixth of the tokens, almost half the bill.
These numbers are copied from the course's model registry, and the cache-write price assumes the usual 1.25x of input. Nothing in the code checks them against an invoice. Treat every dollar figure in this lesson as "tokens times a table I should re-check". When a new model appears,
cost() returns None and the CLI prints n/a, because a dashboard that shows $0.00 for an expensive unknown model is worse than one that shows nothing.Prompt caching, measured
The API can store a prefix of your request and bill later reads of it at a fraction of the input price. You mark where a reusable prefix ends with cache_control. Dayflow marks two places:
def _cached_system(system: str) -> list[dict]:
"""Tools come before the system prompt in the cached prefix, so this one marker covers both."""
return [{"type": "text", "text": system, "cache_control": {"type": "ephemeral"}}]
def _cached_tail(messages: list[dict]) -> list[dict]:
"""A second breakpoint on the last block of the last message, so the next step reads
everything up to here from the cache. Returns a copy: stored history carries no markers."""Same brief, same fixtures, caching on:
step what ms in cached write out cost outcome
1 claude-sonnet-5-5 2193 98 2119 0 212 $0.0025 tool_use
2 claude-sonnet-5-5 5725 2 3716 0 808 $0.0085 tool_use
3 claude-sonnet-5-5 6115 2 3716 1247 898 $0.0125 end_turn
total 14035 102 9551 1247 1918 $0.0235| Sonnet 5.5, one brief on the fixtures | Cost | vs uncached |
|---|---|---|
| Caching off (three runs: $0.0410, $0.0423, $0.0401) | $0.041 | |
| Caching on, first run, nothing cached yet | $0.032 | 23% less |
| Caching on, run again within minutes (two runs: $0.0256, $0.0235) | $0.025 | 40% less |
Read those rows carefully, because only one of them is yours:
- The cold number is the real one for a daily brief. The cache lives for minutes. A brief that runs once a morning starts cold every time and saves the 23%, which comes from steps 2 and 3 re-reading what step 1 paid for.
- The warm number flatters. It happens here because the fixtures are identical on every run, so a second run finds the first run's prefix still cached. It is the right number for an eval suite or a busy multi-user service, and the wrong one to put in a budget for a personal agent.
- Output is untouched. Caching only discounts input. The $0.018 of output is the same in every row, and it is now most of the bill.
- No speed-up showed up. 12.4 s uncached, 14.0 s cached, single runs. Time here is output tokens, and those did not change.
With caching on,
usage.input_tokens is only the uncached part: 102 in the run above, where the model actually read 10,900. A token budget that adds up input_tokens would have quietly stopped guarding anything. The loop now counts all three kinds, andtest_cached_tokens_count_toward_the_token_budget pins it. Any time you turn caching on in an existing system, look for every place that reads that field.Across runs: stats
$ dayflow stats last 10 run(s) kind model runs failed p50 s p95 s in/run cached% out/run $/run $ total brief claude-haiku-5-5 3 0 13.2 14.3 11937 61% 2921 $0.0021 $0.0063 brief claude-sonnet-5-5 7 1 13.6 14.6 10918 43% 1909 $0.0327 $0.2292 failed x1: token budget exceeded
That answers lesson 89's open question. Haiku writes half as much again (2,921 output tokens against 1,909) and still costs about a fifteenth as much per brief, at the same speed. On the eval suite the two were indistinguishable. For this job, on these fixtures, the evidence points at Haiku, with the caveat lesson 89 already made: the suite has no check on summary quality.
Three habits for reading a table like this:
- Count before you trust a percentile. With three runs, "p95" is the slowest run. The function is nearest-rank on purpose so it never invents a value between samples.
- Failures get a reason, not just a count. "1 failed" sends you digging. "token budget exceeded" tells you which guard fired.
- The Sonnet row mixes cached and uncached runs. Its $0.0327 is an average of two different configurations, which is why the cached% column is there. An average over a change is a number about nothing.
Find where the money goes
About fifteen cents of API calls on Sonnet. Use a scratch database so your numbers are clean: export DAYFLOW_DB=/tmp/l90.db
- Run `pytest tests/test_observe.py -v`. 12 pass with no API key. Read test_cached_tokens_count_toward_the_token_budget and say what would have broken without it.
- Run `DAYFLOW_CACHE=0 dayflow brief --approve queue` then `dayflow trace`. Which step costs most, and is that because of its input or its output?
- Run `dayflow brief --approve queue` (caching on) and `dayflow trace`. Compare the in, cached and write columns step by step with the previous trace. Then run it once more within a minute and compare again.
- Work out your own cold saving: (uncached cost - first cached cost) / uncached cost. Is it near 23%? Why does the second cached run save more, and would your real morning brief get that?
- Run `DAYFLOW_MODEL=claude-haiku-5-5 dayflow brief --approve queue` three times, then `dayflow stats`. Compute Sonnet $/run divided by Haiku $/run from your own table.
- Make a run fail on purpose: `dayflow brief --approve queue --token-budget 9000`. Run `dayflow stats` and `dayflow trace`. At which step did the guard fire, and how much had been spent by then?
- Add a price for a model the table does not know, or remove one, and run `dayflow stats`. Confirm it prints n/a and never $0.0000.
- Open dayflow.db with sqlite3 and write one query the CLI does not offer: the slowest five model calls across all runs, with their output tokens. Does latency track output tokens in your data too?
What this lesson deliberately does not do
- Trace the SDK and orchestrated engines. Only the raw loop writes
events. The SDK reports its own cost, shown since lessons 84 and 85; bringing its messages into the same table is a gap, not a design. - Export to a tracing backend. The rows are already span-shaped. Sending them to OpenTelemetry or a hosted tool is an adapter, and SQLite is enough for one user on one machine.
- Alert.
dayflow statsis something you run. A scheduled check that pages you when failures or cost per run cross a line belongs with deployment, in the capstone. - Store prompts and outputs in the events. They are already in the
stepstable from lesson 83. Remember what that means: the database holds your email. Lesson 88's token-file warning applies todayflow.dbtoo. - Verify the price table. Said above, repeated here because it is the easiest thing in this lesson to get silently wrong.
One row per model call or tool call: kind, name, ms, tokens by type, outcome. The raw material for everything else.
One run as a waterfall. Shows where time and money went and what each tool call returned.
Recent runs by kind and model: failures with reasons, p50/p95, tokens, cached %, cost per run.
Uncached input, output, cache read, cache write. Each has its own price; output is 5x input.
cost() returns None and the CLI prints n/a. Never $0.00.
cache_control marks the end of a reusable prefix. Dayflow marks the system prompt (covers tools) and the tail of the conversation.
Measured on Sonnet 5.5: 23% cheaper cold, 40% warm. A once-a-day agent only ever gets the cold number.
Only the uncached part. Budgets and totals must add cache_read and cache_write.
Turns the markers off, for comparison.
Nearest-rank: with few runs it is simply the worst one. Count before you quote it.