From 0c15eee31a41e53dc5155878cf7a9c0187956f3b Mon Sep 17 00:00:00 2001 From: Aikhan Jumashukurov <117706338+aikhanj@users.noreply.github.com> Date: Thu, 8 Oct 2026 19:24:33 -0400 Subject: [PATCH] Log token usage and model cost for every chat turn 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) --- app/src/server/pi.ts | 59 +++++++++++++++++ app/src/server/usage.ts | 138 ++++++++++++++++++++++++++++++++++++++++ app/tests/usage.test.ts | 71 +++++++++++++++++++++ 3 files changed, 268 insertions(+) create mode 100644 app/src/server/usage.ts create mode 100644 app/tests/usage.test.ts diff --git a/app/src/server/pi.ts b/app/src/server/pi.ts index 6399ee1..d3902f9 100644 --- a/app/src/server/pi.ts +++ b/app/src/server/pi.ts @@ -6,6 +6,14 @@ import { hasToolCall, tool, type UIMessage } from "ai"; import { z } from "zod"; import { EMPTY_WORKSPACES, workspaceContext, type WorkspaceState } from "../shared/workspaces"; import { handleWorkspaceRequest, WORKSPACE_KEY } from "./workspaces"; +import { + addStep, + costUsd, + emptyTurnUsage, + pseudonym, + type StepUsage, + type TurnUsage, +} from "./usage"; import { GCAL_CALLBACK_PATH, GCAL_MCP_URL, @@ -214,6 +222,12 @@ export class Pi extends Think { */ chatStreamStallTimeoutMs = 120_000; + /** This turn's token counts so far (see usage.ts); null between turns. */ + private turnUsage: TurnUsage | null = null; + private turnStartedAt = 0; + /** The model getModel() resolved, for pricing the turn. */ + private turnModel = DEFAULT_CLAUDE_MODEL; + getDefaultTimezone() { return "America/New_York"; } @@ -230,6 +244,7 @@ export class Pi extends Think { const model = CLAUDE_MODELS.has(preference) ? preference : DEFAULT_CLAUDE_MODEL; + this.turnModel = model; return createAnthropic({ apiKey: key })(model); } @@ -520,6 +535,8 @@ export class Pi extends Think { override async beforeTurn( ctx: Parameters[0] ): Promise extends infer R ? Awaited : never> { + this.turnUsage = emptyTurnUsage(); + this.turnStartedAt = Date.now(); const inherited = await super.beforeTurn(ctx); const settings = this.getConfig(); if (!settings) return inherited ?? undefined; @@ -617,15 +634,57 @@ export class Pi extends Think { override async onChatResponse(result: Parameters[0]) { await super.onChatResponse(result); + await this.logTurnUsage(result.status); await this.releaseIdleMcp(); } override async onChatError(error: unknown, ctx?: Parameters[1]) { const out = await super.onChatError(error, ctx); + await this.logTurnUsage("error"); await this.releaseIdleMcp(); return out; } + /** Every model call in a turn is billed, so each one is added up. */ + override async onStepEnd(ctx: Parameters[0]) { + await super.onStepEnd(ctx); + if (this.turnUsage) { + this.turnUsage = addStep(this.turnUsage, ctx.usage as StepUsage); + } + } + + /** + * One `pi.usage` line per turn, for the cost analysis. Runs once per turn: + * whichever of onChatResponse and onChatError comes first takes the total. + * Never allowed to fail the turn it's describing. + */ + private async logTurnUsage(status: string): Promise { + const usage = this.turnUsage; + if (!usage) return; + this.turnUsage = null; + try { + const netid = this.getConfig()?.netid ?? ""; + const cost = costUsd(this.turnModel, usage); + if (cost === null) { + console.warn(`usage: no price for ${this.turnModel}, add it to MODEL_PRICES`); + } + console.log( + JSON.stringify({ + event: "pi.usage", + status, + user: netid ? await pseudonym(netid, this.env.SESSION_SECRET ?? "") : null, + chat: this.name.slice(`u-${netid}-`.length), + model: this.turnModel, + ...usage, + costUsd: cost === null ? null : Math.round(cost * 1e6) / 1e6, + ms: Date.now() - this.turnStartedAt, + }) + ); + } catch (err) { + console.warn("usage: couldn't log this turn", err); + } + } + /** * Direct MCP tool call for non-chat surfaces (planner, agenda). Returns the * tool's JSON payload parsed from its text content. diff --git a/app/src/server/usage.ts b/app/src/server/usage.ts new file mode 100644 index 0000000..ac0f15f --- /dev/null +++ b/app/src/server/usage.ts @@ -0,0 +1,138 @@ +/** + * What a chat turn costs in model spend. One turn is several model calls (one + * per agent step), each resending the system prompt, the tool definitions and + * the history, so the turn's bill is the sum over its steps. Pi adds each + * step up as it finishes and logs one `pi.usage` line per turn, which is what + * the cost analysis reads (Workers Logs parses JSON lines into fields). + */ + +/** USD per million tokens, from Anthropic's price list. */ +type Price = { + input: number; + output: number; + cacheRead: number; + /** 5-minute cache writes, 1.25x input. */ + cacheWrite5m: number; + /** 1-hour cache writes, 2x input. */ + cacheWrite1h: number; +}; + +export const MODEL_PRICES: Record = { + "claude-opus-5": { input: 5, output: 25, cacheRead: 0.5, cacheWrite5m: 6.25, cacheWrite1h: 10 }, + "claude-sonnet-5": { input: 2, output: 10, cacheRead: 0.2, cacheWrite5m: 2.5, cacheWrite1h: 4 }, + "claude-opus-5-5": { input: 4, output: 20, cacheRead: 0.2, cacheWrite5m: 5, cacheWrite1h: 8 }, + "claude-sonnet-5-5": { input: 2, output: 10, cacheRead: 0.2, cacheWrite5m: 2.5, cacheWrite1h: 4 }, +}; + +/** Anthropic's server-side web search: $10 per 1,000 searches. */ +export const WEB_SEARCH_USD = 0.01; + +/** Token counts summed over one turn's steps. */ +export type TurnUsage = { + steps: number; + /** Input tokens billed at the full rate (not read from or written to cache). */ + input: number; + cacheRead: number; + cacheWrite5m: number; + cacheWrite1h: number; + /** All output tokens, reasoning included. */ + output: number; + reasoning: number; + webSearches: number; +}; + +export function emptyTurnUsage(): TurnUsage { + return { + steps: 0, + input: 0, + cacheRead: 0, + cacheWrite5m: 0, + cacheWrite1h: 0, + output: 0, + reasoning: 0, + webSearches: 0, + }; +} + +/** + * The part of the AI SDK's step usage this reads. With the Anthropic + * provider, `noCacheTokens`, `cacheReadTokens` and `cacheWriteTokens` are + * Anthropic's `input_tokens`, `cache_read_input_tokens` and + * `cache_creation_input_tokens`, and `raw` is Anthropic's own usage object. + */ +export type StepUsage = { + inputTokens?: number | undefined; + inputTokenDetails?: { + noCacheTokens?: number | undefined; + cacheReadTokens?: number | undefined; + cacheWriteTokens?: number | undefined; + }; + outputTokens?: number | undefined; + outputTokenDetails?: { reasoningTokens?: number | undefined }; + raw?: unknown; +}; + +const n = (value: unknown): number => + typeof value === "number" && Number.isFinite(value) && value > 0 ? value : 0; + +/** Adds one finished step to the turn's running total. */ +export function addStep(total: TurnUsage, usage: StepUsage | undefined): TurnUsage { + const raw = (usage?.raw ?? {}) as { + server_tool_use?: { web_search_requests?: unknown }; + cache_creation?: { ephemeral_1h_input_tokens?: unknown }; + }; + const cacheRead = n(usage?.inputTokenDetails?.cacheReadTokens); + const cacheWrite = n(usage?.inputTokenDetails?.cacheWriteTokens); + // Anthropic splits cache writes by TTL only in its raw usage; anything it + // doesn't mark as 1-hour is priced as the default 5-minute write. + const cacheWrite1h = Math.min(cacheWrite, n(raw.cache_creation?.ephemeral_1h_input_tokens)); + const noCache = usage?.inputTokenDetails?.noCacheTokens; + const input = + noCache !== undefined + ? n(noCache) + : Math.max(0, n(usage?.inputTokens) - cacheRead - cacheWrite); + return { + steps: total.steps + 1, + input: total.input + input, + cacheRead: total.cacheRead + cacheRead, + cacheWrite5m: total.cacheWrite5m + cacheWrite - cacheWrite1h, + cacheWrite1h: total.cacheWrite1h + cacheWrite1h, + output: total.output + n(usage?.outputTokens), + reasoning: total.reasoning + n(usage?.outputTokenDetails?.reasoningTokens), + webSearches: total.webSearches + n(raw.server_tool_use?.web_search_requests), + }; +} + +/** + * The turn's model spend in USD, or null for a model missing from + * MODEL_PRICES, so an unpriced model shows up as a gap rather than as $0. + */ +export function costUsd(model: string, usage: TurnUsage): number | null { + const price = MODEL_PRICES[model]; + if (!price) return null; + const tokens = + usage.input * price.input + + usage.cacheRead * price.cacheRead + + usage.cacheWrite5m * price.cacheWrite5m + + usage.cacheWrite1h * price.cacheWrite1h + + usage.output * price.output; + return tokens / 1_000_000 + usage.webSearches * WEB_SEARCH_USD; +} + +/** + * A stable, non-reversible id for a student in the logs, so the analysis can + * see how usage spreads across people without the logs carrying NetIDs. Keyed + * with a server secret because NetIDs are short enough to guess and hash. + */ +export async function pseudonym(netid: string, secret: string): Promise { + const enc = new TextEncoder(); + const key = await crypto.subtle.importKey( + "raw", + enc.encode(secret || "pi-dev"), + { name: "HMAC", hash: "SHA-256" }, + false, + ["sign"] + ); + const sig = new Uint8Array(await crypto.subtle.sign("HMAC", key, enc.encode(netid))); + return [...sig.slice(0, 8)].map((b) => b.toString(16).padStart(2, "0")).join(""); +} diff --git a/app/tests/usage.test.ts b/app/tests/usage.test.ts new file mode 100644 index 0000000..41b1976 --- /dev/null +++ b/app/tests/usage.test.ts @@ -0,0 +1,71 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { addStep, costUsd, emptyTurnUsage, pseudonym } from "../src/server/usage.ts"; + +// One Anthropic step as the AI SDK reports it: 1,000 uncached input tokens, +// 8,000 read from cache, 2,000 written (500 of them with the 1-hour TTL), +// 300 output of which 100 were reasoning, and two web searches. +const step = { + inputTokens: 11_000, + inputTokenDetails: { noCacheTokens: 1_000, cacheReadTokens: 8_000, cacheWriteTokens: 2_000 }, + outputTokens: 300, + outputTokenDetails: { reasoningTokens: 100 }, + raw: { + input_tokens: 1_000, + server_tool_use: { web_search_requests: 2 }, + cache_creation: { ephemeral_5m_input_tokens: 1_500, ephemeral_1h_input_tokens: 500 }, + }, +}; + +test("a step's tokens land in the right buckets", () => { + assert.deepEqual(addStep(emptyTurnUsage(), step), { + steps: 1, + input: 1_000, + cacheRead: 8_000, + cacheWrite5m: 1_500, + cacheWrite1h: 500, + output: 300, + reasoning: 100, + webSearches: 2, + }); +}); + +test("a turn's cost is every step priced at its own rate", () => { + const turn = addStep(addStep(emptyTurnUsage(), step), step); + assert.equal(turn.steps, 2); + // Per step on Opus 5: 1,000 x $5 + 8,000 x $0.50 + 1,500 x $6.25 + // + 500 x $10 + 300 x $25 = $30,875 per million tokens, plus $0.02 of search. + assert.ok(Math.abs(costUsd("claude-opus-5", turn)! - 2 * (0.030875 + 0.02)) < 1e-12); + // Sonnet 5: 1,000 x $2 + 8,000 x $0.20 + 1,500 x $2.50 + 500 x $4 + 300 x $10. + assert.ok(Math.abs(costUsd("claude-sonnet-5", addStep(emptyTurnUsage(), step))! - (0.01235 + 0.02)) < 1e-12); +}); + +test("missing detail falls back sensibly and never goes negative", () => { + const plain = addStep(emptyTurnUsage(), { inputTokens: 4_000, outputTokens: 50 }); + assert.equal(plain.input, 4_000); + assert.equal(plain.cacheWrite5m, 0); + assert.equal(plain.webSearches, 0); + + const derived = addStep(emptyTurnUsage(), { + inputTokens: 4_000, + inputTokenDetails: { cacheReadTokens: 3_000 }, + }); + assert.equal(derived.input, 1_000); + + const empty = addStep(emptyTurnUsage(), undefined); + assert.equal(empty.steps, 1); + assert.equal(costUsd("claude-opus-5", empty), 0); +}); + +test("an unpriced model reads as unknown, not free", () => { + assert.equal(costUsd("claude-mystery-9", addStep(emptyTurnUsage(), step)), null); +}); + +test("student ids in the logs are stable, short and not the NetID", async () => { + const a = await pseudonym("aj5828", "secret-one"); + assert.match(a, /^[0-9a-f]{16}$/); + assert.equal(await pseudonym("aj5828", "secret-one"), a); + assert.notEqual(await pseudonym("aj5828", "secret-two"), a); + assert.notEqual(await pseudonym("ab1234", "secret-one"), a); + assert.ok(!a.includes("aj5828")); +});