Skip to content

Log token usage and cost for every chat turn - #33

Merged
DIodide merged 2 commits into
mainfrom
feat/usage-logging
Nov 30, 2026
Merged

DIodide merged 2 commits into
mainfrom
feat/usage-logging

Conversation

@aikhanjum

@aikhanjum aikhanjum commented Oct 8, 2026 •

Copy link
Copy Markdown
Collaborator

First step of the cost analysis from the Oct 8 meeting. Before we can say what PI costs at N users, we need real cost per chat instead of guesses. This PR logs it for every turn.

What gets logged
After each turn, the chat object writes one JSON line to Workers Logs (observability is already on in wrangler.jsonc):

{"event":"pi.usage","status":"completed","user":"3f9a1c0e7b2d4a55","chat":"a1b2c3d4-e5f6","model":"claude-opus-5",
 "steps":3,"input":2140,"cacheRead":0,"cacheWrite5m":0,"cacheWrite1h":0,"output":612,"reasoning":180,
 "webSearches":0,"costUsd":0.026,"ms":14210}
  • steps counts the model calls in the turn. Every tool call adds a step, and each step resends the system prompt, the tool definitions and the history, so the turn's bill is the sum over all of them.
  • Input is split into uncached, cache read, 5-minute cache write and 1-hour cache write, and each is priced at its own rate. Web searches add $0.01 each.
  • user is an HMAC of the NetID keyed with SESSION_SECRET. That lets us see how usage spreads across students without NetIDs in the logs.
  • ms is wall time for the turn. The chat object is billed for that whole time, so this is what turns into Durable Object GB-s.
  • An unpriced model logs costUsd: null with a warning, so it shows up as a gap and not as free.

Code

  • src/server/usage.ts (new) holds the price table (Opus 5, Sonnet 5, Opus 5.5, Sonnet 5.5) and the pure functions addStep, costUsd and pseudonym.
  • src/server/pi.ts resets the counter in beforeTurn, adds each step in onStepEnd, and logs once in onChatResponse or onChatError, whichever comes first. Logging is wrapped so it can never fail a turn.
  • tests/usage.test.ts checks the buckets, the price math against hand-computed values, the fallbacks, unpriced models and the pseudonyms.

Testing

  • npm run typecheck, npm test (45 passing) and npm run build all pass.
  • I fed a recorded-shape Anthropic stream through the real AI SDK streamText into these functions. The counts matched (1,000 uncached, 8,000 cache read, 1,500 + 500 cache write, 300 output, 2 searches), and the cost came out to $0.050875, the same as by hand.
  • Not yet seen on live traffic. After deploy, filter Workers Logs on event = "pi.usage".

Next
The analysis doc (cost at 100, 500, 1k and 3k users, and free-tier breakpoints) uses these numbers. After that comes the rolling per-student usage limit on the desk object.

🤖 Generated with Claude Code

Each turn now ends with one structured pi.usage log line: model, steps,
uncached input, cache reads and writes, output, reasoning, web searches,
estimated USD and wall time, with the student as a keyed pseudonym
instead of a NetID. This is the data for the PI cost analysis and the
basis for a per-student usage limit.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
@aikhanjum

Copy link
Copy Markdown
Collaborator Author

Following up on #31, #32, #33, and #34 together to keep this in one place. The test, typecheck, and build checks pass on all four. Please review #33 before #34, since the weekly budget change is based on the usage logging branch. I would appreciate feedback on the set when convenient.

@DIodide DIodide left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed the usage accounting and lifecycle hooks after updating this branch with current main. No blocking findings. Token buckets, cache TTL pricing, search charges, and keyed user pseudonyms are covered by tests; normal/error completion clears the running total before logging. The selectable models here have known rates. Sonnet 5.5 pricing is corrected by the already-reviewed follow-up #49.

Validation: fresh npm ci, Wrangler types, typecheck, all 78 tests, production build, and git diff --check passed. Live provider billing reconciliation was not exercised.

@DIodide
DIodide merged commit 077455d into main Nov 30, 2026
2 checks passed
@DIodide
DIodide deleted the feat/usage-logging branch November 30, 2026 20:35
DIodide added a commit that referenced this pull request Nov 30, 2026
Stacked on #33, which adds the per-turn cost this budget counts. Review
#33 first. Once it merges, this PR will retarget to `main`.

Per Ibraheem: the limit is in dollars, copies PrincetonCourses' limit,
and uses a weekly window only.

**The limit**
PrincetonCourses' ask gateway
(`tiger-junction/apps/ask-gateway/app/usage_tracker.py`) gives each
student:
- **Tier 1:** $3.00 on any model, Opus 5 included
- **Tier 2:** another $1.00, Sonnet 5 only. Opus requests step down
automatically.
- **Exhausted:** after $4.00, no more answers until the window frees up

