@posthog/ai 7.8.13 → 7.9.1

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.
@@ -0,0 +1,1127 @@
1
+ 'use strict';
2
+
3
+ var uuid = require('uuid');
4
+ var core = require('@posthog/core');
5
+
6
+ var version = "7.9.1";
7
+
8
+ // Type guards for safer type checking
9
+
10
+ const isString = value => {
11
+ return typeof value === 'string';
12
+ };
13
+
14
+ const REDACTED_IMAGE_PLACEHOLDER = '[base64 image redacted]';
15
+
16
+ // ============================================
17
+ // Multimodal Feature Toggle
18
+ // ============================================
19
+
20
+ const isMultimodalEnabled = () => {
21
+ const val = process.env._INTERNAL_LLMA_MULTIMODAL || '';
22
+ return val.toLowerCase() === 'true' || val === '1' || val.toLowerCase() === 'yes';
23
+ };
24
+
25
+ // ============================================
26
+ // Base64 Detection Helpers
27
+ // ============================================
28
+
29
+ const isBase64DataUrl = str => {
30
+ return /^data:([^;]+);base64,/.test(str);
31
+ };
32
+ const isValidUrl = str => {
33
+ try {
34
+ new URL(str);
35
+ return true;
36
+ } catch {
37
+ // Not an absolute URL, check if it's a relative URL or path
38
+ return str.startsWith('/') || str.startsWith('./') || str.startsWith('../');
39
+ }
40
+ };
41
+ const isRawBase64 = str => {
42
+ // Skip if it's a valid URL or path
43
+ if (isValidUrl(str)) {
44
+ return false;
45
+ }
46
+
47
+ // Check if it's a valid base64 string
48
+ // Base64 images are typically at least a few hundred chars, but we'll be conservative
49
+ return str.length > 20 && /^[A-Za-z0-9+/]+=*$/.test(str);
50
+ };
51
+ function redactBase64DataUrl(str) {
52
+ if (isMultimodalEnabled()) return str;
53
+ if (!isString(str)) return str;
54
+
55
+ // Check for data URL format
56
+ if (isBase64DataUrl(str)) {
57
+ return REDACTED_IMAGE_PLACEHOLDER;
58
+ }
59
+
60
+ // Check for raw base64 (Vercel sends raw base64 for inline images)
61
+ if (isRawBase64(str)) {
62
+ return REDACTED_IMAGE_PLACEHOLDER;
63
+ }
64
+ return str;
65
+ }
66
+
67
+ // limit large outputs by truncating to 200kb (approx 200k bytes)
68
+ const MAX_OUTPUT_SIZE = 200000;
69
+ const STRING_FORMAT = 'utf8';
70
+ const getModelParams = params => {
71
+ if (!params) {
72
+ return {};
73
+ }
74
+ const modelParams = {};
75
+ const paramKeys = ['temperature', 'max_tokens', 'max_completion_tokens', 'top_p', 'frequency_penalty', 'presence_penalty', 'n', 'stop', 'stream', 'streaming', 'language', 'response_format', 'timestamp_granularities'];
76
+ for (const key of paramKeys) {
77
+ if (key in params && params[key] !== undefined) {
78
+ modelParams[key] = params[key];
79
+ }
80
+ }
81
+ return modelParams;
82
+ };
83
+ const withPrivacyMode = (client, privacyMode, input) => {
84
+ return client.privacy_mode || privacyMode ? null : input;
85
+ };
86
+ function toSafeString(input) {
87
+ if (input === undefined || input === null) {
88
+ return '';
89
+ }
90
+ if (typeof input === 'string') {
91
+ return input;
92
+ }
93
+ try {
94
+ return JSON.stringify(input);
95
+ } catch {
96
+ console.warn('Failed to stringify input', input);
97
+ return '';
98
+ }
99
+ }
100
+ const truncate = input => {
101
+ const str = toSafeString(input);
102
+ if (str === '') {
103
+ return '';
104
+ }
105
+
106
+ // Check if we need to truncate and ensure STRING_FORMAT is respected
107
+ const encoder = new TextEncoder();
108
+ const buffer = encoder.encode(str);
109
+ if (buffer.length <= MAX_OUTPUT_SIZE) {
110
+ // Ensure STRING_FORMAT is respected
111
+ return new TextDecoder(STRING_FORMAT).decode(buffer);
112
+ }
113
+
114
+ // Truncate the buffer and ensure a valid string is returned
115
+ const truncatedBuffer = buffer.slice(0, MAX_OUTPUT_SIZE);
116
+ // fatal: false means we get U+FFFD at the end if truncation broke the encoding
117
+ const decoder = new TextDecoder(STRING_FORMAT, {
118
+ fatal: false
119
+ });
120
+ let truncatedStr = decoder.decode(truncatedBuffer);
121
+ if (truncatedStr.endsWith('\uFFFD')) {
122
+ truncatedStr = truncatedStr.slice(0, -1);
123
+ }
124
+ return `${truncatedStr}... [truncated]`;
125
+ };
126
+ let AIEvent = /*#__PURE__*/function (AIEvent) {
127
+ AIEvent["Generation"] = "$ai_generation";
128
+ AIEvent["Embedding"] = "$ai_embedding";
129
+ return AIEvent;
130
+ }({});
131
+ function sanitizeValues(obj) {
132
+ if (obj === undefined || obj === null) {
133
+ return obj;
134
+ }
135
+ const jsonSafe = JSON.parse(JSON.stringify(obj));
136
+ if (typeof jsonSafe === 'string') {
137
+ // Sanitize lone surrogates by round-tripping through UTF-8
138
+ return new TextDecoder().decode(new TextEncoder().encode(jsonSafe));
139
+ } else if (Array.isArray(jsonSafe)) {
140
+ return jsonSafe.map(sanitizeValues);
141
+ } else if (jsonSafe && typeof jsonSafe === 'object') {
142
+ return Object.fromEntries(Object.entries(jsonSafe).map(([k, v]) => [k, sanitizeValues(v)]));
143
+ }
144
+ return jsonSafe;
145
+ }
146
+ const sendEventWithErrorToPosthog = async ({
147
+ client,
148
+ traceId,
149
+ error,
150
+ ...args
151
+ }) => {
152
+ const httpStatus = error && typeof error === 'object' && 'status' in error ? error.status ?? 500 : 500;
153
+ const properties = {
154
+ client,
155
+ traceId,
156
+ httpStatus,
157
+ error: JSON.stringify(error),
158
+ ...args
159
+ };
160
+ const enrichedError = error;
161
+ if (client.options?.enableExceptionAutocapture) {
162
+ // assign a uuid that can be used to link the trace and exception events
163
+ const exceptionId = core.uuidv7();
164
+ client.captureException(error, undefined, {
165
+ $ai_trace_id: traceId
166
+ }, exceptionId);
167
+ enrichedError.__posthog_previously_captured_error = true;
168
+ properties.exceptionId = exceptionId;
169
+ }
170
+ await sendEventToPosthog(properties);
171
+ return enrichedError;
172
+ };
173
+ const sendEventToPosthog = async ({
174
+ client,
175
+ eventType = AIEvent.Generation,
176
+ distinctId,
177
+ traceId,
178
+ model,
179
+ provider,
180
+ input,
181
+ output,
182
+ latency,
183
+ timeToFirstToken,
184
+ baseURL,
185
+ params,
186
+ httpStatus = 200,
187
+ usage = {},
188
+ error,
189
+ exceptionId,
190
+ tools,
191
+ captureImmediate = false
192
+ }) => {
193
+ if (!client.capture) {
194
+ return Promise.resolve();
195
+ }
196
+ // sanitize input and output for UTF-8 validity
197
+ const safeInput = sanitizeValues(input);
198
+ const safeOutput = sanitizeValues(output);
199
+ const safeError = sanitizeValues(error);
200
+ let errorData = {};
201
+ if (error) {
202
+ errorData = {
203
+ $ai_is_error: true,
204
+ $ai_error: safeError,
205
+ $exception_event_id: exceptionId
206
+ };
207
+ }
208
+ let costOverrideData = {};
209
+ if (params.posthogCostOverride) {
210
+ const inputCostUSD = (params.posthogCostOverride.inputCost ?? 0) * (usage.inputTokens ?? 0);
211
+ const outputCostUSD = (params.posthogCostOverride.outputCost ?? 0) * (usage.outputTokens ?? 0);
212
+ costOverrideData = {
213
+ $ai_input_cost_usd: inputCostUSD,
214
+ $ai_output_cost_usd: outputCostUSD,
215
+ $ai_total_cost_usd: inputCostUSD + outputCostUSD
216
+ };
217
+ }
218
+ const additionalTokenValues = {
219
+ ...(usage.reasoningTokens ? {
220
+ $ai_reasoning_tokens: usage.reasoningTokens
221
+ } : {}),
222
+ ...(usage.cacheReadInputTokens ? {
223
+ $ai_cache_read_input_tokens: usage.cacheReadInputTokens
224
+ } : {}),
225
+ ...(usage.cacheCreationInputTokens ? {
226
+ $ai_cache_creation_input_tokens: usage.cacheCreationInputTokens
227
+ } : {}),
228
+ ...(usage.webSearchCount ? {
229
+ $ai_web_search_count: usage.webSearchCount
230
+ } : {}),
231
+ ...(usage.rawUsage ? {
232
+ $ai_usage: usage.rawUsage
233
+ } : {})
234
+ };
235
+ const properties = {
236
+ $ai_lib: 'posthog-ai',
237
+ $ai_lib_version: version,
238
+ $ai_provider: params.posthogProviderOverride ?? provider,
239
+ $ai_model: params.posthogModelOverride ?? model,
240
+ $ai_model_parameters: getModelParams(params),
241
+ $ai_input: withPrivacyMode(client, params.posthogPrivacyMode ?? false, safeInput),
242
+ $ai_output_choices: withPrivacyMode(client, params.posthogPrivacyMode ?? false, safeOutput),
243
+ $ai_http_status: httpStatus,
244
+ $ai_input_tokens: usage.inputTokens ?? 0,
245
+ ...(usage.outputTokens !== undefined ? {
246
+ $ai_output_tokens: usage.outputTokens
247
+ } : {}),
248
+ ...additionalTokenValues,
249
+ $ai_latency: latency,
250
+ ...(timeToFirstToken !== undefined ? {
251
+ $ai_time_to_first_token: timeToFirstToken
252
+ } : {}),
253
+ $ai_trace_id: traceId,
254
+ $ai_base_url: baseURL,
255
+ ...params.posthogProperties,
256
+ ...(distinctId ? {} : {
257
+ $process_person_profile: false
258
+ }),
259
+ ...(tools ? {
260
+ $ai_tools: tools
261
+ } : {}),
262
+ ...errorData,
263
+ ...costOverrideData
264
+ };
265
+ const event = {
266
+ distinctId: distinctId ?? traceId,
267
+ event: eventType,
268
+ properties,
269
+ groups: params.posthogGroups
270
+ };
271
+ if (captureImmediate) {
272
+ // await capture promise to send single event in serverless environments
273
+ await client.captureImmediate(event);
274
+ } else {
275
+ client.capture(event);
276
+ }
277
+ return Promise.resolve();
278
+ };
279
+
280
+ const OTEL_STATUS_ERROR = 2;
281
+ const AI_TELEMETRY_METADATA_PREFIX = 'ai.telemetry.metadata.';
282
+ function parseJsonValue(value) {
283
+ if (value === undefined || value === null) {
284
+ return null;
285
+ }
286
+ if (typeof value !== 'string') {
287
+ return value;
288
+ }
289
+ try {
290
+ return JSON.parse(value);
291
+ } catch {
292
+ return null;
293
+ }
294
+ }
295
+ function toNumber(value) {
296
+ if (typeof value === 'number' && Number.isFinite(value)) {
297
+ return value;
298
+ }
299
+ if (typeof value === 'string') {
300
+ const parsed = Number(value);
301
+ if (Number.isFinite(parsed)) {
302
+ return parsed;
303
+ }
304
+ }
305
+ return undefined;
306
+ }
307
+ function toStringValue(value) {
308
+ return typeof value === 'string' ? value : undefined;
309
+ }
310
+ function toStringArray(value) {
311
+ if (!Array.isArray(value)) {
312
+ return [];
313
+ }
314
+ return value.filter(item => typeof item === 'string');
315
+ }
316
+ function toSafeBinaryData(value) {
317
+ const asString = typeof value === 'string' ? value : JSON.stringify(value ?? '');
318
+ return truncate(redactBase64DataUrl(asString));
319
+ }
320
+ function toMimeType(value) {
321
+ return typeof value === 'string' && value.length > 0 ? value : 'application/octet-stream';
322
+ }
323
+ function getSpanLatencySeconds(span) {
324
+ const duration = span.duration;
325
+ if (!duration || !Array.isArray(duration) || duration.length !== 2) {
326
+ return 0;
327
+ }
328
+ const seconds = Number(duration[0]) || 0;
329
+ const nanos = Number(duration[1]) || 0;
330
+ return seconds + nanos / 1_000_000_000;
331
+ }
332
+ function getOperationId(span) {
333
+ const attributes = span.attributes || {};
334
+ const operationId = toStringValue(attributes['ai.operationId']);
335
+ if (operationId) {
336
+ return operationId;
337
+ }
338
+ return span.name || '';
339
+ }
340
+ function isDoGenerateSpan(operationId) {
341
+ return operationId.endsWith('.doGenerate');
342
+ }
343
+ function isDoStreamSpan(operationId) {
344
+ return operationId.endsWith('.doStream');
345
+ }
346
+ function isDoEmbedSpan(operationId) {
347
+ return operationId.endsWith('.doEmbed');
348
+ }
349
+ function shouldMapAiSdkSpan(span) {
350
+ const operationId = getOperationId(span);
351
+ return isDoGenerateSpan(operationId) || isDoStreamSpan(operationId) || isDoEmbedSpan(operationId);
352
+ }
353
+ function extractAiSdkTelemetryMetadata(attributes) {
354
+ const metadata = {};
355
+ for (const [key, value] of Object.entries(attributes)) {
356
+ if (key.startsWith(AI_TELEMETRY_METADATA_PREFIX)) {
357
+ metadata[key.slice(AI_TELEMETRY_METADATA_PREFIX.length)] = value;
358
+ }
359
+ }
360
+ if (metadata.traceId && typeof metadata.traceId === 'string') {
361
+ metadata.trace_id = metadata.traceId;
362
+ }
363
+ return metadata;
364
+ }
365
+ function mapPromptMessagesInput(attributes) {
366
+ const promptMessages = parseJsonValue(attributes['ai.prompt.messages']) || [];
367
+ if (!Array.isArray(promptMessages)) {
368
+ return [];
369
+ }
370
+ return promptMessages.map(message => {
371
+ const role = typeof message?.role === 'string' ? message.role : 'user';
372
+ const content = message?.content;
373
+ if (typeof content === 'string') {
374
+ return {
375
+ role,
376
+ content: [{
377
+ type: 'text',
378
+ text: truncate(content)
379
+ }]
380
+ };
381
+ }
382
+ if (Array.isArray(content)) {
383
+ return {
384
+ role,
385
+ content: content.map(part => {
386
+ if (part && typeof part === 'object' && 'type' in part) {
387
+ const typedPart = part;
388
+ if (typedPart.type === 'text' && typeof typedPart.text === 'string') {
389
+ return {
390
+ type: 'text',
391
+ text: truncate(typedPart.text)
392
+ };
393
+ }
394
+ return typedPart;
395
+ }
396
+ return {
397
+ type: 'text',
398
+ text: truncate(String(part))
399
+ };
400
+ })
401
+ };
402
+ }
403
+ return {
404
+ role,
405
+ content: [{
406
+ type: 'text',
407
+ text: truncate(content)
408
+ }]
409
+ };
410
+ });
411
+ }
412
+ function mapPromptInput(attributes, operationId) {
413
+ if (isDoEmbedSpan(operationId)) {
414
+ if (attributes['ai.values'] !== undefined) {
415
+ return attributes['ai.values'];
416
+ }
417
+ return attributes['ai.value'] ?? null;
418
+ }
419
+ const promptMessages = mapPromptMessagesInput(attributes);
420
+ if (promptMessages.length > 0) {
421
+ return promptMessages;
422
+ }
423
+ if (attributes['ai.prompt'] !== undefined) {
424
+ return [{
425
+ role: 'user',
426
+ content: [{
427
+ type: 'text',
428
+ text: truncate(attributes['ai.prompt'])
429
+ }]
430
+ }];
431
+ }
432
+ return [];
433
+ }
434
+ function mapOutputPart(part) {
435
+ const partType = toStringValue(part.type);
436
+ if (partType === 'text' && typeof part.text === 'string') {
437
+ return {
438
+ type: 'text',
439
+ text: truncate(part.text)
440
+ };
441
+ }
442
+ if (partType === 'tool-call') {
443
+ const toolName = toStringValue(part.toolName) || toStringValue(part.function?.name) || '';
444
+ const toolCallId = toStringValue(part.toolCallId) || toStringValue(part.id) || '';
445
+ const input = 'input' in part ? part.input : part.function?.arguments;
446
+ if (toolName) {
447
+ return {
448
+ type: 'tool-call',
449
+ id: toolCallId,
450
+ function: {
451
+ name: toolName,
452
+ arguments: typeof input === 'string' ? input : JSON.stringify(input ?? {})
453
+ }
454
+ };
455
+ }
456
+ }
457
+ if (partType === 'file') {
458
+ const mediaType = toMimeType(part.mediaType ?? part.mimeType ?? part.contentType);
459
+ const data = part.data ?? part.base64 ?? part.bytes ?? part.url ?? part.uri;
460
+ if (data !== undefined) {
461
+ return {
462
+ type: 'file',
463
+ name: 'generated_file',
464
+ mediaType,
465
+ data: toSafeBinaryData(data)
466
+ };
467
+ }
468
+ }
469
+ if (partType === 'image') {
470
+ const mediaType = toMimeType(part.mediaType ?? part.mimeType ?? part.contentType ?? 'image/unknown');
471
+ const data = part.data ?? part.base64 ?? part.bytes ?? part.url ?? part.uri ?? part.image ?? part.image_url;
472
+ if (data !== undefined) {
473
+ return {
474
+ type: 'file',
475
+ name: 'generated_file',
476
+ mediaType,
477
+ data: toSafeBinaryData(data)
478
+ };
479
+ }
480
+ }
481
+ const inlineData = part.inlineData ?? part.inline_data;
482
+ if (inlineData && typeof inlineData === 'object' && inlineData.data !== undefined) {
483
+ const mediaType = toMimeType(inlineData.mimeType ?? inlineData.mime_type);
484
+ return {
485
+ type: 'file',
486
+ name: 'generated_file',
487
+ mediaType,
488
+ data: toSafeBinaryData(inlineData.data)
489
+ };
490
+ }
491
+ if (partType === 'object' && part.object !== undefined) {
492
+ return {
493
+ type: 'object',
494
+ object: part.object
495
+ };
496
+ }
497
+ return null;
498
+ }
499
+ function mapResponseMessagesOutput(attributes) {
500
+ const messagesRaw = parseJsonValue(attributes['ai.response.messages']) ?? parseJsonValue(attributes['ai.response.message']);
501
+ if (!messagesRaw) {
502
+ return [];
503
+ }
504
+ const messages = Array.isArray(messagesRaw) ? messagesRaw : [messagesRaw];
505
+ const mappedMessages = [];
506
+ for (const message of messages) {
507
+ if (!message || typeof message !== 'object') {
508
+ continue;
509
+ }
510
+ const role = toStringValue(message.role) || 'assistant';
511
+ const content = message.content;
512
+ if (typeof content === 'string') {
513
+ mappedMessages.push({
514
+ role,
515
+ content: [{
516
+ type: 'text',
517
+ text: truncate(content)
518
+ }]
519
+ });
520
+ continue;
521
+ }
522
+ if (Array.isArray(content)) {
523
+ const parts = content.map(part => part && typeof part === 'object' ? mapOutputPart(part) : null).filter(part => part !== null);
524
+ if (parts.length > 0) {
525
+ mappedMessages.push({
526
+ role,
527
+ content: parts
528
+ });
529
+ }
530
+ continue;
531
+ }
532
+ }
533
+ return mappedMessages;
534
+ }
535
+ function mapTextToolObjectOutputParts(attributes) {
536
+ const responseText = toStringValue(attributes['ai.response.text']) || '';
537
+ const toolCalls = parseJsonValue(attributes['ai.response.toolCalls']) || [];
538
+ const responseObjectRaw = attributes['ai.response.object'];
539
+ const responseObject = parseJsonValue(responseObjectRaw);
540
+ const contentParts = [];
541
+ if (responseText) {
542
+ contentParts.push({
543
+ type: 'text',
544
+ text: truncate(responseText)
545
+ });
546
+ }
547
+ if (responseObjectRaw !== undefined) {
548
+ contentParts.push({
549
+ type: 'object',
550
+ object: responseObject ?? responseObjectRaw
551
+ });
552
+ }
553
+ if (Array.isArray(toolCalls)) {
554
+ for (const toolCall of toolCalls) {
555
+ if (!toolCall || typeof toolCall !== 'object') {
556
+ continue;
557
+ }
558
+ const toolName = typeof toolCall.toolName === 'string' ? toolCall.toolName : '';
559
+ const toolCallId = typeof toolCall.toolCallId === 'string' ? toolCall.toolCallId : '';
560
+ if (!toolName) {
561
+ continue;
562
+ }
563
+ const input = 'input' in toolCall ? toolCall.input : {};
564
+ contentParts.push({
565
+ type: 'tool-call',
566
+ id: toolCallId,
567
+ function: {
568
+ name: toolName,
569
+ arguments: typeof input === 'string' ? input : JSON.stringify(input)
570
+ }
571
+ });
572
+ }
573
+ }
574
+ return contentParts;
575
+ }
576
+ function mapResponseFilesOutput(attributes) {
577
+ const responseFiles = parseJsonValue(attributes['ai.response.files']) || [];
578
+ if (!Array.isArray(responseFiles)) {
579
+ return [];
580
+ }
581
+ const mapped = [];
582
+ for (const file of responseFiles) {
583
+ if (!file || typeof file !== 'object') {
584
+ continue;
585
+ }
586
+ const mimeType = toMimeType(file.mimeType ?? file.mediaType ?? file.contentType);
587
+ const data = file.data ?? file.base64 ?? file.bytes;
588
+ const url = typeof file.url === 'string' ? file.url : typeof file.uri === 'string' ? file.uri : undefined;
589
+ if (data !== undefined) {
590
+ mapped.push({
591
+ type: 'file',
592
+ name: 'generated_file',
593
+ mediaType: mimeType,
594
+ data: toSafeBinaryData(data)
595
+ });
596
+ continue;
597
+ }
598
+ if (url) {
599
+ mapped.push({
600
+ type: 'file',
601
+ name: 'generated_file',
602
+ mediaType: mimeType,
603
+ data: truncate(url)
604
+ });
605
+ }
606
+ }
607
+ return mapped;
608
+ }
609
+ function extractGeminiParts(providerMetadata) {
610
+ const parts = [];
611
+ const visit = node => {
612
+ if (!node || typeof node !== 'object') {
613
+ return;
614
+ }
615
+ if (Array.isArray(node)) {
616
+ for (const item of node) {
617
+ visit(item);
618
+ }
619
+ return;
620
+ }
621
+ const objectNode = node;
622
+ const maybeParts = objectNode.parts;
623
+ if (Array.isArray(maybeParts)) {
624
+ for (const part of maybeParts) {
625
+ if (part && typeof part === 'object') {
626
+ parts.push(part);
627
+ }
628
+ }
629
+ }
630
+ for (const value of Object.values(objectNode)) {
631
+ visit(value);
632
+ }
633
+ };
634
+ visit(providerMetadata);
635
+ return parts;
636
+ }
637
+ function mapProviderMetadataInlineDataOutput(providerMetadata) {
638
+ const parts = extractGeminiParts(providerMetadata);
639
+ const mapped = [];
640
+ for (const part of parts) {
641
+ const inlineData = part.inlineData ?? part.inline_data;
642
+ if (!inlineData || typeof inlineData !== 'object') {
643
+ continue;
644
+ }
645
+ const mimeType = toMimeType(inlineData.mimeType ?? inlineData.mime_type);
646
+ if (inlineData.data === undefined) {
647
+ continue;
648
+ }
649
+ mapped.push({
650
+ type: 'file',
651
+ name: 'generated_file',
652
+ mediaType: mimeType,
653
+ data: toSafeBinaryData(inlineData.data)
654
+ });
655
+ }
656
+ return mapped;
657
+ }
658
+ function mapProviderMetadataTextOutput(providerMetadata) {
659
+ const parts = extractGeminiParts(providerMetadata);
660
+ const mapped = [];
661
+ for (const part of parts) {
662
+ if (typeof part.text === 'string' && part.text.length > 0) {
663
+ mapped.push({
664
+ type: 'text',
665
+ text: truncate(part.text)
666
+ });
667
+ }
668
+ }
669
+ return mapped;
670
+ }
671
+ function extractMediaBlocksFromUnknownNode(node) {
672
+ const mapped = [];
673
+ const visit = value => {
674
+ if (!value || typeof value !== 'object') {
675
+ return;
676
+ }
677
+ if (Array.isArray(value)) {
678
+ for (const item of value) {
679
+ visit(item);
680
+ }
681
+ return;
682
+ }
683
+ const objectValue = value;
684
+ const inlineData = objectValue.inlineData ?? objectValue.inline_data;
685
+ if (inlineData && typeof inlineData === 'object' && inlineData.data !== undefined) {
686
+ const mediaType = toMimeType(inlineData.mimeType ?? inlineData.mime_type);
687
+ mapped.push({
688
+ type: 'file',
689
+ name: 'generated_file',
690
+ mediaType,
691
+ data: toSafeBinaryData(inlineData.data)
692
+ });
693
+ }
694
+ if ((objectValue.type === 'file' || 'mediaType' in objectValue || 'mimeType' in objectValue) && objectValue.data) {
695
+ const mediaType = toMimeType(objectValue.mediaType ?? objectValue.mimeType);
696
+ mapped.push({
697
+ type: 'file',
698
+ name: 'generated_file',
699
+ mediaType,
700
+ data: toSafeBinaryData(objectValue.data)
701
+ });
702
+ }
703
+ for (const child of Object.values(objectValue)) {
704
+ visit(child);
705
+ }
706
+ };
707
+ visit(node);
708
+ return mapped;
709
+ }
710
+ function mapUnknownResponseAttributeMediaOutput(attributes) {
711
+ const mapped = [];
712
+ for (const [key, value] of Object.entries(attributes)) {
713
+ if (!key.startsWith('ai.response.')) {
714
+ continue;
715
+ }
716
+ if (key === 'ai.response.text' || key === 'ai.response.toolCalls' || key === 'ai.response.object' || key === 'ai.response.files' || key === 'ai.response.message' || key === 'ai.response.messages' || key === 'ai.response.providerMetadata') {
717
+ continue;
718
+ }
719
+ const parsed = typeof value === 'string' ? parseJsonValue(value) ?? value : value;
720
+ mapped.push(...extractMediaBlocksFromUnknownNode(parsed));
721
+ }
722
+ return mapped;
723
+ }
724
+ function mapGenericResponseAttributeMediaOutput(attributes) {
725
+ const mapped = [];
726
+ for (const [key, value] of Object.entries(attributes)) {
727
+ if (!key.includes('response') || key.startsWith('ai.response.') || key === 'ai.response.providerMetadata' || key.startsWith('ai.prompt.') || key.startsWith('gen_ai.request.')) {
728
+ continue;
729
+ }
730
+ const parsed = typeof value === 'string' ? parseJsonValue(value) : value;
731
+ if (parsed === null || parsed === undefined) {
732
+ continue;
733
+ }
734
+ mapped.push(...extractMediaBlocksFromUnknownNode(parsed));
735
+ }
736
+ return mapped;
737
+ }
738
+ function dedupeContentParts(parts) {
739
+ const seen = new Set();
740
+ const deduped = [];
741
+ for (const part of parts) {
742
+ const key = JSON.stringify(part);
743
+ if (seen.has(key)) {
744
+ continue;
745
+ }
746
+ seen.add(key);
747
+ deduped.push(part);
748
+ }
749
+ return deduped;
750
+ }
751
+ function mapOutput(attributes, operationId, providerMetadata) {
752
+ if (isDoEmbedSpan(operationId)) {
753
+ // Keep embedding behavior aligned with existing provider wrappers.
754
+ return null;
755
+ }
756
+ const responseMessages = mapResponseMessagesOutput(attributes);
757
+ if (responseMessages.length > 0) {
758
+ return responseMessages;
759
+ }
760
+ const textToolObjectParts = mapTextToolObjectOutputParts(attributes);
761
+ const responseFileParts = mapResponseFilesOutput(attributes);
762
+ const unknownMediaParts = mapUnknownResponseAttributeMediaOutput(attributes);
763
+ const genericResponseMediaParts = mapGenericResponseAttributeMediaOutput(attributes);
764
+ const providerMetadataTextParts = mapProviderMetadataTextOutput(providerMetadata);
765
+ const providerMetadataInlineParts = mapProviderMetadataInlineDataOutput(providerMetadata);
766
+ const mergedContentParts = dedupeContentParts([...textToolObjectParts, ...responseFileParts, ...unknownMediaParts, ...genericResponseMediaParts, ...providerMetadataTextParts, ...providerMetadataInlineParts]);
767
+ const contentParts = mergedContentParts;
768
+ if (contentParts.length === 0) {
769
+ return [];
770
+ }
771
+ return [{
772
+ role: 'assistant',
773
+ content: contentParts
774
+ }];
775
+ }
776
+ function mapModelSettings(attributes, operationId) {
777
+ const temperature = toNumber(attributes['ai.settings.temperature']) ?? toNumber(attributes['gen_ai.request.temperature']);
778
+ const maxTokens = toNumber(attributes['ai.settings.maxTokens']) ?? toNumber(attributes['gen_ai.request.max_tokens']);
779
+ const maxOutputTokens = toNumber(attributes['ai.settings.maxOutputTokens']);
780
+ const topP = toNumber(attributes['ai.settings.topP']) ?? toNumber(attributes['gen_ai.request.top_p']);
781
+ const frequencyPenalty = toNumber(attributes['ai.settings.frequencyPenalty']) ?? toNumber(attributes['gen_ai.request.frequency_penalty']);
782
+ const presencePenalty = toNumber(attributes['ai.settings.presencePenalty']) ?? toNumber(attributes['gen_ai.request.presence_penalty']);
783
+ const stopSequences = parseJsonValue(attributes['ai.settings.stopSequences']) ?? parseJsonValue(attributes['gen_ai.request.stop_sequences']);
784
+ const stream = isDoStreamSpan(operationId);
785
+ return {
786
+ ...(temperature !== undefined ? {
787
+ temperature
788
+ } : {}),
789
+ ...(maxTokens !== undefined ? {
790
+ max_tokens: maxTokens
791
+ } : {}),
792
+ ...(maxOutputTokens !== undefined ? {
793
+ max_completion_tokens: maxOutputTokens
794
+ } : {}),
795
+ ...(topP !== undefined ? {
796
+ top_p: topP
797
+ } : {}),
798
+ ...(frequencyPenalty !== undefined ? {
799
+ frequency_penalty: frequencyPenalty
800
+ } : {}),
801
+ ...(presencePenalty !== undefined ? {
802
+ presence_penalty: presencePenalty
803
+ } : {}),
804
+ ...(stopSequences !== null ? {
805
+ stop: stopSequences
806
+ } : {}),
807
+ ...(stream ? {
808
+ stream: true
809
+ } : {})
810
+ };
811
+ }
812
+ function mapUsage(attributes, providerMetadata, operationId) {
813
+ if (isDoEmbedSpan(operationId)) {
814
+ const tokens = toNumber(attributes['ai.usage.tokens']) ?? toNumber(attributes['gen_ai.usage.input_tokens']) ?? 0;
815
+ return {
816
+ inputTokens: tokens,
817
+ rawUsage: {
818
+ usage: {
819
+ tokens
820
+ },
821
+ providerMetadata
822
+ }
823
+ };
824
+ }
825
+ const inputTokens = toNumber(attributes['ai.usage.promptTokens']) ?? toNumber(attributes['gen_ai.usage.input_tokens']) ?? 0;
826
+ const outputTokens = toNumber(attributes['ai.usage.completionTokens']) ?? toNumber(attributes['gen_ai.usage.output_tokens']) ?? 0;
827
+ const totalTokens = toNumber(attributes['ai.usage.totalTokens']);
828
+ const reasoningTokens = toNumber(attributes['ai.usage.reasoningTokens']);
829
+ const cachedInputTokens = toNumber(attributes['ai.usage.cachedInputTokens']);
830
+ return {
831
+ inputTokens,
832
+ outputTokens,
833
+ ...(reasoningTokens !== undefined ? {
834
+ reasoningTokens
835
+ } : {}),
836
+ ...(cachedInputTokens !== undefined ? {
837
+ cacheReadInputTokens: cachedInputTokens
838
+ } : {}),
839
+ rawUsage: {
840
+ usage: {
841
+ promptTokens: inputTokens,
842
+ completionTokens: outputTokens,
843
+ ...(totalTokens !== undefined ? {
844
+ totalTokens
845
+ } : {})
846
+ },
847
+ providerMetadata
848
+ }
849
+ };
850
+ }
851
+ function parsePromptTools(attributes) {
852
+ const rawTools = attributes['ai.prompt.tools'];
853
+ if (!Array.isArray(rawTools)) {
854
+ return null;
855
+ }
856
+ const parsedTools = [];
857
+ for (const rawTool of rawTools) {
858
+ if (typeof rawTool === 'string') {
859
+ const parsed = parseJsonValue(rawTool);
860
+ if (parsed !== null) {
861
+ parsedTools.push(parsed);
862
+ }
863
+ continue;
864
+ }
865
+ if (rawTool && typeof rawTool === 'object') {
866
+ parsedTools.push(rawTool);
867
+ }
868
+ }
869
+ return parsedTools.length > 0 ? parsedTools : null;
870
+ }
871
+ function extractProviderMetadata(attributes) {
872
+ const rawProviderMetadata = attributes['ai.response.providerMetadata'];
873
+ return parseJsonValue(rawProviderMetadata) || {};
874
+ }
875
+ function getAiSdkFrameworkVersion(span) {
876
+ const instrumentedSpan = span;
877
+ const attributes = span.attributes || {};
878
+ const instrumentationScopeVersion = toStringValue(instrumentedSpan.instrumentationScope?.version) || toStringValue(instrumentedSpan.instrumentationLibrary?.version);
879
+ const aiUserAgent = toStringValue(attributes['ai.request.headers.user-agent']);
880
+ const userAgentVersionMatch = aiUserAgent?.match(/\bai\/(\d+(?:\.\d+)*)\b/i);
881
+ const userAgentVersion = userAgentVersionMatch?.[1];
882
+ const rawVersion = instrumentationScopeVersion || userAgentVersion;
883
+ if (!rawVersion) {
884
+ return undefined;
885
+ }
886
+ const majorVersionMatch = rawVersion.match(/^v?(\d+)/i);
887
+ return majorVersionMatch ? majorVersionMatch[1] : rawVersion;
888
+ }
889
+ function buildPosthogProperties(attributes, operationId) {
890
+ const telemetryMetadata = extractAiSdkTelemetryMetadata(attributes);
891
+ const finishReasons = toStringArray(parseJsonValue(attributes['gen_ai.response.finish_reasons']));
892
+ const finishReason = toStringValue(attributes['ai.response.finishReason']) || finishReasons[0];
893
+ const toolChoice = parseJsonValue(attributes['ai.prompt.toolChoice']) ?? attributes['ai.prompt.toolChoice'];
894
+ return {
895
+ ...telemetryMetadata,
896
+ $ai_framework: 'vercel',
897
+ ai_operation_id: operationId,
898
+ ...(finishReason ? {
899
+ ai_finish_reason: finishReason
900
+ } : {}),
901
+ ...(toStringValue(attributes['ai.response.model']) ? {
902
+ ai_response_model: attributes['ai.response.model']
903
+ } : {}),
904
+ ...(toStringValue(attributes['gen_ai.response.model']) ? {
905
+ ai_response_model: attributes['gen_ai.response.model']
906
+ } : {}),
907
+ ...(toStringValue(attributes['ai.response.id']) ? {
908
+ ai_response_id: attributes['ai.response.id']
909
+ } : {}),
910
+ ...(toStringValue(attributes['gen_ai.response.id']) ? {
911
+ ai_response_id: attributes['gen_ai.response.id']
912
+ } : {}),
913
+ ...(toStringValue(attributes['ai.response.timestamp']) ? {
914
+ ai_response_timestamp: attributes['ai.response.timestamp']
915
+ } : {}),
916
+ ...(toNumber(attributes['ai.response.msToFinish']) !== undefined ? {
917
+ ai_response_ms_to_finish: toNumber(attributes['ai.response.msToFinish'])
918
+ } : {}),
919
+ ...(toNumber(attributes['ai.response.avgCompletionTokensPerSecond']) !== undefined ? {
920
+ ai_response_avg_completion_tokens_per_second: toNumber(attributes['ai.response.avgCompletionTokensPerSecond'])
921
+ } : {}),
922
+ ...(toStringValue(attributes['ai.telemetry.functionId']) ? {
923
+ ai_telemetry_function_id: attributes['ai.telemetry.functionId']
924
+ } : {}),
925
+ ...(toNumber(attributes['ai.settings.maxRetries']) !== undefined ? {
926
+ ai_settings_max_retries: toNumber(attributes['ai.settings.maxRetries'])
927
+ } : {}),
928
+ ...(toNumber(attributes['gen_ai.request.top_k']) !== undefined ? {
929
+ ai_request_top_k: toNumber(attributes['gen_ai.request.top_k'])
930
+ } : {}),
931
+ ...(attributes['ai.schema.name'] !== undefined ? {
932
+ ai_schema_name: attributes['ai.schema.name']
933
+ } : {}),
934
+ ...(attributes['ai.schema.description'] !== undefined ? {
935
+ ai_schema_description: attributes['ai.schema.description']
936
+ } : {}),
937
+ ...(attributes['ai.settings.output'] !== undefined ? {
938
+ ai_settings_output: attributes['ai.settings.output']
939
+ } : {}),
940
+ ...(toolChoice ? {
941
+ ai_prompt_tool_choice: toolChoice
942
+ } : {})
943
+ };
944
+ }
945
+ function buildAiSdkMapperResult(span) {
946
+ const attributes = span.attributes || {};
947
+ const operationId = getOperationId(span);
948
+ const providerMetadata = extractProviderMetadata(attributes);
949
+ const model = toStringValue(attributes['ai.model.id']) || toStringValue(attributes['gen_ai.request.model']) || 'unknown';
950
+ const provider = (toStringValue(attributes['ai.model.provider']) || toStringValue(attributes['gen_ai.system']) || 'unknown').toLowerCase();
951
+ const latency = getSpanLatencySeconds(span);
952
+ const timeToFirstTokenMs = toNumber(attributes['ai.response.msToFirstChunk']);
953
+ const timeToFirstToken = timeToFirstTokenMs !== undefined ? timeToFirstTokenMs / 1000 : undefined;
954
+ const input = mapPromptInput(attributes, operationId);
955
+ const output = mapOutput(attributes, operationId, providerMetadata);
956
+ const usage = mapUsage(attributes, providerMetadata, operationId);
957
+ const modelParams = mapModelSettings(attributes, operationId);
958
+ const tools = parsePromptTools(attributes);
959
+ const httpStatus = toNumber(attributes['http.response.status_code']) || 200;
960
+ const eventType = isDoEmbedSpan(operationId) ? AIEvent.Embedding : AIEvent.Generation;
961
+ const frameworkVersion = getAiSdkFrameworkVersion(span);
962
+ const error = span.status?.code === OTEL_STATUS_ERROR ? span.status.message || 'AI SDK span recorded error status' : undefined;
963
+ return {
964
+ model,
965
+ provider,
966
+ input,
967
+ output,
968
+ latency,
969
+ timeToFirstToken,
970
+ httpStatus,
971
+ eventType,
972
+ usage,
973
+ tools,
974
+ modelParams,
975
+ posthogProperties: {
976
+ ...buildPosthogProperties(attributes, operationId),
977
+ ...(frameworkVersion ? {
978
+ $ai_framework_version: frameworkVersion
979
+ } : {})
980
+ },
981
+ error
982
+ };
983
+ }
984
+ const aiSdkSpanMapper = {
985
+ name: 'ai-sdk',
986
+ canMap: shouldMapAiSdkSpan,
987
+ map: span => {
988
+ return buildAiSdkMapperResult(span);
989
+ }
990
+ };
991
+
992
+ const defaultSpanMappers = [aiSdkSpanMapper];
993
+
994
+ function pickMapper(span, mappers) {
995
+ return mappers.find(mapper => {
996
+ try {
997
+ return mapper.canMap(span);
998
+ } catch {
999
+ return false;
1000
+ }
1001
+ });
1002
+ }
1003
+ function getTraceId(span, options, mapperTraceId) {
1004
+ if (mapperTraceId) {
1005
+ return mapperTraceId;
1006
+ }
1007
+ if (options.posthogTraceId) {
1008
+ return options.posthogTraceId;
1009
+ }
1010
+ const spanTraceId = span.spanContext?.().traceId;
1011
+ return spanTraceId || uuid.v4();
1012
+ }
1013
+ function buildPosthogParams(options, traceId, distinctId, modelParams, posthogProperties) {
1014
+ return {
1015
+ ...modelParams,
1016
+ posthogDistinctId: distinctId,
1017
+ posthogTraceId: traceId,
1018
+ posthogProperties,
1019
+ posthogPrivacyMode: options.posthogPrivacyMode,
1020
+ posthogGroups: options.posthogGroups,
1021
+ posthogModelOverride: options.posthogModelOverride,
1022
+ posthogProviderOverride: options.posthogProviderOverride,
1023
+ posthogCostOverride: options.posthogCostOverride,
1024
+ posthogCaptureImmediate: options.posthogCaptureImmediate
1025
+ };
1026
+ }
1027
+ async function captureSpan(span, phClient, options = {}) {
1028
+ if (options.shouldExportSpan && options.shouldExportSpan({
1029
+ otelSpan: span
1030
+ }) === false) {
1031
+ return;
1032
+ }
1033
+ const mappers = options.mappers ?? defaultSpanMappers;
1034
+ const mapper = pickMapper(span, mappers);
1035
+ if (!mapper) {
1036
+ return;
1037
+ }
1038
+ const mapped = mapper.map(span, {
1039
+ options
1040
+ });
1041
+ if (!mapped) {
1042
+ return;
1043
+ }
1044
+ const traceId = getTraceId(span, options, mapped.traceId);
1045
+ const distinctId = mapped.distinctId ?? options.posthogDistinctId;
1046
+ const posthogProperties = {
1047
+ ...options.posthogProperties,
1048
+ ...mapped.posthogProperties
1049
+ };
1050
+ const params = buildPosthogParams(options, traceId, distinctId, mapped.modelParams ?? {}, posthogProperties);
1051
+ const baseURL = mapped.baseURL ?? '';
1052
+ const usage = mapped.usage ?? {};
1053
+ if (mapped.error !== undefined) {
1054
+ await sendEventWithErrorToPosthog({
1055
+ eventType: mapped.eventType,
1056
+ client: phClient,
1057
+ distinctId,
1058
+ traceId,
1059
+ model: mapped.model,
1060
+ provider: mapped.provider,
1061
+ input: mapped.input,
1062
+ output: mapped.output,
1063
+ latency: mapped.latency,
1064
+ baseURL,
1065
+ params: params,
1066
+ usage,
1067
+ tools: mapped.tools,
1068
+ error: mapped.error,
1069
+ captureImmediate: options.posthogCaptureImmediate
1070
+ });
1071
+ return;
1072
+ }
1073
+ await sendEventToPosthog({
1074
+ eventType: mapped.eventType,
1075
+ client: phClient,
1076
+ distinctId,
1077
+ traceId,
1078
+ model: mapped.model,
1079
+ provider: mapped.provider,
1080
+ input: mapped.input,
1081
+ output: mapped.output,
1082
+ latency: mapped.latency,
1083
+ timeToFirstToken: mapped.timeToFirstToken,
1084
+ baseURL,
1085
+ params: params,
1086
+ httpStatus: mapped.httpStatus ?? 200,
1087
+ usage,
1088
+ tools: mapped.tools,
1089
+ captureImmediate: options.posthogCaptureImmediate
1090
+ });
1091
+ }
1092
+
1093
+ class PostHogSpanProcessor {
1094
+ pendingCaptures = new Set();
1095
+ constructor(phClient, options = {}) {
1096
+ this.phClient = phClient;
1097
+ this.options = options;
1098
+ }
1099
+ onStart(_span, _parentContext) {
1100
+ // no-op
1101
+ }
1102
+ onEnd(span) {
1103
+ const capturePromise = captureSpan(span, this.phClient, this.options).catch(error => {
1104
+ console.error('Failed to capture telemetry span', error);
1105
+ }).finally(() => {
1106
+ this.pendingCaptures.delete(capturePromise);
1107
+ });
1108
+ this.pendingCaptures.add(capturePromise);
1109
+ }
1110
+ async shutdown() {
1111
+ await this.forceFlush();
1112
+ }
1113
+ async forceFlush() {
1114
+ while (this.pendingCaptures.size > 0) {
1115
+ await Promise.allSettled([...this.pendingCaptures]);
1116
+ }
1117
+ }
1118
+ }
1119
+ function createPostHogSpanProcessor(phClient, options = {}) {
1120
+ return new PostHogSpanProcessor(phClient, options);
1121
+ }
1122
+
1123
+ exports.PostHogSpanProcessor = PostHogSpanProcessor;
1124
+ exports.aiSdkSpanMapper = aiSdkSpanMapper;
1125
+ exports.captureSpan = captureSpan;
1126
+ exports.createPostHogSpanProcessor = createPostHogSpanProcessor;
1127
+ //# sourceMappingURL=index.cjs.map