Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

usage.md

239 lines10.9 KB

1---
2title: Track usage and cost
3id: harness-usage
4order: 7
5description: "Read the tokens and the cost of a thread, in total, by model, by sender, by run, and by plugin. Show a live total, stop a person who is over budget, and add /usage with your own prices."
6keywords:
7 - tanstack ai
8 - harness
9 - usage
10 - cost
11 - tokens
12 - billing
13---
14​
15Your app bills each person for what they use, or stops a thread that costs too much. For that, you need the tokens and the cost of every model call, per thread and per person. The harness adds up every model call of a thread, and `session.usage()` returns the totals.
16​
17## Read the totals
18​
19```ts group=harness-usage
20import { createHarnessHost, defineHarness } from '@tanstack/ai-harness'
21import { memoryPersistence } from '@tanstack/ai-persistence'
22import { openaiText } from '@tanstack/ai-openai'
23​
24export const assistant = defineHarness({
25 name: 'acme/assistant',
26 adapter: openaiText('gpt-6.1-sol'),
27})
28​
29const host = createHarnessHost({ persistence: memoryPersistence() })
30const session = await host.open(assistant, {
31 threadId: 'team-thread',
32 user: { id: 'ada' },
33})
34​
35await session.send('Summarize the open tickets.')
36​
37const { total, byModel, bySender } = session.usage()
38console.log(total.calls, total.totalTokens, total.cost)
39console.log(byModel['openai/gpt-6.1-sol']?.totalTokens, bySender.ada?.cost)
40```
41​
42The totals have four groups. `snapshot().usage` has the same data:
43​
44- `total`: every model call of the thread.
45- `byModel`: the calls of each model, keyed by `provider/model`, for example `openai/gpt-6.1-sol`.
46- `bySender`: the calls of each person, keyed by the user id. It has only the calls of a known sender, so its sum can be less than `total`.
47- `bySource`: the model calls that are not a turn or an agent run, keyed by their source: `plugin:<name>`, `router`, or `transfer`. See [Usage of plugins](#usage-of-plugins).
48​
49Each entry has `calls`, `promptTokens`, `completionTokens`, `totalTokens`, `cachedTokens`, and `cacheWriteTokens`. If a provider reported a cost, the entry also has `cost`. The harness adds the costs that the providers report, in their currency. It uses no price list of its own.
50​
51## What counts
52​
53At the end of each call, the provider reports its usage. These calls count:
54​
55- The model calls of each turn, for the sender of that turn.
56- The subagents that a turn starts, for the same sender.
57- Background agents, for the person who started the agent.
58- A harness that runs as a child with [`harnessAgent`](./subagents#call-a-harness-as-a-child), for the same person.
59- The model calls of plugins with `ctx.model.chat`, for the user of their run.
60- The model calls of the router with `model.chat`, for the sender of the turn.
61- The summary of a transfer with `messages: 'summary'`, for the person who made the transfer, in the source thread.
62​
63A call that fails before it ends does not count. Each message runs as its sender, so in a [shared thread](./shared-threads), `bySender` shows what each person used.
64​
65## Where the totals live
66​
67The totals stay with the thread. The host keeps one `harness.usage` record per call in the log, so a durable log store keeps the totals after a restart.
68​
69A [fork of a thread](./fork-and-reset) starts at zero.
70​
71## Usage of one run
72​
73One agent run used much more than the others, and you want to know which one. Each `harness.usage` record in the log has the `runId` of the run that made the call: a turn, or an agent run. Add them up per run:
74​
75```ts group=harness-usage
76import { logIdOf } from '@tanstack/ai-harness'
77import type { LogStore } from '@tanstack/ai-persistence'
78​
79// The tokens of the model calls that each run made itself.
80export async function tokensByRun(log: LogStore, threadId: string) {
81 const tokens = new Map<string, number>()
82 for (const { record } of await log.read({ logId: logIdOf({ logId: threadId }) })) {
83 if (record.type !== 'harness.usage' || typeof record.runId !== 'string') continue
84 const { usage } = record
85 if (typeof usage !== 'object' || usage === null || !('totalTokens' in usage)) continue
86 if (typeof usage.totalTokens !== 'number') continue
87 tokens.set(record.runId, (tokens.get(record.runId) ?? 0) + usage.totalTokens)
88 }
89 return tokens
91```
92​
93- A call also counts for each run above its run in the [run tree](./subagents#the-run-tree). So the use of a run includes the use of its children.
94- When an agent run ends, its run record gets `usage`: the tokens of the run and of all its children. It is in the `harness.run.update` record of the end.
95- To stop a run that uses too much, give it a `budget`. See [Give one run a budget and a time limit](./subagents#give-one-run-a-budget-and-a-time-limit).
96​
97## Usage of plugins
98​
99A goal judge or a title writer calls a model next to the turn, and you want to see what these calls cost. A plugin that calls its model with [`ctx.model.chat`](./plugins#call-a-model-from-a-plugin) counts each call under its own name:
100​
101```ts group=harness-usage
102import { title } from '@tanstack/ai-harness/plugins'
103​
104export const titled = defineHarness({
105 name: 'acme/titled',
106 adapter: openaiText('gpt-6.1-sol'),
107 plugins: () => [title({ adapter: openaiText('gpt-6-luna') })],
108})
109​
110const titledSession = await host.open(titled, { threadId: 'titled-thread' })
111await titledSession.send('Plan a trip to Rome.')
112​
113const { bySource } = titledSession.usage()
114console.log(bySource['plugin:tanstack/title']?.totalTokens)
115```
116​
117- The title call runs next to the turn, so its usage can arrive a moment after the turn ends.
118- The calls of a plugin also count in `total`, `byModel`, and `bySender`, and in the use of their run.
119- The calls of turns and agent runs have no source, so they are not in `bySource`.
120- Each `harness.usage` record of a plugin call has `source`, and the `label` of the call when it has one. The `goal()` judge has the label `judge`, `title()` has `title`, and `/compact` has `compact`.
121​
122## Usage of the router and transfers
123​
124Two more kinds of calls run outside a turn model call. Each one has its own source in `bySource`:
125​
126- `router`: the calls of [`model.chat` in the router](./subagents#count-the-model-calls-of-the-router). They also count in the use of the turn.
127- `transfer`: the summary call of a [transfer](./handoffs) with `messages: 'summary'`. Its record has the label `summary`. It counts in the source thread, also when the transfer fails later.
128​
129```ts group=harness-usage
130const { router, transfer } = session.usage().bySource
131console.log(router?.totalTokens, transfer?.totalTokens)
132```
133​
134## Show a live total
135​
136Want a token counter that ticks up while the chat runs? `session.onUsage` calls you after each model call, with the new thread totals:
137​
138```ts group=harness-usage
139const stopCounting = session.onUsage(({ total }) => {
140 console.log(`Tokens so far: ${total.totalTokens}`)
141})
142​
143// When the counter goes away:
144stopCounting()
145```
146​
147You also get the `model`, the `sender` when it is known, and the `usage` of that one call. A call of a plugin or of the router also has its `source`, and its `label` when it has one. Reading raw events? Each call is a `harness.usage` event (`HARNESS_EVENTS.usage`).
148​
149## Stop a person who is over budget
150​
151Read the totals of the sender before you send a prompt. This route refuses a prompt from a person who used more than their budget:
152​
153```ts group=harness-usage
154const BUDGET_USD = 5
155​
156export async function send(threadId: string, userId: string, text: string) {
157 const thread = await host.open(assistant, { threadId, user: { id: userId } })
158 const spent = thread.usage().bySender[userId]?.cost ?? 0
159 if (spent >= BUDGET_USD) {
160 return { error: 'You used your budget for this thread.' }
161 }
162 return thread.send(text).receipt
164```
165​
166Many providers report no cost, so `cost` can stay empty. For those, compare the token counts with a budget in tokens.
167​
168## Show the tokens in a list of sessions
169​
170With `stores.sessions`, each [session index](./sessions) entry has a `usage` field. The host writes the token counts of `session.usage()` at the end of each turn. `turns` is the number of model calls.
171​
172```ts group=harness-usage
173const page = await host.sessions.list({ limit: 20 })
174for (const entry of page.entries) {
175 console.log(entry.title ?? 'New chat', entry.usage?.totalTokens ?? 0)
177```
178​
179A background agent can end after the turn. Then the index entry counts its tokens at the end of the next turn.
180​
181## Show usage and price the calls
182​
183Many providers report no cost, so `cost` stays empty. The `usage()` plugin adds a `/usage` command, and can price those calls with your own price list:
184​
185```ts group=harness-usage
186import { usage } from '@tanstack/ai-harness/plugins'
187​
188// USD per 1M tokens, by model id.
189const prices: Record<string, { input: number; output: number; cacheRead?: number }> = {
190 'gpt-6.1-sol': { input: 2, output: 8, cacheRead: 0.2 },
192​
193export const priced = defineHarness({
194 name: 'acme/priced',
195 adapter: openaiText('gpt-6.1-sol'),
196 plugins: () => [
197 usage({
198 model: (id) => {
199 const cost = prices[id]
200 return cost === undefined ? undefined : { cost }
201 },
202 }),
203 ],
204})
205```
206​
207`session.runCommand({ name: 'usage' })` reads `session.usage()` and shows the total. When the thread used more than one model, it also shows a line for each model:
208​
209```text
2103 model calls, 41200 input tokens (30000 cache read, 0 cache write), 2100 output tokens, 43300 total. Cost: $0.0432.
211openai/gpt-6.1-sol: 2 model calls, 40000 input tokens (30000 cache read, 0 cache write), 2000 output tokens, 42000 total.
212openai/gpt-6-luna: 1 model calls, 1200 input tokens, 100 output tokens, 1300 total.
213```
214​
215How the plugin finds the cost:
216​
217- A call with a cost from its provider keeps that cost, as it is.
218- `model` prices only the calls with no provider cost. It gets the model id without the provider, like `gpt-6.1-sol`. It returns `{ cost }` with prices in USD per 1M tokens, or `undefined`.
219- Without `model`, `/usage` shows `Cost:` only when a provider reported a cost.
220- A call with no price adds a note, for example `(cost unknown for 1 call)`.
221​
222The plugin also writes the cost to `usage.cost` of the session index entry, whenever it has one. `session.usage()` keeps only the costs that the providers report.
223​
224The plugin state, `snapshot().plugins['tanstack/usage']`, has a copy of `session.usage().total` and `contextTokens`: the input tokens of the latest call of the lead model. Compare it with the context window of the model to show how full the context is.
225​
226Limits of the plugin:
227​
228- For one model, when some calls have a provider cost and others do not, `model` does not price the others.
229- On a host with a log, the cost in the index entry and the state copy can miss the last call of a run. They get it at the end of the next run.
230​
231## What you have now
232​
233- The tokens and the cost of a thread, in total, by model, by sender, and by plugin.
234- The tokens of each run, with the use of its children in the run above them.
235- Totals that stay after a restart.
236- A live total from the `harness.usage` event.
237- A budget check before each prompt.
238- The token counts of each session in the session index.
239- `/usage` with your own prices, and a cost for each session in the session index.