PrincetonCourses uses fixed 8-hour windows. PI uses one **rolling 7-day
window**, so each turn's cost stops counting exactly a week after it was
spent.

⚠️ This is $4 per week, where PrincetonCourses allows $4 per 8 hours, so
PI is about 21x tighter per week. If that wasn't the intent, it's a
config change. The amounts are Worker vars in `wrangler.jsonc`
(`USAGE_TIER1_USD`, `USAGE_TIER2_USD`), with no code change needed.

**How it works**
- **Ledger:** each student's desk object (`u-<netid>-desk`) gets a
`pi_usage` SQLite table (`at`, `micros`, `chat`). After every turn, the
chat records its cost from #33 there. That includes failed or stopped
turns, since they were still billed.
- **Pruning:** spend older than 7 days is deleted on the same write a
turn already causes. No alarms, so nothing wakes the desk on a timer.
- **Before each turn,** the chat asks the desk for the student's status:
- **Tier 2 with Opus selected:** the turn is answered by Sonnet 5
instead.
- **Exhausted:** the turn is answered by a stand-in model
(`notice-model.ts`) that streams the limit note ("You've used this
week's PI allowance. It frees up Thu, Oct 15, 3:10 PM.") and never calls
Anthropic. No MCP connections open, and nothing is billed.
- **If the desk can't answer,** the turn runs anyway and the error is
logged. The budget is for cost control, so an outage there shouldn't
take PI down.
- **The chat page** shows a note when a student is on Sonnet-only or out
of budget, with the time it frees up in Eastern time.

**Files**
- `src/shared/usage-limit.ts` (new): budget defaults, `budgetFrom(env)`,
`usageStatus` (rolling window, tier, when the next tier frees up), note
text
- `src/server/notice-model.ts` (new): the zero-cost stand-in model
- `src/server/pi.ts`: budget check and step-down in `beforeTurn`,
recording in `logTurnUsage`, desk RPCs `usageRecord` / `usageStatus`
- `src/client/pages/ChatPage.tsx`: the note
- `wrangler.jsonc`: `USAGE_TIER1_USD: "3"`, `USAGE_TIER2_USD: "1"`
- `tests/usage-limit.test.ts`: tiers, rolling window edges, reset times,
env parsing, Eastern time formatting, and the stand-in model streaming
the note with zero usage

**Testing**
- `npm run typecheck`, `npm test` (52 passing) and `npm run build` all
pass.
- I checked in Think 0.16's source that `getModel()` runs before
`beforeTurn`, and that a `model`, `maxSteps` and `activeTools` returned
from `beforeTurn` are what `streamText` gets.
- The desk's SQLite ledger only runs inside the Workers runtime, so it
isn't unit tested. Please run one signed-in turn on a preview and check
that a `pi_usage` row lands.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Aikhan Jumashukurov <117706338+aikhanj@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Co-authored-by: DIodide <ibraheem.amin3@gmail.com>
DIodide added a commit that referenced this pull request Nov 30, 2026
PI currently defaults to Opus and sends reusable prompt prefixes without
cache markers. This makes Sonnet 5.5 the default and adds Haiku 5.5,
including the request in
[TIG-311](https://linear.app/tigerapps/issue/TIG-311/add-prompt-caching-and-switch-pi-to-sonnet-55#comment-f3fd05b3).

- Apply five-minute cache breakpoints to the system prefix and final
conversation block for every Claude call, including tool-result
follow-ups and budget downgrades.
- Share model selection between browser preferences and the server.
Preserve existing Opus choices and migrate old Sonnet 5 or retired
choices to Sonnet 5.5.
- Keep Haiku selected when the weekly budget restricts Opus to Sonnet.
Leave the existing dollar allowances unchanged.
- Add Haiku pricing, applying its higher rates only to individual
requests above 100,000 prompt tokens. Correct Sonnet 5.5 cache-read
pricing using [Anthropic's price
list](https://platform.claude.com/docs/en/about-claude/pricing).

Stacked on #34, which depends on #33. Merge order is #33, #34, then this
PR.

Validation passed with the repository's example development variables.

- `npx wrangler types`
- `npm run typecheck`
- `npm test`, 78 passed and 0 failed
- `npm run build`
- `git diff --check`

Tests capture real SDK request bodies for all three models, including
streaming and tool results, and cover budget selection and Haiku pricing
thresholds. Provider responses are mocked. Live inference, signed-in UI
behavior, and actual cache hits have not been verified. The installed
Anthropic SDK accepts Haiku 5.5 through its compatibility path and emits
an informational 128,000-token output-limit warning.

Implemented with Codex assistance.

---------

Co-authored-by: Aikhan Jumashukurov <117706338+aikhanj@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Co-authored-by: DIodide <ibraheem.amin3@gmail.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants