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

usage-count.ts

135 lines4.6 KB

1import type { MetadataStore, ModelMessage, TokenUsage } from '@tanstack/ai'
2​
3/** The MetadataStore namespace of the saved usage. The key is the thread id. */
4export const USAGE_NAMESPACE = '@tanstack/ai-compaction:usage'
5​
6/** The usage of the last model call of a thread, and the list it got. */
7export interface UsageCount {
8 schemaVersion: 1
9 /** `promptTokens + completionTokens` of the call. */
10 tokens: number
11 /** How many messages the call got. Its reply comes after them. */
12 coveredCount: number
13 /** The hash of the last message the call got. */
14 lastCoveredHash: string
15 /** True when the call got a compacted view, not the canonical list. */
16 compacted: boolean
18​
19export async function hashMessages(
20 messages: ReadonlyArray<ModelMessage>,
21): Promise<string> {
22 const bytes = new TextEncoder().encode(JSON.stringify(messages))
23 const digest = await globalThis.crypto.subtle.digest('SHA-256', bytes)
24 return Array.from(new Uint8Array(digest), (byte) =>
25 byte.toString(16).padStart(2, '0'),
26 ).join('')
28​
29function isUsageCount(value: unknown): value is UsageCount {
30 return (
31 typeof value === 'object' &&
32 value !== null &&
33 'schemaVersion' in value &&
34 value.schemaVersion === 1 &&
35 'tokens' in value &&
36 typeof value.tokens === 'number' &&
37 'coveredCount' in value &&
38 typeof value.coveredCount === 'number' &&
39 Number.isInteger(value.coveredCount) &&
40 value.coveredCount >= 1 &&
41 'lastCoveredHash' in value &&
42 typeof value.lastCoveredHash === 'string' &&
43 'compacted' in value &&
44 typeof value.compacted === 'boolean'
45 )
47​
48/** The saved usage of a call that got `covered`. `undefined` for an empty list. */
49export async function toUsageCount(
50 covered: ReadonlyArray<ModelMessage>,
51 usage: TokenUsage,
52 compacted: boolean,
53): Promise<UsageCount | undefined> {
54 const last = covered.at(-1)
55 if (!last) return undefined
56 return {
57 schemaVersion: 1,
58 tokens: usage.promptTokens + usage.completionTokens,
59 coveredCount: covered.length,
60 lastCoveredHash: await hashMessages([last]),
61 compacted,
62 }
64​
65/**
66 * The token count of `messages` from a saved usage: the usage, plus the
67 * estimate of each message after the reply. `undefined` when the usage does
68 * not fit: none is saved, the list is shorter, the last covered message
69 * changed (a compaction or an edit), or the usage is of a compacted view and
70 * this call does not reuse the checkpoint of that view.
71 */
72export async function countFromUsage(
73 saved: unknown,
74 messages: ReadonlyArray<ModelMessage>,
75 estimate: (message: ModelMessage) => number,
76 reusedCheckpoint: boolean,
77): Promise<number | undefined> {
78 if (
79 !isUsageCount(saved) ||
80 (saved.compacted && !reusedCheckpoint) ||
81 messages.length < saved.coveredCount
82 ) {
83 return undefined
84 }
85 const last = messages[saved.coveredCount - 1]
86 if (!last || (await hashMessages([last])) !== saved.lastCoveredHash) {
87 return undefined
88 }
89 // completionTokens counts the reply. One reply can be more than one
90 // assistant message.
91 let start = saved.coveredCount
92 while (messages[start]?.role === 'assistant') start += 1
93 return messages
94 .slice(start)
95 .reduce((total, message) => total + estimate(message), saved.tokens)
97​
98/** A MetadataStore in memory, for a run that has none. The key is the thread. */
99export function memoryMetadata(): MetadataStore {
100 const threads = new Map<string, Map<string, unknown>>()
101 return {
102 get: async (namespace, key) => threads.get(key)?.get(namespace) ?? null,
103 set: async (namespace, key, value) => {
104 const values = threads.get(key) ?? new Map<string, unknown>()
105 // Delete, then set, so the thread moves to the newest place.
106 threads.delete(key)
107 threads.set(key, values.set(namespace, value))
108 // ponytail: keeps the 1000 newest threads; use a MetadataStore for more
109 const [oldest] = threads.keys()
110 if (threads.size > 1000 && oldest !== undefined) threads.delete(oldest)
111 },
112 delete: async (namespace, key) => {
113 threads.get(key)?.delete(namespace)
114 },
115 }
117​
118/**
119 * Add two usages. ponytail: only the token counts and `cost` add up. The
120 * details of a first usage are dropped when a second one comes.
121 */
122export function sumUsage(
123 total: TokenUsage | undefined,
124 next: TokenUsage,
125): TokenUsage {
126 if (!total) return next
127 return {
128 promptTokens: total.promptTokens + next.promptTokens,
129 completionTokens: total.completionTokens + next.completionTokens,
130 totalTokens: total.totalTokens + next.totalTokens,
131 ...(total.cost !== undefined && next.cost !== undefined
132 ? { cost: total.cost + next.cost }
133 : {}),
134 }