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