Repository navigation
Log token usage and cost for every chat turn - #33
Merged
Merged
Conversation
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>
Collaborator
Author
DIodide
approved these changes
Nov 30, 2026
DIodide
left a comment
Member
There was a problem hiding this comment.
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
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>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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}stepscounts 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.useris an HMAC of the NetID keyed withSESSION_SECRET. That lets us see how usage spreads across students without NetIDs in the logs.msis wall time for the turn. The chat object is billed for that whole time, so this is what turns into Durable Object GB-s.costUsd: nullwith 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 functionsaddStep,costUsdandpseudonym.src/server/pi.tsresets the counter inbeforeTurn, adds each step inonStepEnd, and logs once inonChatResponseoronChatError, whichever comes first. Logging is wrapped so it can never fail a turn.tests/usage.test.tschecks the buckets, the price math against hand-computed values, the fallbacks, unpriced models and the pseudonyms.Testing
npm run typecheck,npm test(45 passing) andnpm run buildall pass.streamTextinto 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.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