Repository navigation
Expand file tree
/
Copy pathdownsample.tool.ts
More file actions
281 lines (256 loc) · 9.43 KB
/
Copy pathdownsample.tool.ts
File metadata and controls
281 lines (256 loc) · 9.43 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
import { createTool } from '@mastra/core/tools'
import { z } from 'zod'
import { log } from '../config/logger'
import lttb from 'downsample-lttb'
import { SpanType, getOrCreateSpan } from '@mastra/core/observability'
export const downsampleTool = createTool({
id: 'downsample',
description:
'Downsample numeric series using LTTB (Largest Triangle Three Buckets)',
inputSchema: z.object({
values: z.array(z.number()).describe('Numeric series to downsample'),
target: z.number().min(2).describe('Target number of samples'),
algorithm: z.enum(['lttb', 'min-max', 'm4']).optional().default('lttb'),
}),
outputSchema: z.object({
indices: z.array(z.number()),
values: z.array(z.number()),
originalLength: z.number(),
target: z.number(),
}),
strict: true,
onInputStart: ({ toolCallId, messages }) => {
log.info('Downsample tool input streaming started', {
toolCallId,
messages: messages ?? [],
hook: 'onInputStart',
})
},
onInputDelta: ({ inputTextDelta, toolCallId, messages }) => {
log.info('Downsample tool received input chunk', {
toolCallId,
inputTextDelta,
messages: messages ?? [],
hook: 'onInputDelta',
})
},
onInputAvailable: ({ input, toolCallId, messages }) => {
log.info('Downsample tool received input', {
toolCallId,
messages: messages ?? [],
inputData: {
valuesCount: input.values.length,
target: input.target,
},
hook: 'onInputAvailable',
})
},
execute: async (input, context) => {
const writer = context?.writer
// Create root span using getOrCreateSpan (creates root OR attaches to parent)
const rootSpan = getOrCreateSpan({
type: SpanType.TOOL_CALL,
name: 'downsample',
input,
metadata: {
'tool.id': 'downsample',
'tool.input.valuesCount': input.values.length,
'tool.input.target': input.target,
'tool.input.algorithm': input.algorithm,
},
requestContext: context?.requestContext,
})
// Create child span for downsampling operation
const downsampleSpan = rootSpan?.createChildSpan({
type: SpanType.TOOL_CALL,
name: 'downsample-operation',
input,
metadata: {
'tool.id': 'downsample-exec',
'operation.type': input.algorithm,
},
})
await writer?.custom({
type: 'data-tool-progress',
data: {
status: 'in-progress',
message: `Input: target=${input.target} - 📉 Starting downsampling`,
stage: 'downsample',
},
id: 'downsample',
})
const { values, target, algorithm } = input
const originalLength = values.length
if (target >= originalLength || originalLength <= 2) {
const result = {
indices: values.map((_, i) => i),
values: values.slice(),
originalLength,
target,
}
downsampleSpan?.update({
output: result,
metadata: {
'operation.completed': true,
},
})
downsampleSpan?.end()
rootSpan?.update({
output: result,
metadata: {
'tool.output.success': true,
'tool.status': 'skipped',
},
})
rootSpan?.end()
await writer?.custom({
type: 'data-tool-progress',
data: {
status: 'done',
message: `Input: target=${input.target} - ✅ No downsampling needed`,
stage: 'downsample',
},
id: 'downsample',
})
// Nothing to do: return full series indices
return result
}
try {
let result
if (algorithm === 'lttb') {
// Build points as [index, value]
const points: Array<[number, number]> = values.map((v, i) => [
i,
Number.isFinite(v) ? v : NaN,
])
const decimated: Array<[number, number]> = lttb(points, target)
const indices = decimated.map((p) =>
Math.max(0, Math.min(originalLength - 1, Math.round(p[0])))
)
const sampledValues = indices.map((i) => values[i])
result = {
indices,
values: sampledValues,
originalLength,
target,
}
} else {
// Min-max and M4 algorithms
const bucketSize = Math.max(
1,
Math.floor(originalLength / target)
)
const indices: number[] = []
for (
let start = 0;
start < originalLength;
start += bucketSize
) {
const end = Math.min(start + bucketSize, originalLength)
if (end - start <= 0) {
continue
}
const firstIdx = start
const lastIdx = end - 1
// find min and max within segment
let minIdx = start
let maxIdx = start
for (let j = start; j < end; j++) {
if (values[j] < values[minIdx]) {
minIdx = j
}
if (values[j] > values[maxIdx]) {
maxIdx = j
}
}
if (algorithm === 'min-max') {
if (minIdx === maxIdx) {
indices.push(minIdx)
} else if (minIdx < maxIdx) {
indices.push(minIdx, maxIdx)
} else {
indices.push(maxIdx, minIdx)
}
} else if (algorithm === 'm4') {
indices.push(firstIdx, minIdx, maxIdx, lastIdx)
}
}
// ensure unique and sorted
const uniqueIndices = Array.from(new Set(indices)).sort(
(a, b) => a - b
)
const sampledValues = uniqueIndices.map((i) => values[i])
result = {
indices: uniqueIndices,
values: sampledValues,
originalLength,
target,
}
}
downsampleSpan?.update({
output: result,
metadata: {
'operation.completed': true,
},
})
downsampleSpan?.end()
rootSpan?.update({
output: result,
metadata: {
'tool.output.success': true,
'tool.output.sampledCount': result.values.length,
},
})
rootSpan?.end()
await writer?.custom({
type: 'data-tool-progress',
data: {
status: 'done',
message: `Input: target=${input.target} - ✅ Downsampling complete`,
stage: 'downsample',
},
id: 'downsample',
})
return result
} catch (err) {
const error = err instanceof Error ? err : new Error(String(err))
log.error('downsample tool failed', { error: error.message })
// Record error in both spans
downsampleSpan?.error({ error, endSpan: true })
rootSpan?.error({ error, endSpan: true })
// Fallback: uniform sampling
const step = Math.max(1, Math.floor(originalLength / target))
const indices = Array.from(
{ length: Math.min(target, originalLength) },
(_, i) => Math.min(originalLength - 1, i * step)
)
const sampledValues = indices.map((i) => values[i])
const fallbackResult = {
indices,
values: sampledValues,
originalLength,
target,
}
await writer?.custom({
type: 'data-tool-progress',
data: {
status: 'done',
message: `Input: target=${input.target} - ⚠️ Downsampling failed, used fallback`,
stage: 'downsample',
},
id: 'downsample',
})
return fallbackResult
}
},
onOutput: ({ output, toolCallId, toolName, abortSignal }) => {
log.info('Downsample tool completed', {
toolCallId,
toolName,
outputData: { sampledCount: output?.values?.length ?? 0 },
abortSignal: abortSignal?.aborted,
hook: 'onOutput',
})
},
})
export type DownsampleUITool = typeof downsampleTool