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