@xsai-ext/telemetry 0.4.0-beta.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE.md +21 -0
- package/dist/index.d.ts +25 -0
- package/dist/index.js +569 -0
- package/package.json +48 -0
package/LICENSE.md
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2024 Moeru AI
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { AttributeValue } from '@opentelemetry/api';
|
|
2
|
+
import { GenerateTextOptions, GenerateTextResult, StreamTextOptions, StreamTextResult } from 'xsai';
|
|
3
|
+
export * from 'xsai';
|
|
4
|
+
|
|
5
|
+
type TelemetryMetadata = Record<string, AttributeValue>;
|
|
6
|
+
interface TelemetryOptions {
|
|
7
|
+
metadata?: TelemetryMetadata;
|
|
8
|
+
}
|
|
9
|
+
type WithTelemetry<T> = T & {
|
|
10
|
+
telemetry?: TelemetryOptions;
|
|
11
|
+
};
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* @experimental
|
|
15
|
+
* Generating Text with Telemetry.
|
|
16
|
+
*/
|
|
17
|
+
declare const generateText: (options: WithTelemetry<GenerateTextOptions>) => Promise<GenerateTextResult>;
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* @experimental
|
|
21
|
+
* Streaming Text with Telemetry.
|
|
22
|
+
*/
|
|
23
|
+
declare const streamText: (options: WithTelemetry<StreamTextOptions>) => StreamTextResult;
|
|
24
|
+
|
|
25
|
+
export { type TelemetryMetadata, type TelemetryOptions, type WithTelemetry, generateText, streamText };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,569 @@
|
|
|
1
|
+
import { determineStepType, clean, executeTool, trampoline, chat, responseJSON, objCamelToSnake } from 'xsai';
|
|
2
|
+
export * from 'xsai';
|
|
3
|
+
import { trace, SpanStatusCode } from '@opentelemetry/api';
|
|
4
|
+
|
|
5
|
+
const metadataAttributes = (metadata = {}) => Object.fromEntries(
|
|
6
|
+
Object.entries(metadata).map(([key, value]) => [`ai.telemetry.metadata.${key}`, value])
|
|
7
|
+
);
|
|
8
|
+
const idAttributes = () => {
|
|
9
|
+
const id = crypto.randomUUID();
|
|
10
|
+
return {
|
|
11
|
+
"ai.response.id": id,
|
|
12
|
+
"ai.response.timestamp": (/* @__PURE__ */ new Date()).toISOString(),
|
|
13
|
+
"gen_ai.response.id": id
|
|
14
|
+
};
|
|
15
|
+
};
|
|
16
|
+
const commonAttributes = (operationId, model) => ({
|
|
17
|
+
"ai.model.id": model,
|
|
18
|
+
// TODO: provider name
|
|
19
|
+
"ai.model.provider": "xsai",
|
|
20
|
+
"ai.operationId": operationId,
|
|
21
|
+
"ai.response.providerMetadata": "{}",
|
|
22
|
+
"operation.name": operationId
|
|
23
|
+
});
|
|
24
|
+
|
|
25
|
+
const extractGenerateTextStep = async (options, res) => {
|
|
26
|
+
const { choices, usage } = res;
|
|
27
|
+
if (!choices?.length)
|
|
28
|
+
throw new Error(`No choices returned, response body: ${JSON.stringify(res)}`);
|
|
29
|
+
const messages = [];
|
|
30
|
+
const toolCalls = [];
|
|
31
|
+
const { finish_reason: finishReason, message } = choices[0];
|
|
32
|
+
const msgToolCalls = message?.tool_calls ?? [];
|
|
33
|
+
const stepType = determineStepType({
|
|
34
|
+
finishReason,
|
|
35
|
+
maxSteps: options.maxSteps ?? 1,
|
|
36
|
+
stepsLength: options.steps?.length ?? 0,
|
|
37
|
+
toolCallsLength: msgToolCalls.length
|
|
38
|
+
});
|
|
39
|
+
messages.push(clean({
|
|
40
|
+
...message,
|
|
41
|
+
reasoning_content: void 0
|
|
42
|
+
}));
|
|
43
|
+
if (finishReason !== "stop" || stepType !== "done") {
|
|
44
|
+
for (const toolCall of msgToolCalls) {
|
|
45
|
+
toolCalls.push({
|
|
46
|
+
args: toolCall.function.arguments,
|
|
47
|
+
toolCallId: toolCall.id,
|
|
48
|
+
toolCallType: toolCall.type,
|
|
49
|
+
toolName: toolCall.function.name
|
|
50
|
+
});
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
return [
|
|
54
|
+
{
|
|
55
|
+
finishReason,
|
|
56
|
+
stepType,
|
|
57
|
+
text: message.content,
|
|
58
|
+
toolCalls,
|
|
59
|
+
usage
|
|
60
|
+
},
|
|
61
|
+
{
|
|
62
|
+
messages,
|
|
63
|
+
msgToolCalls,
|
|
64
|
+
reasoningText: message.reasoning_content
|
|
65
|
+
}
|
|
66
|
+
];
|
|
67
|
+
};
|
|
68
|
+
const extractGenerateTextStepPost = async (options, msgToolCalls) => {
|
|
69
|
+
const inputMessages = structuredClone(options.messages);
|
|
70
|
+
const outputMessages = [];
|
|
71
|
+
const toolResults = [];
|
|
72
|
+
for (const toolCall of msgToolCalls) {
|
|
73
|
+
const { completionToolResult, message } = await executeTool({
|
|
74
|
+
abortSignal: options.abortSignal,
|
|
75
|
+
messages: inputMessages,
|
|
76
|
+
toolCall,
|
|
77
|
+
tools: options.tools
|
|
78
|
+
});
|
|
79
|
+
toolResults.push(completionToolResult);
|
|
80
|
+
outputMessages.push(message);
|
|
81
|
+
}
|
|
82
|
+
return [
|
|
83
|
+
toolResults,
|
|
84
|
+
outputMessages
|
|
85
|
+
];
|
|
86
|
+
};
|
|
87
|
+
|
|
88
|
+
const getTracer = () => trace.getTracer("@xsai-ext/telemetry");
|
|
89
|
+
|
|
90
|
+
const recordErrorOnSpan = (span, error) => {
|
|
91
|
+
if (error instanceof Error) {
|
|
92
|
+
span.recordException({
|
|
93
|
+
message: error.message,
|
|
94
|
+
name: error.name,
|
|
95
|
+
stack: error.stack
|
|
96
|
+
});
|
|
97
|
+
span.setStatus({
|
|
98
|
+
code: SpanStatusCode.ERROR,
|
|
99
|
+
message: error.message
|
|
100
|
+
});
|
|
101
|
+
} else {
|
|
102
|
+
span.setStatus({ code: SpanStatusCode.ERROR });
|
|
103
|
+
}
|
|
104
|
+
};
|
|
105
|
+
const recordSpan = async ({
|
|
106
|
+
attributes,
|
|
107
|
+
endWhenDone = true,
|
|
108
|
+
name,
|
|
109
|
+
tracer
|
|
110
|
+
}, fn) => tracer.startActiveSpan(name, { attributes }, async (span) => {
|
|
111
|
+
try {
|
|
112
|
+
const result = await fn(span);
|
|
113
|
+
if (endWhenDone)
|
|
114
|
+
span.end();
|
|
115
|
+
return result;
|
|
116
|
+
} catch (error) {
|
|
117
|
+
try {
|
|
118
|
+
recordErrorOnSpan(span, error);
|
|
119
|
+
} finally {
|
|
120
|
+
span.end();
|
|
121
|
+
}
|
|
122
|
+
throw error;
|
|
123
|
+
}
|
|
124
|
+
});
|
|
125
|
+
const recordSpanSync = ({
|
|
126
|
+
attributes,
|
|
127
|
+
endWhenDone = true,
|
|
128
|
+
name,
|
|
129
|
+
tracer
|
|
130
|
+
}, fn) => tracer.startActiveSpan(name, { attributes }, (span) => {
|
|
131
|
+
try {
|
|
132
|
+
const result = fn(span);
|
|
133
|
+
if (endWhenDone)
|
|
134
|
+
span.end();
|
|
135
|
+
return result;
|
|
136
|
+
} catch (error) {
|
|
137
|
+
try {
|
|
138
|
+
recordErrorOnSpan(span, error);
|
|
139
|
+
} finally {
|
|
140
|
+
span.end();
|
|
141
|
+
}
|
|
142
|
+
throw error;
|
|
143
|
+
}
|
|
144
|
+
});
|
|
145
|
+
|
|
146
|
+
const stringifyTool = ({ function: func, type }) => JSON.stringify({ description: func.description, inputSchema: func.parameters, name: func.name, type });
|
|
147
|
+
|
|
148
|
+
const wrapTool = (tool, tracer) => ({
|
|
149
|
+
execute: async (input, options) => recordSpan({
|
|
150
|
+
attributes: {
|
|
151
|
+
"ai.operationId": "ai.toolCall",
|
|
152
|
+
"ai.toolCall.args": JSON.stringify(input),
|
|
153
|
+
"ai.toolCall.id": options.toolCallId,
|
|
154
|
+
"ai.toolCall.name": tool.function.name,
|
|
155
|
+
"operation.name": "ai.toolCall"
|
|
156
|
+
},
|
|
157
|
+
name: "ai.toolCall",
|
|
158
|
+
tracer
|
|
159
|
+
}, async (span) => {
|
|
160
|
+
const result = await tool.execute(input, options);
|
|
161
|
+
span.setAttribute("ai.toolCall.result", JSON.stringify(result));
|
|
162
|
+
return result;
|
|
163
|
+
}),
|
|
164
|
+
function: tool.function,
|
|
165
|
+
type: tool.type
|
|
166
|
+
});
|
|
167
|
+
|
|
168
|
+
const generateText = async (options) => {
|
|
169
|
+
const tracer = getTracer();
|
|
170
|
+
const rawGenerateText = async (options2) => {
|
|
171
|
+
const messages = structuredClone(options2.messages);
|
|
172
|
+
const steps = options2.steps ? structuredClone(options2.steps) : [];
|
|
173
|
+
const [stepWithoutToolCalls, { messages: msgs1, msgToolCalls, reasoningText }] = await recordSpan({
|
|
174
|
+
attributes: {
|
|
175
|
+
...idAttributes(),
|
|
176
|
+
...commonAttributes("ai.generateText.doGenerate", options2.model),
|
|
177
|
+
...metadataAttributes(options2.telemetry?.metadata),
|
|
178
|
+
...options2.tools != null && options2.tools.length > 0 ? {
|
|
179
|
+
"ai.prompt.toolChoice": JSON.stringify(options2.toolChoice ?? { type: "auto" }),
|
|
180
|
+
"ai.prompt.tools": options2.tools.map(stringifyTool)
|
|
181
|
+
} : {},
|
|
182
|
+
"ai.prompt.messages": JSON.stringify(messages),
|
|
183
|
+
"ai.response.model": options2.model,
|
|
184
|
+
"gen_ai.request.model": options2.model,
|
|
185
|
+
"gen_ai.response.id": crypto.randomUUID(),
|
|
186
|
+
"gen_ai.response.model": options2.model,
|
|
187
|
+
"gen_ai.system": "xsai"
|
|
188
|
+
},
|
|
189
|
+
name: "ai.generateText.doGenerate",
|
|
190
|
+
tracer
|
|
191
|
+
}, async (span) => {
|
|
192
|
+
const res = await chat({
|
|
193
|
+
...options2,
|
|
194
|
+
maxSteps: void 0,
|
|
195
|
+
steps: void 0,
|
|
196
|
+
stream: false,
|
|
197
|
+
telemetry: void 0
|
|
198
|
+
}).then(responseJSON);
|
|
199
|
+
const [step2, { messages: msgs, msgToolCalls: msgToolCalls2, reasoningText: reasoningText2 }] = await extractGenerateTextStep({
|
|
200
|
+
...options2,
|
|
201
|
+
messages,
|
|
202
|
+
steps
|
|
203
|
+
}, res);
|
|
204
|
+
span.setAttributes({
|
|
205
|
+
...step2.text != null && step2.toolCalls.length === 0 ? { "ai.response.text": step2.text } : {},
|
|
206
|
+
...step2.toolCalls.length > 0 ? { "ai.response.toolCalls": JSON.stringify(step2.toolCalls) } : {},
|
|
207
|
+
"ai.response.finishReason": step2.finishReason,
|
|
208
|
+
"ai.usage.completionTokens": step2.usage.completion_tokens,
|
|
209
|
+
"ai.usage.promptTokens": step2.usage.prompt_tokens,
|
|
210
|
+
"gen_ai.response.finish_reasons": [step2.finishReason],
|
|
211
|
+
"gen_ai.usage.input_tokens": step2.usage.prompt_tokens,
|
|
212
|
+
"gen_ai.usage.output_tokens": step2.usage.completion_tokens
|
|
213
|
+
});
|
|
214
|
+
return [step2, { messages: msgs, msgToolCalls: msgToolCalls2, reasoningText: reasoningText2 }];
|
|
215
|
+
});
|
|
216
|
+
const [toolResults, msgs2] = await extractGenerateTextStepPost({
|
|
217
|
+
...options2,
|
|
218
|
+
messages}, msgToolCalls);
|
|
219
|
+
const step = { ...stepWithoutToolCalls, toolResults };
|
|
220
|
+
steps.push(step);
|
|
221
|
+
messages.push(...msgs1, ...msgs2);
|
|
222
|
+
if (options2.onStepFinish)
|
|
223
|
+
await options2.onStepFinish(step);
|
|
224
|
+
if (step.finishReason === "stop" || step.stepType === "done") {
|
|
225
|
+
return {
|
|
226
|
+
finishReason: step.finishReason,
|
|
227
|
+
messages,
|
|
228
|
+
reasoningText,
|
|
229
|
+
steps,
|
|
230
|
+
text: step.text,
|
|
231
|
+
toolCalls: step.toolCalls,
|
|
232
|
+
toolResults: step.toolResults,
|
|
233
|
+
usage: step.usage
|
|
234
|
+
};
|
|
235
|
+
} else {
|
|
236
|
+
return async () => rawGenerateText({
|
|
237
|
+
...options2,
|
|
238
|
+
messages,
|
|
239
|
+
steps
|
|
240
|
+
});
|
|
241
|
+
}
|
|
242
|
+
};
|
|
243
|
+
return recordSpan({
|
|
244
|
+
attributes: {
|
|
245
|
+
...commonAttributes("ai.generateText", options.model),
|
|
246
|
+
...metadataAttributes(options.telemetry?.metadata),
|
|
247
|
+
"ai.prompt": JSON.stringify({ messages: options.messages })
|
|
248
|
+
},
|
|
249
|
+
name: "ai.generateText",
|
|
250
|
+
tracer
|
|
251
|
+
}, async (span) => {
|
|
252
|
+
const result = await trampoline(async () => rawGenerateText({
|
|
253
|
+
...options,
|
|
254
|
+
tools: options.tools?.map((tool) => wrapTool(tool, tracer))
|
|
255
|
+
}));
|
|
256
|
+
span.setAttributes({
|
|
257
|
+
...result.toolCalls.length > 0 ? { "ai.response.toolCalls": JSON.stringify(result.toolCalls) } : {},
|
|
258
|
+
...result.text != null ? { "ai.response.text": result.text } : {},
|
|
259
|
+
"ai.response.finishReason": result.finishReason,
|
|
260
|
+
"ai.usage.completionTokens": result.usage.completion_tokens,
|
|
261
|
+
"ai.usage.promptTokens": result.usage.prompt_tokens
|
|
262
|
+
});
|
|
263
|
+
return result;
|
|
264
|
+
});
|
|
265
|
+
};
|
|
266
|
+
|
|
267
|
+
const now = () => globalThis?.performance?.now() ?? Date.now();
|
|
268
|
+
|
|
269
|
+
const parseChunk = (text) => {
|
|
270
|
+
if (!text || !text.startsWith("data:"))
|
|
271
|
+
return [void 0, false];
|
|
272
|
+
const content = text.slice("data:".length);
|
|
273
|
+
const data = content.startsWith(" ") ? content.slice(1) : content;
|
|
274
|
+
if (data === "[DONE]") {
|
|
275
|
+
return [void 0, true];
|
|
276
|
+
}
|
|
277
|
+
if (data.startsWith("{") && data.includes('"error":')) {
|
|
278
|
+
throw new Error(`Error from server: ${data}`);
|
|
279
|
+
}
|
|
280
|
+
const chunk = JSON.parse(data);
|
|
281
|
+
return [chunk, false];
|
|
282
|
+
};
|
|
283
|
+
const transformChunk = () => {
|
|
284
|
+
const decoder = new TextDecoder();
|
|
285
|
+
let buffer = "";
|
|
286
|
+
return new TransformStream({
|
|
287
|
+
transform: async (chunk, controller) => {
|
|
288
|
+
const text = decoder.decode(chunk, { stream: true });
|
|
289
|
+
buffer += text;
|
|
290
|
+
const lines = buffer.split("\n");
|
|
291
|
+
buffer = lines.pop() ?? "";
|
|
292
|
+
for (const line of lines) {
|
|
293
|
+
try {
|
|
294
|
+
const [chunk2, isEnd] = parseChunk(line);
|
|
295
|
+
if (isEnd)
|
|
296
|
+
break;
|
|
297
|
+
if (chunk2) {
|
|
298
|
+
controller.enqueue(chunk2);
|
|
299
|
+
}
|
|
300
|
+
} catch (error) {
|
|
301
|
+
controller.error(error);
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
});
|
|
306
|
+
};
|
|
307
|
+
class DelayedPromise {
|
|
308
|
+
get promise() {
|
|
309
|
+
if (this._promise == null) {
|
|
310
|
+
this._promise = new Promise((resolve, reject) => {
|
|
311
|
+
if (this.status.type === "resolved") {
|
|
312
|
+
resolve(this.status.value);
|
|
313
|
+
} else if (this.status.type === "rejected") {
|
|
314
|
+
reject(this.status.error);
|
|
315
|
+
}
|
|
316
|
+
this._resolve = resolve;
|
|
317
|
+
this._reject = reject;
|
|
318
|
+
});
|
|
319
|
+
}
|
|
320
|
+
return this._promise;
|
|
321
|
+
}
|
|
322
|
+
_promise;
|
|
323
|
+
_reject;
|
|
324
|
+
_resolve;
|
|
325
|
+
status = { type: "pending" };
|
|
326
|
+
reject(error) {
|
|
327
|
+
this.status = { error, type: "rejected" };
|
|
328
|
+
if (this._promise) {
|
|
329
|
+
this._reject?.(error);
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
resolve(value) {
|
|
333
|
+
this.status = { type: "resolved", value };
|
|
334
|
+
if (this._promise) {
|
|
335
|
+
this._resolve?.(value);
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
const streamText = (options) => {
|
|
341
|
+
const tracer = getTracer();
|
|
342
|
+
const steps = [];
|
|
343
|
+
const messages = structuredClone(options.messages);
|
|
344
|
+
const maxSteps = options.maxSteps ?? 1;
|
|
345
|
+
let usage;
|
|
346
|
+
let totalUsage;
|
|
347
|
+
const resultSteps = new DelayedPromise();
|
|
348
|
+
const resultMessages = new DelayedPromise();
|
|
349
|
+
const resultUsage = new DelayedPromise();
|
|
350
|
+
const resultTotalUsage = new DelayedPromise();
|
|
351
|
+
let eventCtrl;
|
|
352
|
+
let textCtrl;
|
|
353
|
+
const eventStream = new ReadableStream({ start: (controller) => eventCtrl = controller });
|
|
354
|
+
const textStream = new ReadableStream({ start: (controller) => textCtrl = controller });
|
|
355
|
+
const pushEvent = (stepEvent) => {
|
|
356
|
+
eventCtrl?.enqueue(stepEvent);
|
|
357
|
+
void options.onEvent?.(stepEvent);
|
|
358
|
+
};
|
|
359
|
+
const pushStep = (step) => {
|
|
360
|
+
steps.push(step);
|
|
361
|
+
void options.onStepFinish?.(step);
|
|
362
|
+
};
|
|
363
|
+
const tools = options.tools != null && options.tools.length > 0 ? options.tools.map((tool) => wrapTool(tool, tracer)) : void 0;
|
|
364
|
+
const doStream = async () => recordSpan({
|
|
365
|
+
attributes: {
|
|
366
|
+
...idAttributes(),
|
|
367
|
+
...commonAttributes("ai.streamText.doStream", options.model),
|
|
368
|
+
...metadataAttributes(options.telemetry?.metadata),
|
|
369
|
+
...tools != null && tools.length > 0 && {
|
|
370
|
+
"ai.prompt.toolChoice": JSON.stringify(options.toolChoice ?? { type: "auto" }),
|
|
371
|
+
"ai.prompt.tools": tools.map(stringifyTool)
|
|
372
|
+
},
|
|
373
|
+
"ai.prompt.messages": JSON.stringify(options.messages),
|
|
374
|
+
"ai.response.model": options.model,
|
|
375
|
+
"gen_ai.request.model": options.model,
|
|
376
|
+
"gen_ai.response.id": crypto.randomUUID(),
|
|
377
|
+
"gen_ai.response.model": options.model,
|
|
378
|
+
"gen_ai.system": "xsai"
|
|
379
|
+
},
|
|
380
|
+
name: "ai.streamText.doStream",
|
|
381
|
+
tracer
|
|
382
|
+
}, async (span) => {
|
|
383
|
+
const startMs = now();
|
|
384
|
+
const { body: stream } = await chat({
|
|
385
|
+
...options,
|
|
386
|
+
maxSteps: void 0,
|
|
387
|
+
messages,
|
|
388
|
+
stream: true,
|
|
389
|
+
streamOptions: options.streamOptions != null ? objCamelToSnake(options.streamOptions) : void 0,
|
|
390
|
+
tools
|
|
391
|
+
});
|
|
392
|
+
const pushUsage = (u) => {
|
|
393
|
+
usage = u;
|
|
394
|
+
totalUsage = totalUsage ? {
|
|
395
|
+
completion_tokens: totalUsage.completion_tokens + u.completion_tokens,
|
|
396
|
+
prompt_tokens: totalUsage.prompt_tokens + u.prompt_tokens,
|
|
397
|
+
total_tokens: totalUsage.total_tokens + u.total_tokens
|
|
398
|
+
} : { ...u };
|
|
399
|
+
};
|
|
400
|
+
let text = "";
|
|
401
|
+
const pushText = (content) => {
|
|
402
|
+
textCtrl?.enqueue(content);
|
|
403
|
+
text += content;
|
|
404
|
+
};
|
|
405
|
+
const tool_calls = [];
|
|
406
|
+
const toolCalls = [];
|
|
407
|
+
const toolResults = [];
|
|
408
|
+
let finishReason = "other";
|
|
409
|
+
let firstChunk = true;
|
|
410
|
+
await stream.pipeThrough(transformChunk()).pipeTo(new WritableStream({
|
|
411
|
+
abort: (reason) => {
|
|
412
|
+
eventCtrl?.error(reason);
|
|
413
|
+
textCtrl?.error(reason);
|
|
414
|
+
},
|
|
415
|
+
close: () => {
|
|
416
|
+
},
|
|
417
|
+
// eslint-disable-next-line sonarjs/cognitive-complexity
|
|
418
|
+
write: (chunk) => {
|
|
419
|
+
if (firstChunk) {
|
|
420
|
+
const msToFirstChunk = now() - startMs;
|
|
421
|
+
span.addEvent("ai.stream.firstChunk", {
|
|
422
|
+
"ai.response.msToFirstChunk": msToFirstChunk
|
|
423
|
+
});
|
|
424
|
+
span.setAttributes({
|
|
425
|
+
"ai.response.msToFirstChunk": msToFirstChunk
|
|
426
|
+
});
|
|
427
|
+
firstChunk = false;
|
|
428
|
+
}
|
|
429
|
+
if (chunk.usage)
|
|
430
|
+
pushUsage(chunk.usage);
|
|
431
|
+
if (chunk.choices == null || chunk.choices.length === 0)
|
|
432
|
+
return;
|
|
433
|
+
const choice = chunk.choices[0];
|
|
434
|
+
if (choice.delta.reasoning_content != null)
|
|
435
|
+
pushEvent({ text: choice.delta.reasoning_content, type: "reasoning-delta" });
|
|
436
|
+
if (choice.finish_reason != null)
|
|
437
|
+
finishReason = choice.finish_reason;
|
|
438
|
+
if (choice.delta.tool_calls?.length === 0 || choice.delta.tool_calls == null) {
|
|
439
|
+
if (choice.delta.content != null) {
|
|
440
|
+
pushEvent({ text: choice.delta.content, type: "text-delta" });
|
|
441
|
+
pushText(choice.delta.content);
|
|
442
|
+
} else if (choice.delta.refusal != null) {
|
|
443
|
+
pushEvent({ error: choice.delta.refusal, type: "error" });
|
|
444
|
+
} else if (choice.finish_reason != null) {
|
|
445
|
+
pushEvent({ finishReason: choice.finish_reason, type: "finish", usage });
|
|
446
|
+
}
|
|
447
|
+
} else {
|
|
448
|
+
for (const toolCall of choice.delta.tool_calls) {
|
|
449
|
+
const { index } = toolCall;
|
|
450
|
+
if (!tool_calls.at(index)) {
|
|
451
|
+
tool_calls[index] = toolCall;
|
|
452
|
+
pushEvent({ toolCallId: toolCall.id, toolName: toolCall.function.name, type: "tool-call-streaming-start" });
|
|
453
|
+
} else {
|
|
454
|
+
tool_calls[index].function.arguments += toolCall.function.arguments;
|
|
455
|
+
pushEvent({ argsTextDelta: toolCall.function.arguments, toolCallId: toolCall.id, toolName: toolCall.function.name, type: "tool-call-delta" });
|
|
456
|
+
}
|
|
457
|
+
}
|
|
458
|
+
}
|
|
459
|
+
}
|
|
460
|
+
}));
|
|
461
|
+
messages.push({ content: text, role: "assistant", tool_calls });
|
|
462
|
+
if (tool_calls.length !== 0) {
|
|
463
|
+
for (const toolCall of tool_calls) {
|
|
464
|
+
const { completionToolCall, completionToolResult, message } = await executeTool({
|
|
465
|
+
abortSignal: options.abortSignal,
|
|
466
|
+
messages,
|
|
467
|
+
toolCall,
|
|
468
|
+
tools
|
|
469
|
+
});
|
|
470
|
+
toolCalls.push(completionToolCall);
|
|
471
|
+
toolResults.push(completionToolResult);
|
|
472
|
+
messages.push(message);
|
|
473
|
+
pushEvent({ ...completionToolCall, type: "tool-call" });
|
|
474
|
+
pushEvent({ ...completionToolResult, type: "tool-result" });
|
|
475
|
+
}
|
|
476
|
+
} else {
|
|
477
|
+
pushEvent({
|
|
478
|
+
finishReason,
|
|
479
|
+
type: "finish",
|
|
480
|
+
usage
|
|
481
|
+
});
|
|
482
|
+
}
|
|
483
|
+
const step = {
|
|
484
|
+
finishReason,
|
|
485
|
+
stepType: determineStepType({ finishReason, maxSteps, stepsLength: steps.length, toolCallsLength: toolCalls.length }),
|
|
486
|
+
text,
|
|
487
|
+
toolCalls,
|
|
488
|
+
toolResults,
|
|
489
|
+
usage
|
|
490
|
+
};
|
|
491
|
+
pushStep(step);
|
|
492
|
+
const msToFinish = now() - startMs;
|
|
493
|
+
span.addEvent("ai.stream.finish");
|
|
494
|
+
span.setAttributes({
|
|
495
|
+
"ai.response.msToFinish": msToFinish,
|
|
496
|
+
...step.toolCalls.length > 0 && { "ai.response.toolCalls": JSON.stringify(step.toolCalls) },
|
|
497
|
+
"ai.response.finishReason": step.finishReason,
|
|
498
|
+
"ai.response.text": step.text != null ? step.text : "",
|
|
499
|
+
"gen_ai.response.finish_reasons": [step.finishReason],
|
|
500
|
+
...step.usage && {
|
|
501
|
+
"ai.response.avgOutputTokensPerSecond": 1e3 * (step.usage.completion_tokens ?? 0) / msToFinish,
|
|
502
|
+
"ai.usage.inputTokens": step.usage.prompt_tokens,
|
|
503
|
+
"ai.usage.outputTokens": step.usage.completion_tokens,
|
|
504
|
+
"ai.usage.totalTokens": step.usage.total_tokens,
|
|
505
|
+
"gen_ai.usage.input_tokens": step.usage.prompt_tokens,
|
|
506
|
+
"gen_ai.usage.output_tokens": step.usage.completion_tokens
|
|
507
|
+
}
|
|
508
|
+
});
|
|
509
|
+
if (toolCalls.length !== 0 && steps.length < maxSteps)
|
|
510
|
+
return async () => doStream();
|
|
511
|
+
});
|
|
512
|
+
return recordSpanSync({
|
|
513
|
+
attributes: {
|
|
514
|
+
...commonAttributes("ai.streamText", options.model),
|
|
515
|
+
...metadataAttributes(options.telemetry?.metadata),
|
|
516
|
+
"ai.prompt": JSON.stringify({ messages: options.messages })
|
|
517
|
+
},
|
|
518
|
+
endWhenDone: false,
|
|
519
|
+
name: "ai.streamText",
|
|
520
|
+
tracer
|
|
521
|
+
}, (rootSpan) => {
|
|
522
|
+
void (async () => {
|
|
523
|
+
try {
|
|
524
|
+
await trampoline(async () => doStream());
|
|
525
|
+
eventCtrl?.close();
|
|
526
|
+
textCtrl?.close();
|
|
527
|
+
} catch (err) {
|
|
528
|
+
eventCtrl?.error(err);
|
|
529
|
+
textCtrl?.error(err);
|
|
530
|
+
resultSteps.reject(err);
|
|
531
|
+
resultMessages.reject(err);
|
|
532
|
+
resultUsage.reject(err);
|
|
533
|
+
resultTotalUsage.reject(err);
|
|
534
|
+
} finally {
|
|
535
|
+
resultSteps.resolve(steps);
|
|
536
|
+
resultMessages.resolve(messages);
|
|
537
|
+
resultUsage.resolve(usage);
|
|
538
|
+
resultTotalUsage.resolve(totalUsage);
|
|
539
|
+
const finishStep = steps.at(-1);
|
|
540
|
+
if (finishStep) {
|
|
541
|
+
rootSpan.setAttributes({
|
|
542
|
+
...finishStep.toolCalls.length > 0 && { "ai.response.toolCalls": JSON.stringify(finishStep.toolCalls) },
|
|
543
|
+
"ai.response.finishReason": finishStep.finishReason,
|
|
544
|
+
"ai.response.text": finishStep.text != null ? finishStep.text : ""
|
|
545
|
+
});
|
|
546
|
+
}
|
|
547
|
+
if (totalUsage) {
|
|
548
|
+
rootSpan.setAttributes({
|
|
549
|
+
"ai.usage.inputTokens": totalUsage.prompt_tokens,
|
|
550
|
+
"ai.usage.outputTokens": totalUsage.completion_tokens,
|
|
551
|
+
"ai.usage.totalTokens": totalUsage.total_tokens
|
|
552
|
+
});
|
|
553
|
+
}
|
|
554
|
+
void options.onFinish?.(finishStep);
|
|
555
|
+
rootSpan.end();
|
|
556
|
+
}
|
|
557
|
+
})();
|
|
558
|
+
return {
|
|
559
|
+
fullStream: eventStream,
|
|
560
|
+
messages: resultMessages.promise,
|
|
561
|
+
steps: resultSteps.promise,
|
|
562
|
+
textStream,
|
|
563
|
+
totalUsage: resultTotalUsage.promise,
|
|
564
|
+
usage: resultUsage.promise
|
|
565
|
+
};
|
|
566
|
+
});
|
|
567
|
+
};
|
|
568
|
+
|
|
569
|
+
export { generateText, streamText };
|
package/package.json
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@xsai-ext/telemetry",
|
|
3
|
+
"type": "module",
|
|
4
|
+
"version": "0.4.0-beta.3",
|
|
5
|
+
"description": "extra-small AI SDK.",
|
|
6
|
+
"author": "Moeru AI",
|
|
7
|
+
"license": "MIT",
|
|
8
|
+
"homepage": "https://xsai.js.org",
|
|
9
|
+
"repository": {
|
|
10
|
+
"type": "git",
|
|
11
|
+
"url": "git+https://github.com/moeru-ai/xsai.git",
|
|
12
|
+
"directory": "packages-ext/telemetry"
|
|
13
|
+
},
|
|
14
|
+
"bugs": "https://github.com/moeru-ai/xsai/issues",
|
|
15
|
+
"keywords": [
|
|
16
|
+
"xsai",
|
|
17
|
+
"openai",
|
|
18
|
+
"ai"
|
|
19
|
+
],
|
|
20
|
+
"sideEffects": false,
|
|
21
|
+
"exports": {
|
|
22
|
+
".": {
|
|
23
|
+
"types": "./dist/index.d.ts",
|
|
24
|
+
"default": "./dist/index.js"
|
|
25
|
+
},
|
|
26
|
+
"./package.json": "./package.json"
|
|
27
|
+
},
|
|
28
|
+
"files": [
|
|
29
|
+
"dist"
|
|
30
|
+
],
|
|
31
|
+
"dependencies": {
|
|
32
|
+
"@opentelemetry/api": "^1.9.0",
|
|
33
|
+
"xsai": "~0.4.0-beta.3"
|
|
34
|
+
},
|
|
35
|
+
"devDependencies": {
|
|
36
|
+
"@opentelemetry/sdk-trace-base": "^2.0.1",
|
|
37
|
+
"@opentelemetry/sdk-trace-node": "^2.0.1",
|
|
38
|
+
"ai": "^5.0.28",
|
|
39
|
+
"ollama-ai-provider-v2": "^1.2.1",
|
|
40
|
+
"zod": "^4.1.5"
|
|
41
|
+
},
|
|
42
|
+
"scripts": {
|
|
43
|
+
"build": "pkgroll",
|
|
44
|
+
"test": "vitest run --update"
|
|
45
|
+
},
|
|
46
|
+
"main": "./dist/index.js",
|
|
47
|
+
"types": "./dist/index.d.ts"
|
|
48
|
+
}
|