@core-ai/opentelemetry 0.10.0

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 ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Omnifact (https://omnifact.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/README.md ADDED
@@ -0,0 +1,30 @@
1
+ # @core-ai/opentelemetry
2
+
3
+ [![npm](https://img.shields.io/npm/v/@core-ai/opentelemetry.svg)](https://www.npmjs.com/package/@core-ai/opentelemetry)
4
+
5
+ OpenTelemetry middleware for `@core-ai/core-ai`.
6
+
7
+ ## Installation
8
+
9
+ ```bash
10
+ npm install @core-ai/opentelemetry @opentelemetry/api
11
+ ```
12
+
13
+ `@opentelemetry/api` is a peer dependency and must be installed alongside this package.
14
+
15
+ ## Usage
16
+
17
+ ```ts
18
+ import { generate } from '@core-ai/core-ai';
19
+ import { createOpenAI } from '@core-ai/openai';
20
+ import { createOtelMiddleware } from '@core-ai/opentelemetry';
21
+
22
+ const openai = createOpenAI({ apiKey: process.env.OPENAI_API_KEY });
23
+ const model = openai.chatModel('gpt-5-mini');
24
+
25
+ const result = await generate({
26
+ model,
27
+ messages: [{ role: 'user', content: 'Hello!' }],
28
+ middleware: [createOtelMiddleware()],
29
+ });
30
+ ```
@@ -0,0 +1,11 @@
1
+ import { EmbeddingModelMiddleware, ImageModelMiddleware, ChatModelMiddleware } from '@core-ai/core-ai';
2
+
3
+ type OtelMiddlewareOptions = {
4
+ recordContent?: boolean;
5
+ tracerName?: string;
6
+ };
7
+ declare function createOtelMiddleware(options?: OtelMiddlewareOptions): ChatModelMiddleware;
8
+ declare function createOtelEmbeddingMiddleware(options?: OtelMiddlewareOptions): EmbeddingModelMiddleware;
9
+ declare function createOtelImageMiddleware(options?: OtelMiddlewareOptions): ImageModelMiddleware;
10
+
11
+ export { type OtelMiddlewareOptions, createOtelEmbeddingMiddleware, createOtelImageMiddleware, createOtelMiddleware };
package/dist/index.js ADDED
@@ -0,0 +1,536 @@
1
+ // src/index.ts
2
+ import { SpanKind, SpanStatusCode, trace } from "@opentelemetry/api";
3
+
4
+ // src/attributes.ts
5
+ import { zodSchemaToJsonSchema } from "@core-ai/core-ai";
6
+ function safeJsonStringify(value) {
7
+ try {
8
+ return JSON.stringify(value);
9
+ } catch {
10
+ return void 0;
11
+ }
12
+ }
13
+ function setSpanAttribute(span, key, value) {
14
+ if (value !== void 0) {
15
+ span.setAttribute(key, value);
16
+ }
17
+ }
18
+ function isPrimitiveArray(value) {
19
+ if (!Array.isArray(value)) {
20
+ return false;
21
+ }
22
+ if (value.length === 0) {
23
+ return true;
24
+ }
25
+ const first = value[0];
26
+ const primitiveType = typeof first;
27
+ if (primitiveType !== "string" && primitiveType !== "number" && primitiveType !== "boolean") {
28
+ return false;
29
+ }
30
+ return value.every((item) => typeof item === primitiveType);
31
+ }
32
+ function toSpanAttributeValue(value) {
33
+ if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
34
+ return value;
35
+ }
36
+ if (isPrimitiveArray(value)) {
37
+ return value;
38
+ }
39
+ return safeJsonStringify(value);
40
+ }
41
+ function setMetadataAttributes(span, metadata) {
42
+ if (!metadata) {
43
+ return;
44
+ }
45
+ const { functionId, ...restMetadata } = metadata;
46
+ if (typeof functionId === "string") {
47
+ span.setAttribute("core_ai.function_id", functionId);
48
+ }
49
+ for (const [key, value] of Object.entries(restMetadata)) {
50
+ setSpanAttribute(
51
+ span,
52
+ `core_ai.metadata.${key}`,
53
+ toSpanAttributeValue(value)
54
+ );
55
+ }
56
+ }
57
+ function serializeUserContentParts(content) {
58
+ if (typeof content === "string") {
59
+ return [{ type: "text", content }];
60
+ }
61
+ return content.map((part) => {
62
+ if (part.type === "text") {
63
+ return {
64
+ type: "text",
65
+ content: part.text
66
+ };
67
+ }
68
+ if (part.type === "image") {
69
+ return {
70
+ type: "image",
71
+ source: part.source
72
+ };
73
+ }
74
+ return {
75
+ type: "file",
76
+ data: part.data,
77
+ mime_type: part.mimeType,
78
+ ...part.filename ? { filename: part.filename } : {}
79
+ };
80
+ });
81
+ }
82
+ function serializeAssistantContentParts(parts) {
83
+ return parts.map((part) => {
84
+ if (part.type === "text") {
85
+ return {
86
+ type: "text",
87
+ content: part.text
88
+ };
89
+ }
90
+ if (part.type === "reasoning") {
91
+ return {
92
+ type: "reasoning",
93
+ content: part.text,
94
+ ...part.providerMetadata ? {
95
+ provider_metadata: part.providerMetadata
96
+ } : {}
97
+ };
98
+ }
99
+ return {
100
+ type: "tool_call",
101
+ id: part.toolCall.id,
102
+ name: part.toolCall.name,
103
+ arguments: part.toolCall.arguments
104
+ };
105
+ });
106
+ }
107
+ function setChatInputAttributes(span, messages, tools) {
108
+ const systemInstructions = [];
109
+ const inputMessages = [];
110
+ for (const message of messages) {
111
+ if (message.role === "system") {
112
+ systemInstructions.push({
113
+ type: "text",
114
+ content: message.content
115
+ });
116
+ continue;
117
+ }
118
+ if (message.role === "user") {
119
+ inputMessages.push({
120
+ role: "user",
121
+ parts: serializeUserContentParts(message.content)
122
+ });
123
+ continue;
124
+ }
125
+ if (message.role === "assistant") {
126
+ inputMessages.push({
127
+ role: "assistant",
128
+ parts: serializeAssistantContentParts(message.parts)
129
+ });
130
+ continue;
131
+ }
132
+ inputMessages.push({
133
+ role: "tool",
134
+ parts: [
135
+ {
136
+ type: "tool_call_response",
137
+ id: message.toolCallId,
138
+ result: message.content,
139
+ ...message.isError ? { is_error: true } : {}
140
+ }
141
+ ]
142
+ });
143
+ }
144
+ if (systemInstructions.length > 0) {
145
+ setSpanAttribute(
146
+ span,
147
+ "gen_ai.system_instructions",
148
+ safeJsonStringify(systemInstructions)
149
+ );
150
+ }
151
+ setSpanAttribute(
152
+ span,
153
+ "gen_ai.input.messages",
154
+ safeJsonStringify(inputMessages)
155
+ );
156
+ setSpanAttribute(span, "input.value", safeJsonStringify(messages));
157
+ if (tools && Object.keys(tools).length > 0) {
158
+ setSpanAttribute(
159
+ span,
160
+ "gen_ai.tool.definitions",
161
+ safeJsonStringify(
162
+ Object.entries(tools).map(([name, definition]) => ({
163
+ type: "function",
164
+ name,
165
+ description: definition.description,
166
+ parameters: zodSchemaToJsonSchema(definition.parameters)
167
+ }))
168
+ )
169
+ );
170
+ }
171
+ }
172
+ function setChatOutputAttributes(span, result) {
173
+ const parts = serializeAssistantContentParts(result.parts);
174
+ setSpanAttribute(
175
+ span,
176
+ "gen_ai.output.messages",
177
+ safeJsonStringify([
178
+ {
179
+ role: "assistant",
180
+ parts,
181
+ finish_reason: result.finishReason
182
+ }
183
+ ])
184
+ );
185
+ const outputValue = result.content ?? (parts.length > 0 ? safeJsonStringify(parts) : void 0);
186
+ setSpanAttribute(
187
+ span,
188
+ "output.value",
189
+ outputValue === null ? void 0 : outputValue
190
+ );
191
+ }
192
+ function setObjectOutputAttributes(span, result) {
193
+ if (result.object === void 0) {
194
+ return;
195
+ }
196
+ const objectContent = safeJsonStringify(result.object);
197
+ if (!objectContent) {
198
+ return;
199
+ }
200
+ setSpanAttribute(
201
+ span,
202
+ "gen_ai.output.messages",
203
+ safeJsonStringify([
204
+ {
205
+ role: "assistant",
206
+ parts: [
207
+ {
208
+ type: "text",
209
+ content: objectContent
210
+ }
211
+ ],
212
+ finish_reason: result.finishReason
213
+ }
214
+ ])
215
+ );
216
+ span.setAttribute("output.value", objectContent);
217
+ }
218
+ function setEmbedInputAttributes(span, input) {
219
+ setSpanAttribute(
220
+ span,
221
+ "input.value",
222
+ typeof input === "string" ? input : safeJsonStringify(input)
223
+ );
224
+ }
225
+ function setImageInputAttributes(span, prompt) {
226
+ span.setAttribute("input.value", prompt);
227
+ }
228
+ function setChatUsageAttributes(span, usage) {
229
+ span.setAttribute("gen_ai.usage.input_tokens", usage.inputTokens);
230
+ span.setAttribute("gen_ai.usage.output_tokens", usage.outputTokens);
231
+ span.setAttribute(
232
+ "gen_ai.usage.cache_read.input_tokens",
233
+ usage.inputTokenDetails.cacheReadTokens
234
+ );
235
+ span.setAttribute(
236
+ "gen_ai.usage.cache_creation.input_tokens",
237
+ usage.inputTokenDetails.cacheWriteTokens
238
+ );
239
+ }
240
+ function setEmbedUsageAttributes(span, usage) {
241
+ if (!usage) {
242
+ return;
243
+ }
244
+ span.setAttribute("gen_ai.usage.input_tokens", usage.inputTokens);
245
+ }
246
+ function setFinishReasonAttribute(span, finishReason) {
247
+ span.setAttribute("gen_ai.response.finish_reasons", [finishReason]);
248
+ }
249
+ function setChatRequestAttributes(span, model, options, outputType) {
250
+ span.setAttribute("gen_ai.provider.name", model.provider);
251
+ span.setAttribute("gen_ai.request.model", model.modelId);
252
+ span.setAttribute("gen_ai.operation.name", "chat");
253
+ span.setAttribute("gen_ai.output.type", outputType);
254
+ setSpanAttribute(
255
+ span,
256
+ "gen_ai.request.temperature",
257
+ options.temperature
258
+ );
259
+ setSpanAttribute(span, "gen_ai.request.max_tokens", options.maxTokens);
260
+ setSpanAttribute(span, "gen_ai.request.top_p", options.topP);
261
+ if ("schemaName" in options) {
262
+ setSpanAttribute(
263
+ span,
264
+ "gen_ai.request.schema_name",
265
+ options.schemaName
266
+ );
267
+ }
268
+ setMetadataAttributes(span, options.metadata);
269
+ }
270
+ function setEmbedRequestAttributes(span, model, options) {
271
+ span.setAttribute("gen_ai.provider.name", model.provider);
272
+ span.setAttribute("gen_ai.request.model", model.modelId);
273
+ span.setAttribute("gen_ai.operation.name", "embeddings");
274
+ setMetadataAttributes(span, options.metadata);
275
+ }
276
+ function setImageRequestAttributes(span, model, options) {
277
+ span.setAttribute("gen_ai.provider.name", model.provider);
278
+ span.setAttribute("gen_ai.request.model", model.modelId);
279
+ span.setAttribute("gen_ai.operation.name", "image_generation");
280
+ span.setAttribute("gen_ai.output.type", "image");
281
+ setMetadataAttributes(span, options.metadata);
282
+ }
283
+ function createChatSpanName(model) {
284
+ return `chat ${model.modelId}`;
285
+ }
286
+ function createEmbedSpanName(model) {
287
+ return `embeddings ${model.modelId}`;
288
+ }
289
+ function createImageSpanName(model) {
290
+ return `image_generation ${model.modelId}`;
291
+ }
292
+
293
+ // src/index.ts
294
+ function getErrorMessage(error) {
295
+ if (error instanceof Error) {
296
+ return error.message;
297
+ }
298
+ return String(error);
299
+ }
300
+ function toError(error) {
301
+ if (error instanceof Error) {
302
+ return error;
303
+ }
304
+ return new Error(String(error));
305
+ }
306
+ function recordError(span, error) {
307
+ span.setAttribute("error.type", error instanceof Error ? error.name : "_OTHER");
308
+ span.setStatus({
309
+ code: SpanStatusCode.ERROR,
310
+ message: getErrorMessage(error)
311
+ });
312
+ span.recordException(toError(error));
313
+ }
314
+ function createOtelMiddleware(options = {}) {
315
+ const { recordContent = false, tracerName = "core-ai" } = options;
316
+ return {
317
+ generate: async ({ execute, options: generateOptions, model }) => {
318
+ const tracer = trace.getTracer(tracerName);
319
+ return tracer.startActiveSpan(
320
+ createChatSpanName(model),
321
+ {
322
+ kind: SpanKind.CLIENT
323
+ },
324
+ async (span) => {
325
+ setChatRequestAttributes(span, model, generateOptions, "text");
326
+ if (recordContent) {
327
+ setChatInputAttributes(
328
+ span,
329
+ generateOptions.messages,
330
+ generateOptions.tools
331
+ );
332
+ }
333
+ try {
334
+ const result = await execute();
335
+ setChatUsageAttributes(span, result.usage);
336
+ setFinishReasonAttribute(span, result.finishReason);
337
+ if (recordContent) {
338
+ setChatOutputAttributes(span, result);
339
+ }
340
+ span.setStatus({
341
+ code: SpanStatusCode.OK
342
+ });
343
+ return result;
344
+ } catch (error) {
345
+ recordError(span, error);
346
+ throw error;
347
+ } finally {
348
+ span.end();
349
+ }
350
+ }
351
+ );
352
+ },
353
+ stream: async ({ execute, options: generateOptions, model }) => {
354
+ const tracer = trace.getTracer(tracerName);
355
+ return tracer.startActiveSpan(
356
+ createChatSpanName(model),
357
+ {
358
+ kind: SpanKind.CLIENT
359
+ },
360
+ async (span) => {
361
+ setChatRequestAttributes(span, model, generateOptions, "text");
362
+ if (recordContent) {
363
+ setChatInputAttributes(
364
+ span,
365
+ generateOptions.messages,
366
+ generateOptions.tools
367
+ );
368
+ }
369
+ try {
370
+ const chatStream = await execute();
371
+ void chatStream.result.then((result) => {
372
+ setChatUsageAttributes(span, result.usage);
373
+ setFinishReasonAttribute(span, result.finishReason);
374
+ if (recordContent) {
375
+ setChatOutputAttributes(span, result);
376
+ }
377
+ span.setStatus({
378
+ code: SpanStatusCode.OK
379
+ });
380
+ }).catch((error) => {
381
+ recordError(span, error);
382
+ }).finally(() => {
383
+ span.end();
384
+ });
385
+ return chatStream;
386
+ } catch (error) {
387
+ recordError(span, error);
388
+ span.end();
389
+ throw error;
390
+ }
391
+ }
392
+ );
393
+ },
394
+ generateObject: async (args) => {
395
+ const { execute, options: generateOptions, model } = args;
396
+ const tracer = trace.getTracer(tracerName);
397
+ return tracer.startActiveSpan(
398
+ createChatSpanName(model),
399
+ {
400
+ kind: SpanKind.CLIENT
401
+ },
402
+ async (span) => {
403
+ setChatRequestAttributes(span, model, generateOptions, "json");
404
+ if (recordContent) {
405
+ setChatInputAttributes(span, generateOptions.messages);
406
+ }
407
+ try {
408
+ const result = await execute();
409
+ setChatUsageAttributes(span, result.usage);
410
+ setFinishReasonAttribute(span, result.finishReason);
411
+ if (recordContent) {
412
+ setObjectOutputAttributes(span, result);
413
+ }
414
+ span.setStatus({
415
+ code: SpanStatusCode.OK
416
+ });
417
+ return result;
418
+ } catch (error) {
419
+ recordError(span, error);
420
+ throw error;
421
+ } finally {
422
+ span.end();
423
+ }
424
+ }
425
+ );
426
+ },
427
+ streamObject: async (args) => {
428
+ const { execute, options: generateOptions, model } = args;
429
+ const tracer = trace.getTracer(tracerName);
430
+ return tracer.startActiveSpan(
431
+ createChatSpanName(model),
432
+ {
433
+ kind: SpanKind.CLIENT
434
+ },
435
+ async (span) => {
436
+ setChatRequestAttributes(span, model, generateOptions, "json");
437
+ if (recordContent) {
438
+ setChatInputAttributes(span, generateOptions.messages);
439
+ }
440
+ try {
441
+ const objectStream = await execute();
442
+ void objectStream.result.then((result) => {
443
+ setChatUsageAttributes(span, result.usage);
444
+ setFinishReasonAttribute(span, result.finishReason);
445
+ if (recordContent) {
446
+ setObjectOutputAttributes(span, result);
447
+ }
448
+ span.setStatus({
449
+ code: SpanStatusCode.OK
450
+ });
451
+ }).catch((error) => {
452
+ recordError(span, error);
453
+ }).finally(() => {
454
+ span.end();
455
+ });
456
+ return objectStream;
457
+ } catch (error) {
458
+ recordError(span, error);
459
+ span.end();
460
+ throw error;
461
+ }
462
+ }
463
+ );
464
+ }
465
+ };
466
+ }
467
+ function createOtelEmbeddingMiddleware(options = {}) {
468
+ const { recordContent = false, tracerName = "core-ai" } = options;
469
+ return {
470
+ embed: async ({ execute, options: embedOptions, model }) => {
471
+ const tracer = trace.getTracer(tracerName);
472
+ return tracer.startActiveSpan(
473
+ createEmbedSpanName(model),
474
+ {
475
+ kind: SpanKind.CLIENT
476
+ },
477
+ async (span) => {
478
+ setEmbedRequestAttributes(span, model, embedOptions);
479
+ if (recordContent) {
480
+ setEmbedInputAttributes(span, embedOptions.input);
481
+ }
482
+ try {
483
+ const result = await execute();
484
+ setEmbedUsageAttributes(span, result.usage);
485
+ span.setStatus({
486
+ code: SpanStatusCode.OK
487
+ });
488
+ return result;
489
+ } catch (error) {
490
+ recordError(span, error);
491
+ throw error;
492
+ } finally {
493
+ span.end();
494
+ }
495
+ }
496
+ );
497
+ }
498
+ };
499
+ }
500
+ function createOtelImageMiddleware(options = {}) {
501
+ const { recordContent = false, tracerName = "core-ai" } = options;
502
+ return {
503
+ generate: async ({ execute, options: imageOptions, model }) => {
504
+ const tracer = trace.getTracer(tracerName);
505
+ return tracer.startActiveSpan(
506
+ createImageSpanName(model),
507
+ {
508
+ kind: SpanKind.CLIENT
509
+ },
510
+ async (span) => {
511
+ setImageRequestAttributes(span, model, imageOptions);
512
+ if (recordContent) {
513
+ setImageInputAttributes(span, imageOptions.prompt);
514
+ }
515
+ try {
516
+ const result = await execute();
517
+ span.setStatus({
518
+ code: SpanStatusCode.OK
519
+ });
520
+ return result;
521
+ } catch (error) {
522
+ recordError(span, error);
523
+ throw error;
524
+ } finally {
525
+ span.end();
526
+ }
527
+ }
528
+ );
529
+ }
530
+ };
531
+ }
532
+ export {
533
+ createOtelEmbeddingMiddleware,
534
+ createOtelImageMiddleware,
535
+ createOtelMiddleware
536
+ };
package/package.json ADDED
@@ -0,0 +1,60 @@
1
+ {
2
+ "name": "@core-ai/opentelemetry",
3
+ "version": "0.10.0",
4
+ "description": "OpenTelemetry middleware for @core-ai/core-ai",
5
+ "license": "MIT",
6
+ "author": "Omnifact (https://omnifact.ai)",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/agdevhq/core-ai.git",
10
+ "directory": "packages/opentelemetry"
11
+ },
12
+ "keywords": [
13
+ "llm",
14
+ "ai",
15
+ "sdk",
16
+ "opentelemetry",
17
+ "observability"
18
+ ],
19
+ "type": "module",
20
+ "main": "./dist/index.js",
21
+ "types": "./dist/index.d.ts",
22
+ "exports": {
23
+ ".": {
24
+ "types": "./dist/index.d.ts",
25
+ "import": "./dist/index.js"
26
+ }
27
+ },
28
+ "files": [
29
+ "dist",
30
+ "README.md",
31
+ "LICENSE"
32
+ ],
33
+ "publishConfig": {
34
+ "access": "public",
35
+ "provenance": true
36
+ },
37
+ "scripts": {
38
+ "build": "tsup",
39
+ "lint": "eslint src/ --max-warnings 0",
40
+ "check-types": "tsc --noEmit",
41
+ "test": "vitest run",
42
+ "test:watch": "vitest"
43
+ },
44
+ "dependencies": {
45
+ "@core-ai/core-ai": "^0.10.0"
46
+ },
47
+ "peerDependencies": {
48
+ "@opentelemetry/api": "^1.9.1"
49
+ },
50
+ "devDependencies": {
51
+ "@core-ai/eslint-config": "*",
52
+ "@core-ai/typescript-config": "*",
53
+ "@opentelemetry/api": "^1.9.1",
54
+ "@opentelemetry/context-async-hooks": "^2.6.1",
55
+ "@opentelemetry/sdk-trace-base": "^2.6.1",
56
+ "typescript": "^5.7.3",
57
+ "vitest": "^3.2.4",
58
+ "zod": "^4.0.0"
59
+ }
60
+ }