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

metrics.ts

212 lines5.7 KB

1import type { UIMessage } from '@tanstack/ai'
2​
3export interface TypeScriptAttempt {
4 toolCallId: string
5 typescriptCode: string
6 success?: boolean
7 errorName?: string
8 errorMessage?: string
9}
10​
11export interface ComputedMetrics {
12 totalToolCalls: number
13 totalExecuteCalls: number
14 successfulExecuteCalls: number
15 compilationFailures: number
16 runtimeFailures: number
17 redundantSchemaChecks: number
18 typeScriptAttempts: Array<TypeScriptAttempt>
20​
21export interface StarInputs {
22 accuracy: number
23 comprehensiveness: number
24 typescriptQuality: number
25 codeModeEfficiency: number
26 speedTier: number
27 tokenEfficiencyTier: number
28 stabilityTier: number
29 compilationFailures: number
30 runtimeFailures: number
31 totalExecuteCalls: number
33​
34export interface StarRating {
35 stars: 1 | 2 | 3
36 weightedScore: number
38​
39function safeJsonParse(value: string): unknown {
40 try {
41 return JSON.parse(value)
42 } catch {
43 return undefined
44 }
46​
47export function computeMetrics(messages: Array<UIMessage>): ComputedMetrics {
48 const toolCallLookup = new Map<string, { name: string; arguments: string }>()
49 const toolResultLookup = new Map<
50 string,
51 { content: string; state?: string; error?: string }
52 >()
53​
54 let totalToolCalls = 0
55 let totalExecuteCalls = 0
56 let redundantSchemaChecks = 0
57 let hasSeenSchemaCheck = false
58​
59 for (const message of messages) {
60 for (const part of message.parts) {
61 if (part.type === 'tool-call') {
62 totalToolCalls += 1
63 toolCallLookup.set(part.id, {
64 name: part.name,
65 arguments: part.arguments,
66 })
67​
68 if (part.name === 'getSchemaInfo') {
69 if (hasSeenSchemaCheck) redundantSchemaChecks += 1
70 hasSeenSchemaCheck = true
71 }
72 if (part.name === 'execute_typescript') {
73 totalExecuteCalls += 1
74 }
75 }
76​
77 if (part.type === 'tool-result') {
78 toolResultLookup.set(part.toolCallId, {
79 // `content` may be multimodal (`Array<ContentPart>`) since tool
80 // results can now carry images/etc. The eval only inspects the JSON
81 // string `execute_typescript` returns, so coerce non-string content
82 // to a serialized form that `safeJsonParse` can handle.
83 content:
84 typeof part.content === 'string'
85 ? part.content
86 : JSON.stringify(part.content),
87 state: part.state,
88 error: part.error,
89 })
90 }
91 }
92 }
93​
94 const typeScriptAttempts: Array<TypeScriptAttempt> = []
95 let compilationFailures = 0
96 let runtimeFailures = 0
97​
98 for (const [toolCallId, call] of toolCallLookup.entries()) {
99 if (call.name !== 'execute_typescript') continue
100​
101 const args = safeJsonParse(call.arguments) as
102 | { typescriptCode?: string }
103 | undefined
104 const result = toolResultLookup.get(toolCallId)
105 const parsedResult = result?.content
106 ? (safeJsonParse(result.content) as
107 | {
108 success?: boolean
109 error?: { name?: string; message?: string }
110 }
111 | undefined)
112 : undefined
113​
114 const success = parsedResult?.success
115 const errorName = parsedResult?.error?.name
116 const errorMessage = parsedResult?.error?.message || result?.error
117 if (success === false) {
118 if (errorName === 'TypeScriptError') compilationFailures += 1
119 else runtimeFailures += 1
120 }
121​
122 typeScriptAttempts.push({
123 toolCallId,
124 typescriptCode: args?.typescriptCode || '',
125 success,
126 errorName,
127 errorMessage,
128 })
129 }
130​
131 return {
132 totalToolCalls,
133 totalExecuteCalls,
134 successfulExecuteCalls: typeScriptAttempts.filter((a) => a.success).length,
135 compilationFailures,
136 runtimeFailures,
137 redundantSchemaChecks,
138 typeScriptAttempts,
139 }
141​
142export function formatTypescriptEvidence(
143 attempts: Array<TypeScriptAttempt>,
144): string {
145 if (attempts.length === 0) {
146 return 'No execute_typescript calls were made.'
147 }
148​
149 return attempts
150 .map((attempt, idx) => {
151 const code = attempt.typescriptCode || '<missing typescriptCode>'
152 const status =
153 attempt.success === true
154 ? 'success'
155 : attempt.success === false
156 ? `failed (${attempt.errorName || 'Error'}: ${attempt.errorMessage || 'unknown'})`
157 : 'unknown'
158 return [
159 `### Attempt ${idx + 1} (${attempt.toolCallId})`,
160 `status: ${status}`,
161 '```typescript',
162 code,
163 '```',
164 ].join('\n')
165 })
166 .join('\n\n')
168​
169function clamp01(value: number): number {
170 if (value < 0) return 0
171 if (value > 1) return 1
172 return value
174​
175function normalizeTenPoint(value: number): number {
176 return clamp01((value - 1) / 9)
178​
179function normalizeFivePoint(value: number): number {
180 return clamp01((value - 1) / 4)
182​
183function failurePenalty(inputs: StarInputs): number {
184 if (inputs.totalExecuteCalls <= 0) return 0.4
185 const failureRate =
186 (inputs.compilationFailures + inputs.runtimeFailures) /
187 inputs.totalExecuteCalls
188 return clamp01(1 - failureRate)
190​
191export function computeStarRating(inputs: StarInputs): StarRating {
192 const codeModeBlended =
193 normalizeTenPoint(inputs.codeModeEfficiency) * 0.7 +
194 failurePenalty(inputs) * 0.3
195​
196 const weightedScore =
197 normalizeTenPoint(inputs.accuracy) * 0.25 +
198 normalizeTenPoint(inputs.comprehensiveness) * 0.15 +
199 normalizeTenPoint(inputs.typescriptQuality) * 0.15 +
200 codeModeBlended * 0.1 +
201 normalizeFivePoint(inputs.speedTier) * 0.1 +
202 normalizeFivePoint(inputs.tokenEfficiencyTier) * 0.1 +
203 normalizeFivePoint(inputs.stabilityTier) * 0.15
204​
205 const stars: 1 | 2 | 3 =
206 weightedScore >= 0.75 ? 3 : weightedScore >= 0.45 ? 2 : 1
207​
208 return {
209 stars,
210 weightedScore: Number(weightedScore.toFixed(4)),
211 }