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