@posthog/ai 7.8.12 → 7.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -5,7 +5,7 @@ import { uuidv7 } from '@posthog/core';
5
5
  import AnthropicOriginal from '@anthropic-ai/sdk';
6
6
  import { GoogleGenAI } from '@google/genai';
7
7
 
8
- var version = "7.8.12";
8
+ var version = "7.9.0";
9
9
 
10
10
  // Type guards for safer type checking
11
11
  const isString = value => {
@@ -2593,6 +2593,849 @@ const wrapVercelLanguageModel = (model, phClient, options) => {
2593
2593
  return wrappedModel;
2594
2594
  };
2595
2595
 
2596
+ const OTEL_STATUS_ERROR = 2;
2597
+ const AI_TELEMETRY_METADATA_PREFIX = 'ai.telemetry.metadata.';
2598
+ function parseJsonValue(value) {
2599
+ if (value === undefined || value === null) {
2600
+ return null;
2601
+ }
2602
+ if (typeof value !== 'string') {
2603
+ return value;
2604
+ }
2605
+ try {
2606
+ return JSON.parse(value);
2607
+ } catch {
2608
+ return null;
2609
+ }
2610
+ }
2611
+ function toNumber(value) {
2612
+ if (typeof value === 'number' && Number.isFinite(value)) {
2613
+ return value;
2614
+ }
2615
+ if (typeof value === 'string') {
2616
+ const parsed = Number(value);
2617
+ if (Number.isFinite(parsed)) {
2618
+ return parsed;
2619
+ }
2620
+ }
2621
+ return undefined;
2622
+ }
2623
+ function toStringValue(value) {
2624
+ return typeof value === 'string' ? value : undefined;
2625
+ }
2626
+ function toStringArray(value) {
2627
+ if (!Array.isArray(value)) {
2628
+ return [];
2629
+ }
2630
+ return value.filter(item => typeof item === 'string');
2631
+ }
2632
+ function toSafeBinaryData(value) {
2633
+ const asString = typeof value === 'string' ? value : JSON.stringify(value ?? '');
2634
+ return truncate(redactBase64DataUrl(asString));
2635
+ }
2636
+ function toMimeType(value) {
2637
+ return typeof value === 'string' && value.length > 0 ? value : 'application/octet-stream';
2638
+ }
2639
+ function getSpanLatencySeconds(span) {
2640
+ const duration = span.duration;
2641
+ if (!duration || !Array.isArray(duration) || duration.length !== 2) {
2642
+ return 0;
2643
+ }
2644
+ const seconds = Number(duration[0]) || 0;
2645
+ const nanos = Number(duration[1]) || 0;
2646
+ return seconds + nanos / 1000000000;
2647
+ }
2648
+ function getOperationId(span) {
2649
+ const attributes = span.attributes || {};
2650
+ const operationId = toStringValue(attributes['ai.operationId']);
2651
+ if (operationId) {
2652
+ return operationId;
2653
+ }
2654
+ return span.name || '';
2655
+ }
2656
+ function isDoGenerateSpan(operationId) {
2657
+ return operationId.endsWith('.doGenerate');
2658
+ }
2659
+ function isDoStreamSpan(operationId) {
2660
+ return operationId.endsWith('.doStream');
2661
+ }
2662
+ function isDoEmbedSpan(operationId) {
2663
+ return operationId.endsWith('.doEmbed');
2664
+ }
2665
+ function shouldMapAiSdkSpan(span) {
2666
+ const operationId = getOperationId(span);
2667
+ return isDoGenerateSpan(operationId) || isDoStreamSpan(operationId) || isDoEmbedSpan(operationId);
2668
+ }
2669
+ function extractAiSdkTelemetryMetadata(attributes) {
2670
+ const metadata = {};
2671
+ for (const [key, value] of Object.entries(attributes)) {
2672
+ if (key.startsWith(AI_TELEMETRY_METADATA_PREFIX)) {
2673
+ metadata[key.slice(AI_TELEMETRY_METADATA_PREFIX.length)] = value;
2674
+ }
2675
+ }
2676
+ if (metadata.traceId && typeof metadata.traceId === 'string') {
2677
+ metadata.trace_id = metadata.traceId;
2678
+ }
2679
+ return metadata;
2680
+ }
2681
+ function mapPromptMessagesInput(attributes) {
2682
+ const promptMessages = parseJsonValue(attributes['ai.prompt.messages']) || [];
2683
+ if (!Array.isArray(promptMessages)) {
2684
+ return [];
2685
+ }
2686
+ return promptMessages.map(message => {
2687
+ const role = typeof message?.role === 'string' ? message.role : 'user';
2688
+ const content = message?.content;
2689
+ if (typeof content === 'string') {
2690
+ return {
2691
+ role,
2692
+ content: [{
2693
+ type: 'text',
2694
+ text: truncate(content)
2695
+ }]
2696
+ };
2697
+ }
2698
+ if (Array.isArray(content)) {
2699
+ return {
2700
+ role,
2701
+ content: content.map(part => {
2702
+ if (part && typeof part === 'object' && 'type' in part) {
2703
+ const typedPart = part;
2704
+ if (typedPart.type === 'text' && typeof typedPart.text === 'string') {
2705
+ return {
2706
+ type: 'text',
2707
+ text: truncate(typedPart.text)
2708
+ };
2709
+ }
2710
+ return typedPart;
2711
+ }
2712
+ return {
2713
+ type: 'text',
2714
+ text: truncate(String(part))
2715
+ };
2716
+ })
2717
+ };
2718
+ }
2719
+ return {
2720
+ role,
2721
+ content: [{
2722
+ type: 'text',
2723
+ text: truncate(content)
2724
+ }]
2725
+ };
2726
+ });
2727
+ }
2728
+ function mapPromptInput(attributes, operationId) {
2729
+ if (isDoEmbedSpan(operationId)) {
2730
+ if (attributes['ai.values'] !== undefined) {
2731
+ return attributes['ai.values'];
2732
+ }
2733
+ return attributes['ai.value'] ?? null;
2734
+ }
2735
+ const promptMessages = mapPromptMessagesInput(attributes);
2736
+ if (promptMessages.length > 0) {
2737
+ return promptMessages;
2738
+ }
2739
+ if (attributes['ai.prompt'] !== undefined) {
2740
+ return [{
2741
+ role: 'user',
2742
+ content: [{
2743
+ type: 'text',
2744
+ text: truncate(attributes['ai.prompt'])
2745
+ }]
2746
+ }];
2747
+ }
2748
+ return [];
2749
+ }
2750
+ function mapOutputPart(part) {
2751
+ const partType = toStringValue(part.type);
2752
+ if (partType === 'text' && typeof part.text === 'string') {
2753
+ return {
2754
+ type: 'text',
2755
+ text: truncate(part.text)
2756
+ };
2757
+ }
2758
+ if (partType === 'tool-call') {
2759
+ const toolName = toStringValue(part.toolName) || toStringValue(part.function?.name) || '';
2760
+ const toolCallId = toStringValue(part.toolCallId) || toStringValue(part.id) || '';
2761
+ const input = 'input' in part ? part.input : part.function?.arguments;
2762
+ if (toolName) {
2763
+ return {
2764
+ type: 'tool-call',
2765
+ id: toolCallId,
2766
+ function: {
2767
+ name: toolName,
2768
+ arguments: typeof input === 'string' ? input : JSON.stringify(input ?? {})
2769
+ }
2770
+ };
2771
+ }
2772
+ }
2773
+ if (partType === 'file') {
2774
+ const mediaType = toMimeType(part.mediaType ?? part.mimeType ?? part.contentType);
2775
+ const data = part.data ?? part.base64 ?? part.bytes ?? part.url ?? part.uri;
2776
+ if (data !== undefined) {
2777
+ return {
2778
+ type: 'file',
2779
+ name: 'generated_file',
2780
+ mediaType,
2781
+ data: toSafeBinaryData(data)
2782
+ };
2783
+ }
2784
+ }
2785
+ if (partType === 'image') {
2786
+ const mediaType = toMimeType(part.mediaType ?? part.mimeType ?? part.contentType ?? 'image/unknown');
2787
+ const data = part.data ?? part.base64 ?? part.bytes ?? part.url ?? part.uri ?? part.image ?? part.image_url;
2788
+ if (data !== undefined) {
2789
+ return {
2790
+ type: 'file',
2791
+ name: 'generated_file',
2792
+ mediaType,
2793
+ data: toSafeBinaryData(data)
2794
+ };
2795
+ }
2796
+ }
2797
+ const inlineData = part.inlineData ?? part.inline_data;
2798
+ if (inlineData && typeof inlineData === 'object' && inlineData.data !== undefined) {
2799
+ const mediaType = toMimeType(inlineData.mimeType ?? inlineData.mime_type);
2800
+ return {
2801
+ type: 'file',
2802
+ name: 'generated_file',
2803
+ mediaType,
2804
+ data: toSafeBinaryData(inlineData.data)
2805
+ };
2806
+ }
2807
+ if (partType === 'object' && part.object !== undefined) {
2808
+ return {
2809
+ type: 'object',
2810
+ object: part.object
2811
+ };
2812
+ }
2813
+ return null;
2814
+ }
2815
+ function mapResponseMessagesOutput(attributes) {
2816
+ const messagesRaw = parseJsonValue(attributes['ai.response.messages']) ?? parseJsonValue(attributes['ai.response.message']);
2817
+ if (!messagesRaw) {
2818
+ return [];
2819
+ }
2820
+ const messages = Array.isArray(messagesRaw) ? messagesRaw : [messagesRaw];
2821
+ const mappedMessages = [];
2822
+ for (const message of messages) {
2823
+ if (!message || typeof message !== 'object') {
2824
+ continue;
2825
+ }
2826
+ const role = toStringValue(message.role) || 'assistant';
2827
+ const content = message.content;
2828
+ if (typeof content === 'string') {
2829
+ mappedMessages.push({
2830
+ role,
2831
+ content: [{
2832
+ type: 'text',
2833
+ text: truncate(content)
2834
+ }]
2835
+ });
2836
+ continue;
2837
+ }
2838
+ if (Array.isArray(content)) {
2839
+ const parts = content.map(part => part && typeof part === 'object' ? mapOutputPart(part) : null).filter(part => part !== null);
2840
+ if (parts.length > 0) {
2841
+ mappedMessages.push({
2842
+ role,
2843
+ content: parts
2844
+ });
2845
+ }
2846
+ continue;
2847
+ }
2848
+ }
2849
+ return mappedMessages;
2850
+ }
2851
+ function mapTextToolObjectOutputParts(attributes) {
2852
+ const responseText = toStringValue(attributes['ai.response.text']) || '';
2853
+ const toolCalls = parseJsonValue(attributes['ai.response.toolCalls']) || [];
2854
+ const responseObjectRaw = attributes['ai.response.object'];
2855
+ const responseObject = parseJsonValue(responseObjectRaw);
2856
+ const contentParts = [];
2857
+ if (responseText) {
2858
+ contentParts.push({
2859
+ type: 'text',
2860
+ text: truncate(responseText)
2861
+ });
2862
+ }
2863
+ if (responseObjectRaw !== undefined) {
2864
+ contentParts.push({
2865
+ type: 'object',
2866
+ object: responseObject ?? responseObjectRaw
2867
+ });
2868
+ }
2869
+ if (Array.isArray(toolCalls)) {
2870
+ for (const toolCall of toolCalls) {
2871
+ if (!toolCall || typeof toolCall !== 'object') {
2872
+ continue;
2873
+ }
2874
+ const toolName = typeof toolCall.toolName === 'string' ? toolCall.toolName : '';
2875
+ const toolCallId = typeof toolCall.toolCallId === 'string' ? toolCall.toolCallId : '';
2876
+ if (!toolName) {
2877
+ continue;
2878
+ }
2879
+ const input = 'input' in toolCall ? toolCall.input : {};
2880
+ contentParts.push({
2881
+ type: 'tool-call',
2882
+ id: toolCallId,
2883
+ function: {
2884
+ name: toolName,
2885
+ arguments: typeof input === 'string' ? input : JSON.stringify(input)
2886
+ }
2887
+ });
2888
+ }
2889
+ }
2890
+ return contentParts;
2891
+ }
2892
+ function mapResponseFilesOutput(attributes) {
2893
+ const responseFiles = parseJsonValue(attributes['ai.response.files']) || [];
2894
+ if (!Array.isArray(responseFiles)) {
2895
+ return [];
2896
+ }
2897
+ const mapped = [];
2898
+ for (const file of responseFiles) {
2899
+ if (!file || typeof file !== 'object') {
2900
+ continue;
2901
+ }
2902
+ const mimeType = toMimeType(file.mimeType ?? file.mediaType ?? file.contentType);
2903
+ const data = file.data ?? file.base64 ?? file.bytes;
2904
+ const url = typeof file.url === 'string' ? file.url : typeof file.uri === 'string' ? file.uri : undefined;
2905
+ if (data !== undefined) {
2906
+ mapped.push({
2907
+ type: 'file',
2908
+ name: 'generated_file',
2909
+ mediaType: mimeType,
2910
+ data: toSafeBinaryData(data)
2911
+ });
2912
+ continue;
2913
+ }
2914
+ if (url) {
2915
+ mapped.push({
2916
+ type: 'file',
2917
+ name: 'generated_file',
2918
+ mediaType: mimeType,
2919
+ data: truncate(url)
2920
+ });
2921
+ }
2922
+ }
2923
+ return mapped;
2924
+ }
2925
+ function extractGeminiParts(providerMetadata) {
2926
+ const parts = [];
2927
+ const visit = node => {
2928
+ if (!node || typeof node !== 'object') {
2929
+ return;
2930
+ }
2931
+ if (Array.isArray(node)) {
2932
+ for (const item of node) {
2933
+ visit(item);
2934
+ }
2935
+ return;
2936
+ }
2937
+ const objectNode = node;
2938
+ const maybeParts = objectNode.parts;
2939
+ if (Array.isArray(maybeParts)) {
2940
+ for (const part of maybeParts) {
2941
+ if (part && typeof part === 'object') {
2942
+ parts.push(part);
2943
+ }
2944
+ }
2945
+ }
2946
+ for (const value of Object.values(objectNode)) {
2947
+ visit(value);
2948
+ }
2949
+ };
2950
+ visit(providerMetadata);
2951
+ return parts;
2952
+ }
2953
+ function mapProviderMetadataInlineDataOutput(providerMetadata) {
2954
+ const parts = extractGeminiParts(providerMetadata);
2955
+ const mapped = [];
2956
+ for (const part of parts) {
2957
+ const inlineData = part.inlineData ?? part.inline_data;
2958
+ if (!inlineData || typeof inlineData !== 'object') {
2959
+ continue;
2960
+ }
2961
+ const mimeType = toMimeType(inlineData.mimeType ?? inlineData.mime_type);
2962
+ if (inlineData.data === undefined) {
2963
+ continue;
2964
+ }
2965
+ mapped.push({
2966
+ type: 'file',
2967
+ name: 'generated_file',
2968
+ mediaType: mimeType,
2969
+ data: toSafeBinaryData(inlineData.data)
2970
+ });
2971
+ }
2972
+ return mapped;
2973
+ }
2974
+ function mapProviderMetadataTextOutput(providerMetadata) {
2975
+ const parts = extractGeminiParts(providerMetadata);
2976
+ const mapped = [];
2977
+ for (const part of parts) {
2978
+ if (typeof part.text === 'string' && part.text.length > 0) {
2979
+ mapped.push({
2980
+ type: 'text',
2981
+ text: truncate(part.text)
2982
+ });
2983
+ }
2984
+ }
2985
+ return mapped;
2986
+ }
2987
+ function extractMediaBlocksFromUnknownNode(node) {
2988
+ const mapped = [];
2989
+ const visit = value => {
2990
+ if (!value || typeof value !== 'object') {
2991
+ return;
2992
+ }
2993
+ if (Array.isArray(value)) {
2994
+ for (const item of value) {
2995
+ visit(item);
2996
+ }
2997
+ return;
2998
+ }
2999
+ const objectValue = value;
3000
+ const inlineData = objectValue.inlineData ?? objectValue.inline_data;
3001
+ if (inlineData && typeof inlineData === 'object' && inlineData.data !== undefined) {
3002
+ const mediaType = toMimeType(inlineData.mimeType ?? inlineData.mime_type);
3003
+ mapped.push({
3004
+ type: 'file',
3005
+ name: 'generated_file',
3006
+ mediaType,
3007
+ data: toSafeBinaryData(inlineData.data)
3008
+ });
3009
+ }
3010
+ if ((objectValue.type === 'file' || 'mediaType' in objectValue || 'mimeType' in objectValue) && objectValue.data) {
3011
+ const mediaType = toMimeType(objectValue.mediaType ?? objectValue.mimeType);
3012
+ mapped.push({
3013
+ type: 'file',
3014
+ name: 'generated_file',
3015
+ mediaType,
3016
+ data: toSafeBinaryData(objectValue.data)
3017
+ });
3018
+ }
3019
+ for (const child of Object.values(objectValue)) {
3020
+ visit(child);
3021
+ }
3022
+ };
3023
+ visit(node);
3024
+ return mapped;
3025
+ }
3026
+ function mapUnknownResponseAttributeMediaOutput(attributes) {
3027
+ const mapped = [];
3028
+ for (const [key, value] of Object.entries(attributes)) {
3029
+ if (!key.startsWith('ai.response.')) {
3030
+ continue;
3031
+ }
3032
+ 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') {
3033
+ continue;
3034
+ }
3035
+ const parsed = typeof value === 'string' ? parseJsonValue(value) ?? value : value;
3036
+ mapped.push(...extractMediaBlocksFromUnknownNode(parsed));
3037
+ }
3038
+ return mapped;
3039
+ }
3040
+ function mapGenericResponseAttributeMediaOutput(attributes) {
3041
+ const mapped = [];
3042
+ for (const [key, value] of Object.entries(attributes)) {
3043
+ if (!key.includes('response') || key.startsWith('ai.response.') || key === 'ai.response.providerMetadata' || key.startsWith('ai.prompt.') || key.startsWith('gen_ai.request.')) {
3044
+ continue;
3045
+ }
3046
+ const parsed = typeof value === 'string' ? parseJsonValue(value) : value;
3047
+ if (parsed === null || parsed === undefined) {
3048
+ continue;
3049
+ }
3050
+ mapped.push(...extractMediaBlocksFromUnknownNode(parsed));
3051
+ }
3052
+ return mapped;
3053
+ }
3054
+ function dedupeContentParts(parts) {
3055
+ const seen = new Set();
3056
+ const deduped = [];
3057
+ for (const part of parts) {
3058
+ const key = JSON.stringify(part);
3059
+ if (seen.has(key)) {
3060
+ continue;
3061
+ }
3062
+ seen.add(key);
3063
+ deduped.push(part);
3064
+ }
3065
+ return deduped;
3066
+ }
3067
+ function mapOutput(attributes, operationId, providerMetadata) {
3068
+ if (isDoEmbedSpan(operationId)) {
3069
+ // Keep embedding behavior aligned with existing provider wrappers.
3070
+ return null;
3071
+ }
3072
+ const responseMessages = mapResponseMessagesOutput(attributes);
3073
+ if (responseMessages.length > 0) {
3074
+ return responseMessages;
3075
+ }
3076
+ const textToolObjectParts = mapTextToolObjectOutputParts(attributes);
3077
+ const responseFileParts = mapResponseFilesOutput(attributes);
3078
+ const unknownMediaParts = mapUnknownResponseAttributeMediaOutput(attributes);
3079
+ const genericResponseMediaParts = mapGenericResponseAttributeMediaOutput(attributes);
3080
+ const providerMetadataTextParts = mapProviderMetadataTextOutput(providerMetadata);
3081
+ const providerMetadataInlineParts = mapProviderMetadataInlineDataOutput(providerMetadata);
3082
+ const mergedContentParts = dedupeContentParts([...textToolObjectParts, ...responseFileParts, ...unknownMediaParts, ...genericResponseMediaParts, ...providerMetadataTextParts, ...providerMetadataInlineParts]);
3083
+ const contentParts = mergedContentParts;
3084
+ if (contentParts.length === 0) {
3085
+ return [];
3086
+ }
3087
+ return [{
3088
+ role: 'assistant',
3089
+ content: contentParts
3090
+ }];
3091
+ }
3092
+ function mapModelSettings(attributes, operationId) {
3093
+ const temperature = toNumber(attributes['ai.settings.temperature']) ?? toNumber(attributes['gen_ai.request.temperature']);
3094
+ const maxTokens = toNumber(attributes['ai.settings.maxTokens']) ?? toNumber(attributes['gen_ai.request.max_tokens']);
3095
+ const maxOutputTokens = toNumber(attributes['ai.settings.maxOutputTokens']);
3096
+ const topP = toNumber(attributes['ai.settings.topP']) ?? toNumber(attributes['gen_ai.request.top_p']);
3097
+ const frequencyPenalty = toNumber(attributes['ai.settings.frequencyPenalty']) ?? toNumber(attributes['gen_ai.request.frequency_penalty']);
3098
+ const presencePenalty = toNumber(attributes['ai.settings.presencePenalty']) ?? toNumber(attributes['gen_ai.request.presence_penalty']);
3099
+ const stopSequences = parseJsonValue(attributes['ai.settings.stopSequences']) ?? parseJsonValue(attributes['gen_ai.request.stop_sequences']);
3100
+ const stream = isDoStreamSpan(operationId);
3101
+ return {
3102
+ ...(temperature !== undefined ? {
3103
+ temperature
3104
+ } : {}),
3105
+ ...(maxTokens !== undefined ? {
3106
+ max_tokens: maxTokens
3107
+ } : {}),
3108
+ ...(maxOutputTokens !== undefined ? {
3109
+ max_completion_tokens: maxOutputTokens
3110
+ } : {}),
3111
+ ...(topP !== undefined ? {
3112
+ top_p: topP
3113
+ } : {}),
3114
+ ...(frequencyPenalty !== undefined ? {
3115
+ frequency_penalty: frequencyPenalty
3116
+ } : {}),
3117
+ ...(presencePenalty !== undefined ? {
3118
+ presence_penalty: presencePenalty
3119
+ } : {}),
3120
+ ...(stopSequences !== null ? {
3121
+ stop: stopSequences
3122
+ } : {}),
3123
+ ...(stream ? {
3124
+ stream: true
3125
+ } : {})
3126
+ };
3127
+ }
3128
+ function mapUsage(attributes, providerMetadata, operationId) {
3129
+ if (isDoEmbedSpan(operationId)) {
3130
+ const tokens = toNumber(attributes['ai.usage.tokens']) ?? toNumber(attributes['gen_ai.usage.input_tokens']) ?? 0;
3131
+ return {
3132
+ inputTokens: tokens,
3133
+ rawUsage: {
3134
+ usage: {
3135
+ tokens
3136
+ },
3137
+ providerMetadata
3138
+ }
3139
+ };
3140
+ }
3141
+ const inputTokens = toNumber(attributes['ai.usage.promptTokens']) ?? toNumber(attributes['gen_ai.usage.input_tokens']) ?? 0;
3142
+ const outputTokens = toNumber(attributes['ai.usage.completionTokens']) ?? toNumber(attributes['gen_ai.usage.output_tokens']) ?? 0;
3143
+ const totalTokens = toNumber(attributes['ai.usage.totalTokens']);
3144
+ const reasoningTokens = toNumber(attributes['ai.usage.reasoningTokens']);
3145
+ const cachedInputTokens = toNumber(attributes['ai.usage.cachedInputTokens']);
3146
+ return {
3147
+ inputTokens,
3148
+ outputTokens,
3149
+ ...(reasoningTokens !== undefined ? {
3150
+ reasoningTokens
3151
+ } : {}),
3152
+ ...(cachedInputTokens !== undefined ? {
3153
+ cacheReadInputTokens: cachedInputTokens
3154
+ } : {}),
3155
+ rawUsage: {
3156
+ usage: {
3157
+ promptTokens: inputTokens,
3158
+ completionTokens: outputTokens,
3159
+ ...(totalTokens !== undefined ? {
3160
+ totalTokens
3161
+ } : {})
3162
+ },
3163
+ providerMetadata
3164
+ }
3165
+ };
3166
+ }
3167
+ function parsePromptTools(attributes) {
3168
+ const rawTools = attributes['ai.prompt.tools'];
3169
+ if (!Array.isArray(rawTools)) {
3170
+ return null;
3171
+ }
3172
+ const parsedTools = [];
3173
+ for (const rawTool of rawTools) {
3174
+ if (typeof rawTool === 'string') {
3175
+ const parsed = parseJsonValue(rawTool);
3176
+ if (parsed !== null) {
3177
+ parsedTools.push(parsed);
3178
+ }
3179
+ continue;
3180
+ }
3181
+ if (rawTool && typeof rawTool === 'object') {
3182
+ parsedTools.push(rawTool);
3183
+ }
3184
+ }
3185
+ return parsedTools.length > 0 ? parsedTools : null;
3186
+ }
3187
+ function extractProviderMetadata(attributes) {
3188
+ const rawProviderMetadata = attributes['ai.response.providerMetadata'];
3189
+ return parseJsonValue(rawProviderMetadata) || {};
3190
+ }
3191
+ function getAiSdkFrameworkVersion(span) {
3192
+ const instrumentedSpan = span;
3193
+ const attributes = span.attributes || {};
3194
+ const instrumentationScopeVersion = toStringValue(instrumentedSpan.instrumentationScope?.version) || toStringValue(instrumentedSpan.instrumentationLibrary?.version);
3195
+ const aiUserAgent = toStringValue(attributes['ai.request.headers.user-agent']);
3196
+ const userAgentVersionMatch = aiUserAgent?.match(/\bai\/(\d+(?:\.\d+)*)\b/i);
3197
+ const userAgentVersion = userAgentVersionMatch?.[1];
3198
+ const rawVersion = instrumentationScopeVersion || userAgentVersion;
3199
+ if (!rawVersion) {
3200
+ return undefined;
3201
+ }
3202
+ const majorVersionMatch = rawVersion.match(/^v?(\d+)/i);
3203
+ return majorVersionMatch ? majorVersionMatch[1] : rawVersion;
3204
+ }
3205
+ function buildPosthogProperties(attributes, operationId) {
3206
+ const telemetryMetadata = extractAiSdkTelemetryMetadata(attributes);
3207
+ const finishReasons = toStringArray(parseJsonValue(attributes['gen_ai.response.finish_reasons']));
3208
+ const finishReason = toStringValue(attributes['ai.response.finishReason']) || finishReasons[0];
3209
+ const toolChoice = parseJsonValue(attributes['ai.prompt.toolChoice']) ?? attributes['ai.prompt.toolChoice'];
3210
+ return {
3211
+ ...telemetryMetadata,
3212
+ $ai_framework: 'vercel',
3213
+ ai_operation_id: operationId,
3214
+ ...(finishReason ? {
3215
+ ai_finish_reason: finishReason
3216
+ } : {}),
3217
+ ...(toStringValue(attributes['ai.response.model']) ? {
3218
+ ai_response_model: attributes['ai.response.model']
3219
+ } : {}),
3220
+ ...(toStringValue(attributes['gen_ai.response.model']) ? {
3221
+ ai_response_model: attributes['gen_ai.response.model']
3222
+ } : {}),
3223
+ ...(toStringValue(attributes['ai.response.id']) ? {
3224
+ ai_response_id: attributes['ai.response.id']
3225
+ } : {}),
3226
+ ...(toStringValue(attributes['gen_ai.response.id']) ? {
3227
+ ai_response_id: attributes['gen_ai.response.id']
3228
+ } : {}),
3229
+ ...(toStringValue(attributes['ai.response.timestamp']) ? {
3230
+ ai_response_timestamp: attributes['ai.response.timestamp']
3231
+ } : {}),
3232
+ ...(toNumber(attributes['ai.response.msToFinish']) !== undefined ? {
3233
+ ai_response_ms_to_finish: toNumber(attributes['ai.response.msToFinish'])
3234
+ } : {}),
3235
+ ...(toNumber(attributes['ai.response.avgCompletionTokensPerSecond']) !== undefined ? {
3236
+ ai_response_avg_completion_tokens_per_second: toNumber(attributes['ai.response.avgCompletionTokensPerSecond'])
3237
+ } : {}),
3238
+ ...(toStringValue(attributes['ai.telemetry.functionId']) ? {
3239
+ ai_telemetry_function_id: attributes['ai.telemetry.functionId']
3240
+ } : {}),
3241
+ ...(toNumber(attributes['ai.settings.maxRetries']) !== undefined ? {
3242
+ ai_settings_max_retries: toNumber(attributes['ai.settings.maxRetries'])
3243
+ } : {}),
3244
+ ...(toNumber(attributes['gen_ai.request.top_k']) !== undefined ? {
3245
+ ai_request_top_k: toNumber(attributes['gen_ai.request.top_k'])
3246
+ } : {}),
3247
+ ...(attributes['ai.schema.name'] !== undefined ? {
3248
+ ai_schema_name: attributes['ai.schema.name']
3249
+ } : {}),
3250
+ ...(attributes['ai.schema.description'] !== undefined ? {
3251
+ ai_schema_description: attributes['ai.schema.description']
3252
+ } : {}),
3253
+ ...(attributes['ai.settings.output'] !== undefined ? {
3254
+ ai_settings_output: attributes['ai.settings.output']
3255
+ } : {}),
3256
+ ...(toolChoice ? {
3257
+ ai_prompt_tool_choice: toolChoice
3258
+ } : {})
3259
+ };
3260
+ }
3261
+ function buildAiSdkMapperResult(span) {
3262
+ const attributes = span.attributes || {};
3263
+ const operationId = getOperationId(span);
3264
+ const providerMetadata = extractProviderMetadata(attributes);
3265
+ const model = toStringValue(attributes['ai.model.id']) || toStringValue(attributes['gen_ai.request.model']) || 'unknown';
3266
+ const provider = (toStringValue(attributes['ai.model.provider']) || toStringValue(attributes['gen_ai.system']) || 'unknown').toLowerCase();
3267
+ const latency = getSpanLatencySeconds(span);
3268
+ const timeToFirstTokenMs = toNumber(attributes['ai.response.msToFirstChunk']);
3269
+ const timeToFirstToken = timeToFirstTokenMs !== undefined ? timeToFirstTokenMs / 1000 : undefined;
3270
+ const input = mapPromptInput(attributes, operationId);
3271
+ const output = mapOutput(attributes, operationId, providerMetadata);
3272
+ const usage = mapUsage(attributes, providerMetadata, operationId);
3273
+ const modelParams = mapModelSettings(attributes, operationId);
3274
+ const tools = parsePromptTools(attributes);
3275
+ const httpStatus = toNumber(attributes['http.response.status_code']) || 200;
3276
+ const eventType = isDoEmbedSpan(operationId) ? AIEvent.Embedding : AIEvent.Generation;
3277
+ const frameworkVersion = getAiSdkFrameworkVersion(span);
3278
+ const error = span.status?.code === OTEL_STATUS_ERROR ? span.status.message || 'AI SDK span recorded error status' : undefined;
3279
+ return {
3280
+ model,
3281
+ provider,
3282
+ input,
3283
+ output,
3284
+ latency,
3285
+ timeToFirstToken,
3286
+ httpStatus,
3287
+ eventType,
3288
+ usage,
3289
+ tools,
3290
+ modelParams,
3291
+ posthogProperties: {
3292
+ ...buildPosthogProperties(attributes, operationId),
3293
+ ...(frameworkVersion ? {
3294
+ $ai_framework_version: frameworkVersion
3295
+ } : {})
3296
+ },
3297
+ error
3298
+ };
3299
+ }
3300
+ const aiSdkSpanMapper = {
3301
+ name: 'ai-sdk',
3302
+ canMap: shouldMapAiSdkSpan,
3303
+ map: span => {
3304
+ return buildAiSdkMapperResult(span);
3305
+ }
3306
+ };
3307
+
3308
+ const defaultSpanMappers = [aiSdkSpanMapper];
3309
+
3310
+ function pickMapper(span, mappers) {
3311
+ return mappers.find(mapper => {
3312
+ try {
3313
+ return mapper.canMap(span);
3314
+ } catch {
3315
+ return false;
3316
+ }
3317
+ });
3318
+ }
3319
+ function getTraceId(span, options, mapperTraceId) {
3320
+ if (mapperTraceId) {
3321
+ return mapperTraceId;
3322
+ }
3323
+ if (options.posthogTraceId) {
3324
+ return options.posthogTraceId;
3325
+ }
3326
+ const spanTraceId = span.spanContext?.().traceId;
3327
+ return spanTraceId || v4();
3328
+ }
3329
+ function buildPosthogParams(options, traceId, distinctId, modelParams, posthogProperties) {
3330
+ return {
3331
+ ...modelParams,
3332
+ posthogDistinctId: distinctId,
3333
+ posthogTraceId: traceId,
3334
+ posthogProperties,
3335
+ posthogPrivacyMode: options.posthogPrivacyMode,
3336
+ posthogGroups: options.posthogGroups,
3337
+ posthogModelOverride: options.posthogModelOverride,
3338
+ posthogProviderOverride: options.posthogProviderOverride,
3339
+ posthogCostOverride: options.posthogCostOverride,
3340
+ posthogCaptureImmediate: options.posthogCaptureImmediate
3341
+ };
3342
+ }
3343
+ async function captureSpan(span, phClient, options = {}) {
3344
+ if (options.shouldExportSpan && options.shouldExportSpan({
3345
+ otelSpan: span
3346
+ }) === false) {
3347
+ return;
3348
+ }
3349
+ const mappers = options.mappers ?? defaultSpanMappers;
3350
+ const mapper = pickMapper(span, mappers);
3351
+ if (!mapper) {
3352
+ return;
3353
+ }
3354
+ const mapped = mapper.map(span, {
3355
+ options
3356
+ });
3357
+ if (!mapped) {
3358
+ return;
3359
+ }
3360
+ const traceId = getTraceId(span, options, mapped.traceId);
3361
+ const distinctId = mapped.distinctId ?? options.posthogDistinctId;
3362
+ const posthogProperties = {
3363
+ ...options.posthogProperties,
3364
+ ...mapped.posthogProperties
3365
+ };
3366
+ const params = buildPosthogParams(options, traceId, distinctId, mapped.modelParams ?? {}, posthogProperties);
3367
+ const baseURL = mapped.baseURL ?? '';
3368
+ const usage = mapped.usage ?? {};
3369
+ if (mapped.error !== undefined) {
3370
+ await sendEventWithErrorToPosthog({
3371
+ eventType: mapped.eventType,
3372
+ client: phClient,
3373
+ distinctId,
3374
+ traceId,
3375
+ model: mapped.model,
3376
+ provider: mapped.provider,
3377
+ input: mapped.input,
3378
+ output: mapped.output,
3379
+ latency: mapped.latency,
3380
+ baseURL,
3381
+ params: params,
3382
+ usage,
3383
+ tools: mapped.tools,
3384
+ error: mapped.error,
3385
+ captureImmediate: options.posthogCaptureImmediate
3386
+ });
3387
+ return;
3388
+ }
3389
+ await sendEventToPosthog({
3390
+ eventType: mapped.eventType,
3391
+ client: phClient,
3392
+ distinctId,
3393
+ traceId,
3394
+ model: mapped.model,
3395
+ provider: mapped.provider,
3396
+ input: mapped.input,
3397
+ output: mapped.output,
3398
+ latency: mapped.latency,
3399
+ timeToFirstToken: mapped.timeToFirstToken,
3400
+ baseURL,
3401
+ params: params,
3402
+ httpStatus: mapped.httpStatus ?? 200,
3403
+ usage,
3404
+ tools: mapped.tools,
3405
+ captureImmediate: options.posthogCaptureImmediate
3406
+ });
3407
+ }
3408
+
3409
+ class PostHogSpanProcessor {
3410
+ constructor(phClient, options = {}) {
3411
+ this.phClient = phClient;
3412
+ this.options = options;
3413
+ this.pendingCaptures = new Set();
3414
+ }
3415
+ onStart(_span, _parentContext) {
3416
+ // no-op
3417
+ }
3418
+ onEnd(span) {
3419
+ const capturePromise = captureSpan(span, this.phClient, this.options).catch(error => {
3420
+ console.error('Failed to capture telemetry span', error);
3421
+ }).finally(() => {
3422
+ this.pendingCaptures.delete(capturePromise);
3423
+ });
3424
+ this.pendingCaptures.add(capturePromise);
3425
+ }
3426
+ async shutdown() {
3427
+ await this.forceFlush();
3428
+ }
3429
+ async forceFlush() {
3430
+ while (this.pendingCaptures.size > 0) {
3431
+ await Promise.allSettled([...this.pendingCaptures]);
3432
+ }
3433
+ }
3434
+ }
3435
+ function createPostHogSpanProcessor(phClient, options = {}) {
3436
+ return new PostHogSpanProcessor(phClient, options);
3437
+ }
3438
+
2596
3439
  class PostHogAnthropic extends AnthropicOriginal {
2597
3440
  constructor(config) {
2598
3441
  const {
@@ -4516,5 +5359,5 @@ class Prompts {
4516
5359
  }
4517
5360
  }
4518
5361
 
4519
- export { PostHogAnthropic as Anthropic, PostHogAzureOpenAI as AzureOpenAI, PostHogGoogleGenAI as GoogleGenAI, LangChainCallbackHandler, PostHogOpenAI as OpenAI, Prompts, wrapVercelLanguageModel as withTracing };
5362
+ export { PostHogAnthropic as Anthropic, PostHogAzureOpenAI as AzureOpenAI, PostHogGoogleGenAI as GoogleGenAI, LangChainCallbackHandler, PostHogOpenAI as OpenAI, PostHogSpanProcessor, Prompts, captureSpan, createPostHogSpanProcessor, wrapVercelLanguageModel as withTracing };
4520
5363
  //# sourceMappingURL=index.mjs.map