@posthog/ai 8.9.3 → 8.10.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/dist/adk/index.cjs +977 -0
  2. package/dist/adk/index.cjs.map +1 -0
  3. package/dist/adk/index.d.ts +149 -0
  4. package/dist/adk/index.mjs +976 -0
  5. package/dist/adk/index.mjs.map +1 -0
  6. package/dist/anthropic/index.cjs +927 -1104
  7. package/dist/anthropic/index.cjs.map +1 -1
  8. package/dist/anthropic/index.d.ts +34 -33
  9. package/dist/anthropic/index.mjs +899 -1095
  10. package/dist/anthropic/index.mjs.map +1 -1
  11. package/dist/gemini/index.cjs +867 -1112
  12. package/dist/gemini/index.cjs.map +1 -1
  13. package/dist/gemini/index.d.ts +38 -35
  14. package/dist/gemini/index.mjs +862 -1107
  15. package/dist/gemini/index.mjs.map +1 -1
  16. package/dist/index.cjs +1218 -1539
  17. package/dist/index.cjs.map +1 -1
  18. package/dist/index.d.ts +170 -157
  19. package/dist/index.mjs +1216 -1537
  20. package/dist/index.mjs.map +1 -1
  21. package/dist/langchain/index.cjs +851 -1029
  22. package/dist/langchain/index.cjs.map +1 -1
  23. package/dist/langchain/index.d.ts +75 -75
  24. package/dist/langchain/index.mjs +850 -1027
  25. package/dist/langchain/index.mjs.map +1 -1
  26. package/dist/langchain/middleware/index.cjs +1016 -1225
  27. package/dist/langchain/middleware/index.cjs.map +1 -1
  28. package/dist/langchain/middleware/index.d.ts +29 -25
  29. package/dist/langchain/middleware/index.mjs +1015 -1223
  30. package/dist/langchain/middleware/index.mjs.map +1 -1
  31. package/dist/openai/index.cjs +1990 -2516
  32. package/dist/openai/index.cjs.map +1 -1
  33. package/dist/openai/index.d.ts +106 -104
  34. package/dist/openai/index.mjs +1985 -2511
  35. package/dist/openai/index.mjs.map +1 -1
  36. package/dist/openai-agents/index.cjs +745 -827
  37. package/dist/openai-agents/index.cjs.map +1 -1
  38. package/dist/openai-agents/index.d.ts +48 -47
  39. package/dist/openai-agents/index.mjs +744 -825
  40. package/dist/openai-agents/index.mjs.map +1 -1
  41. package/dist/otel/index.cjs +427 -486
  42. package/dist/otel/index.cjs.map +1 -1
  43. package/dist/otel/index.d.ts +36 -35
  44. package/dist/otel/index.mjs +426 -484
  45. package/dist/otel/index.mjs.map +1 -1
  46. package/dist/vercel/index.cjs +992 -1336
  47. package/dist/vercel/index.cjs.map +1 -1
  48. package/dist/vercel/index.d.ts +21 -16
  49. package/dist/vercel/index.mjs +991 -1334
  50. package/dist/vercel/index.mjs.map +1 -1
  51. package/package.json +23 -12
@@ -1,1425 +1,1081 @@
1
- 'use strict';
2
-
3
- var uuid = require('uuid');
4
- var core = require('@posthog/core');
5
-
6
- // Type guards for safer type checking
7
-
8
- const isString = value => {
9
- return typeof value === 'string';
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ let uuid = require("uuid");
3
+ let _posthog_core = require("@posthog/core");
4
+ //#region src/typeGuards.ts
5
+ const isString = (value) => {
6
+ return typeof value === "string";
10
7
  };
11
- const isObject = value => {
12
- return value !== null && typeof value === 'object' && !Array.isArray(value);
8
+ const isObject = (value) => {
9
+ return value !== null && typeof value === "object" && !Array.isArray(value);
13
10
  };
14
-
15
- /** @internal */
16
-
17
- /** @internal */
18
-
11
+ //#endregion
12
+ //#region src/captureAiEvent.ts
19
13
  /** @internal */
20
14
  function isFullAiCaptureEnabled(client) {
21
- return client?.enableFullAiCapture === true;
15
+ return client?.enableFullAiCapture === true;
22
16
  }
23
-
24
17
  /** @internal */
25
18
  function captureAiEvent(client, event) {
26
- if (isFullAiCaptureEnabled(client) && typeof client.captureAi === 'function') {
27
- client.captureAi(event);
28
- return;
29
- }
30
- client.capture(event);
19
+ if (isFullAiCaptureEnabled(client) && typeof client.captureAi === "function") {
20
+ client.captureAi(event);
21
+ return;
22
+ }
23
+ client.capture(event);
31
24
  }
32
-
33
25
  /** @internal */
34
26
  async function captureAiEventImmediate(client, event) {
35
- if (isFullAiCaptureEnabled(client) && typeof client.captureAiImmediate === 'function') {
36
- await client.captureAiImmediate(event);
37
- return;
38
- }
39
- await client.captureImmediate(event);
27
+ if (isFullAiCaptureEnabled(client) && typeof client.captureAiImmediate === "function") {
28
+ await client.captureAiImmediate(event);
29
+ return;
30
+ }
31
+ await client.captureImmediate(event);
40
32
  }
41
-
33
+ //#endregion
34
+ //#region src/sanitization/base64_recognizer.ts
42
35
  const DATA_URL_PREFIX_RE = /^data:([^;,\s]+)(?:;[^;,\s]+)*;base64,/i;
43
36
  const BASE64_ALPHABET_RE = /^[A-Za-z0-9+/_=-]+$/;
44
- class Base64Recognizer {
45
- recognize(value, minLength) {
46
- const dataUrl = DATA_URL_PREFIX_RE.exec(value);
47
- if (dataUrl) return {
48
- kind: 'data-url',
49
- mediaType: dataUrl[1]
50
- };
51
- if (value.length < minLength) return {
52
- kind: 'none'
53
- };
54
- const confidencePrefix = value.slice(0, minLength);
55
- if (BASE64_ALPHABET_RE.test(confidencePrefix)) {
56
- return {
57
- kind: 'raw'
58
- };
59
- } else {
60
- return {
61
- kind: 'none'
62
- };
63
- }
64
- }
65
- }
66
-
67
- const MIME_HINT_KEYS = ['mediaType', 'media_type', 'mimeType', 'mime_type'];
68
- const STRONG_CONTEXT_KEYS = new Set(['data', 'file_data', 'fileData', 'image_url', 'imageUrl', 'video_url', 'videoUrl', 'audio', 'audio_data', 'audioData', 'inline_data', 'inlineData', 'source', 'result']);
69
- const STRONG_CONTEXT_TYPES = new Set(['image', 'image_url', 'input_image', 'audio', 'input_audio', 'video', 'video_url', 'file', 'input_file', 'document', 'media', 'file-data']);
70
- const FILE_FAMILY_TYPES = new Set(['file', 'input_file', 'document', 'media', 'file-data']);
71
- const KNOWN_AUDIO_FORMATS = new Set(['wav', 'mp3', 'ogg', 'flac', 'm4a', 'aac', 'webm']);
72
- class MediaTypeContext {
73
- static EMPTY = new MediaTypeContext(undefined, undefined);
74
- constructor(parent, key, explicitMediaType) {
75
- this.parent = parent;
76
- this.key = key;
77
- this.explicitMediaType = explicitMediaType;
78
- }
79
- inferMediaType() {
80
- return this.inferFromSiblingMime() ?? this.inferFromSiblingFormat() ?? this.inferFromParentType() ?? this.inferFromKey();
81
- }
82
- inferFromSiblingMime() {
83
- if (this.explicitMediaType) return this.explicitMediaType;
84
- if (!this.parent) return undefined;
85
- for (const hint of MIME_HINT_KEYS) {
86
- const v = this.parent[hint];
87
- if (typeof v === 'string') return v;
88
- }
89
- return undefined;
90
- }
91
- inferFromSiblingFormat() {
92
- if (!this.parent) return undefined;
93
- const fmt = this.parent.format;
94
- if (typeof fmt === 'string' && KNOWN_AUDIO_FORMATS.has(fmt.toLowerCase())) {
95
- return `audio/${fmt.toLowerCase()}`;
96
- }
97
- return undefined;
98
- }
99
- inferFromParentType() {
100
- if (!this.parent) return undefined;
101
- const t = this.parent.type;
102
- if (typeof t !== 'string') return undefined;
103
- if (t === 'image' || t === 'image_url' || t === 'input_image') return 'image';
104
- if (t === 'audio' || t === 'input_audio') return 'audio';
105
- if (t === 'video' || t === 'video_url') return 'video';
106
- if (FILE_FAMILY_TYPES.has(t)) return 'application/octet-stream';
107
- return undefined;
108
- }
109
- inferFromKey() {
110
- if (!this.key) return undefined;
111
- const key = this.key.toLowerCase();
112
- if (key.includes('audio')) return 'audio';
113
- if (key.includes('video')) return 'video';
114
- if (key.includes('image')) return 'image';
115
- if (key.includes('file') || key.includes('document')) return 'application/octet-stream';
116
- return undefined;
117
- }
118
- hasExplicitBinaryMediaType() {
119
- if (!this.explicitMediaType && (!this.parent || !this.key || !STRONG_CONTEXT_KEYS.has(this.key))) return false;
120
- const mediaType = this.inferFromSiblingMime();
121
- return mediaType !== undefined && !mediaType.toLowerCase().startsWith('text/');
122
- }
123
- signalsBinary() {
124
- if (this.explicitMediaType) return true;
125
- if (this.parent) {
126
- for (const hint of MIME_HINT_KEYS) {
127
- if (typeof this.parent[hint] === 'string') return true;
128
- }
129
- const fmt = this.parent.format;
130
- if (typeof fmt === 'string' && KNOWN_AUDIO_FORMATS.has(fmt.toLowerCase())) return true;
131
- const t = this.parent.type;
132
- if (typeof t === 'string' && STRONG_CONTEXT_TYPES.has(t)) return true;
133
- }
134
- if (this.key && STRONG_CONTEXT_KEYS.has(this.key)) return true;
135
- return false;
136
- }
137
- }
138
-
37
+ var Base64Recognizer = class {
38
+ recognize(value, minLength) {
39
+ const dataUrl = DATA_URL_PREFIX_RE.exec(value);
40
+ if (dataUrl) return {
41
+ kind: "data-url",
42
+ mediaType: dataUrl[1]
43
+ };
44
+ if (value.length < minLength) return { kind: "none" };
45
+ const confidencePrefix = value.slice(0, minLength);
46
+ if (BASE64_ALPHABET_RE.test(confidencePrefix)) return { kind: "raw" };
47
+ else return { kind: "none" };
48
+ }
49
+ };
50
+ //#endregion
51
+ //#region src/sanitization/media_type_context.ts
52
+ const MIME_HINT_KEYS = [
53
+ "mediaType",
54
+ "media_type",
55
+ "mimeType",
56
+ "mime_type"
57
+ ];
58
+ const STRONG_CONTEXT_KEYS = /* @__PURE__ */ new Set([
59
+ "data",
60
+ "file_data",
61
+ "fileData",
62
+ "image_url",
63
+ "imageUrl",
64
+ "video_url",
65
+ "videoUrl",
66
+ "audio",
67
+ "audio_data",
68
+ "audioData",
69
+ "inline_data",
70
+ "inlineData",
71
+ "source",
72
+ "result"
73
+ ]);
74
+ const STRONG_CONTEXT_TYPES = /* @__PURE__ */ new Set([
75
+ "image",
76
+ "image_url",
77
+ "input_image",
78
+ "audio",
79
+ "input_audio",
80
+ "video",
81
+ "video_url",
82
+ "file",
83
+ "input_file",
84
+ "document",
85
+ "media",
86
+ "file-data"
87
+ ]);
88
+ const FILE_FAMILY_TYPES = /* @__PURE__ */ new Set([
89
+ "file",
90
+ "input_file",
91
+ "document",
92
+ "media",
93
+ "file-data"
94
+ ]);
95
+ const KNOWN_AUDIO_FORMATS = /* @__PURE__ */ new Set([
96
+ "wav",
97
+ "mp3",
98
+ "ogg",
99
+ "flac",
100
+ "m4a",
101
+ "aac",
102
+ "webm"
103
+ ]);
104
+ var MediaTypeContext = class MediaTypeContext {
105
+ static {
106
+ this.EMPTY = new MediaTypeContext(void 0, void 0);
107
+ }
108
+ constructor(parent, key, explicitMediaType) {
109
+ this.parent = parent;
110
+ this.key = key;
111
+ this.explicitMediaType = explicitMediaType;
112
+ }
113
+ inferMediaType() {
114
+ return this.inferFromSiblingMime() ?? this.inferFromSiblingFormat() ?? this.inferFromParentType() ?? this.inferFromKey();
115
+ }
116
+ inferFromSiblingMime() {
117
+ if (this.explicitMediaType) return this.explicitMediaType;
118
+ if (!this.parent) return void 0;
119
+ for (const hint of MIME_HINT_KEYS) {
120
+ const v = this.parent[hint];
121
+ if (typeof v === "string") return v;
122
+ }
123
+ }
124
+ inferFromSiblingFormat() {
125
+ if (!this.parent) return void 0;
126
+ const fmt = this.parent.format;
127
+ if (typeof fmt === "string" && KNOWN_AUDIO_FORMATS.has(fmt.toLowerCase())) return `audio/${fmt.toLowerCase()}`;
128
+ }
129
+ inferFromParentType() {
130
+ if (!this.parent) return void 0;
131
+ const t = this.parent.type;
132
+ if (typeof t !== "string") return void 0;
133
+ if (t === "image" || t === "image_url" || t === "input_image") return "image";
134
+ if (t === "audio" || t === "input_audio") return "audio";
135
+ if (t === "video" || t === "video_url") return "video";
136
+ if (FILE_FAMILY_TYPES.has(t)) return "application/octet-stream";
137
+ }
138
+ inferFromKey() {
139
+ if (!this.key) return void 0;
140
+ const key = this.key.toLowerCase();
141
+ if (key.includes("audio")) return "audio";
142
+ if (key.includes("video")) return "video";
143
+ if (key.includes("image")) return "image";
144
+ if (key.includes("file") || key.includes("document")) return "application/octet-stream";
145
+ }
146
+ hasExplicitBinaryMediaType() {
147
+ if (!this.explicitMediaType && (!this.parent || !this.key || !STRONG_CONTEXT_KEYS.has(this.key))) return false;
148
+ const mediaType = this.inferFromSiblingMime();
149
+ return mediaType !== void 0 && !mediaType.toLowerCase().startsWith("text/");
150
+ }
151
+ signalsBinary() {
152
+ if (this.explicitMediaType) return true;
153
+ if (this.parent) {
154
+ for (const hint of MIME_HINT_KEYS) if (typeof this.parent[hint] === "string") return true;
155
+ const fmt = this.parent.format;
156
+ if (typeof fmt === "string" && KNOWN_AUDIO_FORMATS.has(fmt.toLowerCase())) return true;
157
+ const t = this.parent.type;
158
+ if (typeof t === "string" && STRONG_CONTEXT_TYPES.has(t)) return true;
159
+ }
160
+ if (this.key && STRONG_CONTEXT_KEYS.has(this.key)) return true;
161
+ return false;
162
+ }
163
+ };
164
+ //#endregion
165
+ //#region src/sanitization/binary_content_redactor.ts
139
166
  const STRONG_CONTEXT_MIN_LENGTH = 64;
140
167
  const WEAK_CONTEXT_MIN_LENGTH = 1024;
141
- class BinaryContentRedactor {
142
- visited = new WeakSet();
143
- constructor(recognizer = new Base64Recognizer()) {
144
- this.recognizer = recognizer;
145
- }
146
- redact(value, mediaType) {
147
- this.visited = new WeakSet();
148
- return this.walk(value, mediaType ? new MediaTypeContext(undefined, undefined, mediaType) : MediaTypeContext.EMPTY);
149
- }
150
- walk(value, ctx) {
151
- if (value === null || value === undefined) return value;
152
- if (typeof value === 'string') return this.redactString(value, ctx);
153
- if (typeof value !== 'object') return value;
154
-
155
- // Buffer extends Uint8Array, so this branch catches both.
156
- if (typeof Uint8Array !== 'undefined' && value instanceof Uint8Array) {
157
- return this.placeholderFor(ctx.inferMediaType());
158
- }
159
- if (this.visited.has(value)) return null;
160
- this.visited.add(value);
161
- if (Array.isArray(value)) {
162
- return value.map(item => this.walk(item, ctx));
163
- }
164
- const obj = value;
165
- const out = {};
166
- for (const k of Object.keys(obj)) {
167
- out[k] = this.walk(obj[k], new MediaTypeContext(obj, k));
168
- }
169
- return out;
170
- }
171
- redactString(value, ctx) {
172
- const hasExplicitBinaryMediaType = ctx.hasExplicitBinaryMediaType();
173
- const recognitionValue = hasExplicitBinaryMediaType ? value.replace(/[\r\n]/g, '') : value;
174
- const minLength = hasExplicitBinaryMediaType ? Math.min(recognitionValue.length, STRONG_CONTEXT_MIN_LENGTH) : ctx.signalsBinary() ? STRONG_CONTEXT_MIN_LENGTH : WEAK_CONTEXT_MIN_LENGTH;
175
- const recognition = this.recognizer.recognize(recognitionValue, minLength);
176
- switch (recognition.kind) {
177
- case 'data-url':
178
- return this.placeholderFor(recognition.mediaType);
179
- case 'raw':
180
- return this.placeholderFor(ctx.inferMediaType());
181
- case 'none':
182
- return value;
183
- }
184
- }
185
- placeholderFor(mediaType) {
186
- if (!mediaType) return '[base64 redacted]';
187
- if (mediaType === 'application/octet-stream') return '[base64 file redacted]';
188
- return `[base64 ${mediaType} redacted]`;
189
- }
190
- }
191
-
168
+ var BinaryContentRedactor = class {
169
+ constructor(recognizer = new Base64Recognizer()) {
170
+ this.recognizer = recognizer;
171
+ this.visited = /* @__PURE__ */ new WeakSet();
172
+ }
173
+ redact(value, mediaType) {
174
+ this.visited = /* @__PURE__ */ new WeakSet();
175
+ return this.walk(value, mediaType ? new MediaTypeContext(void 0, void 0, mediaType) : MediaTypeContext.EMPTY);
176
+ }
177
+ walk(value, ctx) {
178
+ if (value === null || value === void 0) return value;
179
+ if (typeof value === "string") return this.redactString(value, ctx);
180
+ if (typeof value !== "object") return value;
181
+ if (typeof Uint8Array !== "undefined" && value instanceof Uint8Array) return this.placeholderFor(ctx.inferMediaType());
182
+ if (this.visited.has(value)) return null;
183
+ this.visited.add(value);
184
+ if (Array.isArray(value)) return value.map((item) => this.walk(item, ctx));
185
+ const obj = value;
186
+ const out = {};
187
+ for (const k of Object.keys(obj)) out[k] = this.walk(obj[k], new MediaTypeContext(obj, k));
188
+ return out;
189
+ }
190
+ redactString(value, ctx) {
191
+ const hasExplicitBinaryMediaType = ctx.hasExplicitBinaryMediaType();
192
+ const recognitionValue = hasExplicitBinaryMediaType ? value.replace(/[\r\n]/g, "") : value;
193
+ const minLength = hasExplicitBinaryMediaType ? Math.min(recognitionValue.length, STRONG_CONTEXT_MIN_LENGTH) : ctx.signalsBinary() ? STRONG_CONTEXT_MIN_LENGTH : WEAK_CONTEXT_MIN_LENGTH;
194
+ const recognition = this.recognizer.recognize(recognitionValue, minLength);
195
+ switch (recognition.kind) {
196
+ case "data-url": return this.placeholderFor(recognition.mediaType);
197
+ case "raw": return this.placeholderFor(ctx.inferMediaType());
198
+ case "none": return value;
199
+ }
200
+ }
201
+ placeholderFor(mediaType) {
202
+ if (!mediaType) return "[base64 redacted]";
203
+ if (mediaType === "application/octet-stream") return "[base64 file redacted]";
204
+ return `[base64 ${mediaType} redacted]`;
205
+ }
206
+ };
207
+ //#endregion
208
+ //#region src/sanitization.ts
192
209
  const redactor = new BinaryContentRedactor();
193
210
  function redactBase64DataUrl(str, mediaType) {
194
- return redactor.redact(str, mediaType);
211
+ return redactor.redact(str, mediaType);
195
212
  }
196
213
  const sanitize = (data, client) => isFullAiCaptureEnabled(client) ? data : redactor.redact(data);
197
214
  const sanitizeVercel = (data, client) => sanitize(data, client);
198
-
199
- 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']);
200
-
215
+ //#endregion
216
+ //#region src/utils.ts
217
+ const TOKEN_PROPERTY_KEYS = /* @__PURE__ */ new Set([
218
+ "$ai_input_tokens",
219
+ "$ai_output_tokens",
220
+ "$ai_cache_read_input_tokens",
221
+ "$ai_cache_creation_input_tokens",
222
+ "$ai_total_tokens",
223
+ "$ai_reasoning_tokens"
224
+ ]);
201
225
  /**
202
- * Whether the caller supplied their own token counts, which override the ones the SDK
203
- * derived from the provider response.
204
- */
226
+ * Whether the caller supplied their own token counts, which override the ones the SDK
227
+ * derived from the provider response.
228
+ */
205
229
  function hasTokenOverrides(posthogProperties) {
206
- return !!posthogProperties && Object.keys(posthogProperties).some(key => TOKEN_PROPERTY_KEYS.has(key));
230
+ return !!posthogProperties && Object.keys(posthogProperties).some((key) => TOKEN_PROPERTY_KEYS.has(key));
207
231
  }
208
232
  function getTokensSource(posthogProperties) {
209
- return hasTokenOverrides(posthogProperties) ? 'passthrough' : 'sdk';
233
+ return hasTokenOverrides(posthogProperties) ? "passthrough" : "sdk";
210
234
  }
211
-
212
- // limit large outputs by truncating to 200kb (approx 200k bytes)
213
- const MAX_OUTPUT_SIZE = 200000;
214
- const STRING_FORMAT = 'utf8';
215
-
216
- // Reused across calls to avoid per-invocation allocation; truncate() runs
217
- // hundreds of times for prompts with many parts.
235
+ const MAX_OUTPUT_SIZE = 2e5;
236
+ const STRING_FORMAT = "utf8";
218
237
  const sharedTextEncoder = new TextEncoder();
219
- const sharedTextDecoder = new TextDecoder(STRING_FORMAT, {
220
- fatal: false
221
- });
222
- const utf8ByteLength = str => sharedTextEncoder.encode(str).byteLength;
223
-
238
+ const sharedTextDecoder = new TextDecoder(STRING_FORMAT, { fatal: false });
239
+ const utf8ByteLength = (str) => sharedTextEncoder.encode(str).byteLength;
224
240
  /**
225
- * Safely converts content to a string, preserving structure for objects/arrays.
226
- * - If content is already a string, returns it as-is
227
- * - If content is an object or array, stringifies it with JSON.stringify to preserve structure
228
- * - Otherwise, converts to string with String()
229
- *
230
- * This prevents the "[object Object]" bug when objects are naively converted to strings.
231
- *
232
- * @param content - The content to convert to a string
233
- * @returns A string representation that preserves structure for complex types
234
- */
241
+ * Safely converts content to a string, preserving structure for objects/arrays.
242
+ * - If content is already a string, returns it as-is
243
+ * - If content is an object or array, stringifies it with JSON.stringify to preserve structure
244
+ * - Otherwise, converts to string with String()
245
+ *
246
+ * This prevents the "[object Object]" bug when objects are naively converted to strings.
247
+ *
248
+ * @param content - The content to convert to a string
249
+ * @returns A string representation that preserves structure for complex types
250
+ */
235
251
  function toContentString(content) {
236
- if (typeof content === 'string') {
237
- return content;
238
- }
239
- if (content !== undefined && content !== null && typeof content === 'object') {
240
- try {
241
- return JSON.stringify(content);
242
- } catch {
243
- // Fallback for circular refs, BigInt, or objects with throwing toJSON
244
- return String(content);
245
- }
246
- }
247
- return String(content);
252
+ if (typeof content === "string") return content;
253
+ if (content !== void 0 && content !== null && typeof content === "object") try {
254
+ return JSON.stringify(content);
255
+ } catch {
256
+ return String(content);
257
+ }
258
+ return String(content);
248
259
  }
249
260
  const getModelParams = (params, responseServiceTier) => {
250
- if (!params) {
251
- return {};
252
- }
253
- const modelParams = {};
254
- const paramKeys = ['temperature', 'max_tokens', 'max_completion_tokens', 'top_p', 'frequency_penalty', 'presence_penalty', 'n', 'stop', 'stream', 'streaming', 'language', 'response_format', 'timestamp_granularities', 'service_tier'];
255
- for (const key of paramKeys) {
256
- if (key in params && params[key] !== undefined) {
257
- modelParams[key] = params[key];
258
- }
259
- }
260
- return modelParams;
261
+ if (!params) return {};
262
+ const modelParams = {};
263
+ for (const key of [
264
+ "temperature",
265
+ "max_tokens",
266
+ "max_completion_tokens",
267
+ "top_p",
268
+ "frequency_penalty",
269
+ "presence_penalty",
270
+ "n",
271
+ "stop",
272
+ "stream",
273
+ "streaming",
274
+ "language",
275
+ "response_format",
276
+ "timestamp_granularities",
277
+ "service_tier"
278
+ ]) if (key in params && params[key] !== void 0) modelParams[key] = params[key];
279
+ if (responseServiceTier != null) modelParams.service_tier = responseServiceTier;
280
+ return modelParams;
261
281
  };
262
282
  const withPrivacyMode = (client, privacyMode, input) => {
263
- return client.privacy_mode || privacyMode ? null : input;
283
+ return client.privacy_mode || privacyMode ? null : input;
264
284
  };
265
285
  function toSafeString(input) {
266
- if (input === undefined || input === null) {
267
- return '';
268
- }
269
- if (typeof input === 'string') {
270
- return input;
271
- }
272
- try {
273
- return JSON.stringify(input);
274
- } catch {
275
- console.warn('Failed to stringify input', input);
276
- return '';
277
- }
286
+ if (input === void 0 || input === null) return "";
287
+ if (typeof input === "string") return input;
288
+ try {
289
+ return JSON.stringify(input);
290
+ } catch {
291
+ console.warn("Failed to stringify input", input);
292
+ return "";
293
+ }
278
294
  }
279
295
  const truncate = (input, client) => {
280
- const str = toSafeString(input);
281
- if (str === '') {
282
- return '';
283
- }
284
- if (isFullAiCaptureEnabled(client)) {
285
- return str;
286
- }
287
-
288
- // Check if we need to truncate and ensure STRING_FORMAT is respected
289
- const buffer = sharedTextEncoder.encode(str);
290
- if (buffer.length <= MAX_OUTPUT_SIZE) {
291
- // Ensure STRING_FORMAT is respected
292
- return sharedTextDecoder.decode(buffer);
293
- }
294
-
295
- // Truncate the buffer and ensure a valid string is returned.
296
- // fatal: false means we get U+FFFD at the end if truncation broke the encoding.
297
- const truncatedBuffer = buffer.slice(0, MAX_OUTPUT_SIZE);
298
- let truncatedStr = sharedTextDecoder.decode(truncatedBuffer);
299
- if (truncatedStr.endsWith('\uFFFD')) {
300
- truncatedStr = truncatedStr.slice(0, -1);
301
- }
302
- return `${truncatedStr}... [truncated]`;
296
+ const str = toSafeString(input);
297
+ if (str === "") return "";
298
+ if (isFullAiCaptureEnabled(client)) return str;
299
+ const buffer = sharedTextEncoder.encode(str);
300
+ if (buffer.length <= 2e5) return sharedTextDecoder.decode(buffer);
301
+ const truncatedBuffer = buffer.slice(0, MAX_OUTPUT_SIZE);
302
+ let truncatedStr = sharedTextDecoder.decode(truncatedBuffer);
303
+ if (truncatedStr.endsWith("�")) truncatedStr = truncatedStr.slice(0, -1);
304
+ return `${truncatedStr}... [truncated]`;
303
305
  };
304
-
305
306
  /**
306
- * Calculate web search count from raw API response.
307
- *
308
- * Uses a two-tier detection strategy:
309
- * Priority 1 (Exact Count): Count actual web search calls when available
310
- * Priority 2 (Binary Detection): Return 1 if web search indicators are present, 0 otherwise
311
- *
312
- * @param result - Raw API response from any provider (OpenAI, Perplexity, OpenRouter, Gemini, etc.)
313
- * @returns Number of web searches performed (exact count or binary 1/0)
314
- */
307
+ * Calculate web search count from raw API response.
308
+ *
309
+ * Uses a two-tier detection strategy:
310
+ * Priority 1 (Exact Count): Count actual web search calls when available
311
+ * Priority 2 (Binary Detection): Return 1 if web search indicators are present, 0 otherwise
312
+ *
313
+ * @param result - Raw API response from any provider (OpenAI, Perplexity, OpenRouter, Gemini, etc.)
314
+ * @returns Number of web searches performed (exact count or binary 1/0)
315
+ */
315
316
  function calculateWebSearchCount(result) {
316
- if (!result || typeof result !== 'object') {
317
- return 0;
318
- }
319
-
320
- // Priority 1: Exact Count
321
- // Check for OpenAI Responses API web_search_call items
322
- if ('output' in result && Array.isArray(result.output)) {
323
- let count = 0;
324
- for (const item of result.output) {
325
- if (typeof item === 'object' && item !== null && 'type' in item && item.type === 'web_search_call') {
326
- count++;
327
- }
328
- }
329
- if (count > 0) {
330
- return count;
331
- }
332
- }
333
-
334
- // Priority 2: Binary Detection (1 or 0)
335
-
336
- // Check for citations at root level (Perplexity)
337
- if ('citations' in result && Array.isArray(result.citations) && result.citations.length > 0) {
338
- return 1;
339
- }
340
-
341
- // Check for search_results at root level (Perplexity via OpenRouter)
342
- if ('search_results' in result && Array.isArray(result.search_results) && result.search_results.length > 0) {
343
- return 1;
344
- }
345
-
346
- // Check for usage.search_context_size (Perplexity via OpenRouter)
347
- if ('usage' in result && typeof result.usage === 'object' && result.usage !== null) {
348
- if ('search_context_size' in result.usage && result.usage.search_context_size) {
349
- return 1;
350
- }
351
- }
352
-
353
- // Check for annotations with url_citation in choices[].message or choices[].delta (OpenAI/Perplexity)
354
- if ('choices' in result && Array.isArray(result.choices)) {
355
- for (const choice of result.choices) {
356
- if (typeof choice === 'object' && choice !== null) {
357
- // Check both message (non-streaming) and delta (streaming) for annotations
358
- const content = ('message' in choice ? choice.message : null) || ('delta' in choice ? choice.delta : null);
359
- if (typeof content === 'object' && content !== null && 'annotations' in content) {
360
- const annotations = content.annotations;
361
- if (Array.isArray(annotations)) {
362
- const hasUrlCitation = annotations.some(ann => {
363
- return typeof ann === 'object' && ann !== null && 'type' in ann && ann.type === 'url_citation';
364
- });
365
- if (hasUrlCitation) {
366
- return 1;
367
- }
368
- }
369
- }
370
- }
371
- }
372
- }
373
-
374
- // Check for annotations in output[].content[] (OpenAI Responses API)
375
- if ('output' in result && Array.isArray(result.output)) {
376
- for (const item of result.output) {
377
- if (typeof item === 'object' && item !== null && 'content' in item) {
378
- const content = item.content;
379
- if (Array.isArray(content)) {
380
- for (const contentItem of content) {
381
- if (typeof contentItem === 'object' && contentItem !== null && 'annotations' in contentItem) {
382
- const annotations = contentItem.annotations;
383
- if (Array.isArray(annotations)) {
384
- const hasUrlCitation = annotations.some(ann => {
385
- return typeof ann === 'object' && ann !== null && 'type' in ann && ann.type === 'url_citation';
386
- });
387
- if (hasUrlCitation) {
388
- return 1;
389
- }
390
- }
391
- }
392
- }
393
- }
394
- }
395
- }
396
- }
397
-
398
- // Check for grounding_metadata (Gemini)
399
- if ('candidates' in result && Array.isArray(result.candidates)) {
400
- for (const candidate of result.candidates) {
401
- if (typeof candidate === 'object' && candidate !== null && 'grounding_metadata' in candidate && candidate.grounding_metadata) {
402
- return 1;
403
- }
404
- }
405
- }
406
- return 0;
317
+ if (!result || typeof result !== "object") return 0;
318
+ if ("output" in result && Array.isArray(result.output)) {
319
+ let count = 0;
320
+ for (const item of result.output) if (typeof item === "object" && item !== null && "type" in item && item.type === "web_search_call") count++;
321
+ if (count > 0) return count;
322
+ }
323
+ if ("citations" in result && Array.isArray(result.citations) && result.citations.length > 0) return 1;
324
+ if ("search_results" in result && Array.isArray(result.search_results) && result.search_results.length > 0) return 1;
325
+ if ("usage" in result && typeof result.usage === "object" && result.usage !== null) {
326
+ if ("search_context_size" in result.usage && result.usage.search_context_size) return 1;
327
+ }
328
+ if ("choices" in result && Array.isArray(result.choices)) {
329
+ for (const choice of result.choices) if (typeof choice === "object" && choice !== null) {
330
+ const content = ("message" in choice ? choice.message : null) || ("delta" in choice ? choice.delta : null);
331
+ if (typeof content === "object" && content !== null && "annotations" in content) {
332
+ const annotations = content.annotations;
333
+ if (Array.isArray(annotations)) {
334
+ if (annotations.some((ann) => {
335
+ return typeof ann === "object" && ann !== null && "type" in ann && ann.type === "url_citation";
336
+ })) return 1;
337
+ }
338
+ }
339
+ }
340
+ }
341
+ if ("output" in result && Array.isArray(result.output)) {
342
+ for (const item of result.output) if (typeof item === "object" && item !== null && "content" in item) {
343
+ const content = item.content;
344
+ if (Array.isArray(content)) {
345
+ for (const contentItem of content) if (typeof contentItem === "object" && contentItem !== null && "annotations" in contentItem) {
346
+ const annotations = contentItem.annotations;
347
+ if (Array.isArray(annotations)) {
348
+ if (annotations.some((ann) => {
349
+ return typeof ann === "object" && ann !== null && "type" in ann && ann.type === "url_citation";
350
+ })) return 1;
351
+ }
352
+ }
353
+ }
354
+ }
355
+ }
356
+ if ("candidates" in result && Array.isArray(result.candidates)) {
357
+ for (const candidate of result.candidates) if (typeof candidate === "object" && candidate !== null && "grounding_metadata" in candidate && candidate.grounding_metadata) return 1;
358
+ }
359
+ return 0;
407
360
  }
408
-
409
361
  /**
410
- * Extract available tool calls from the request parameters.
411
- * These are the tools provided to the LLM, not the tool calls in the response.
412
- */
362
+ * Extract available tool calls from the request parameters.
363
+ * These are the tools provided to the LLM, not the tool calls in the response.
364
+ */
413
365
  const extractAvailableToolCalls = (provider, params) => {
414
- {
415
- if (params.tools) {
416
- return params.tools;
417
- }
418
- return null;
419
- }
366
+ if (provider === "anthropic") {
367
+ if (params.tools) return params.tools;
368
+ return null;
369
+ } else if (provider === "gemini") {
370
+ if (params.config && params.config.tools) return params.config.tools;
371
+ return null;
372
+ } else if (provider === "openai") {
373
+ if (params.tools) return params.tools;
374
+ return null;
375
+ } else if (provider === "vercel") {
376
+ if (params.tools) return params.tools;
377
+ return null;
378
+ }
379
+ return null;
420
380
  };
421
- let AIEvent = /*#__PURE__*/function (AIEvent) {
422
- AIEvent["Generation"] = "$ai_generation";
423
- AIEvent["Embedding"] = "$ai_embedding";
424
- return AIEvent;
425
- }({});
426
381
  function sanitizeValues(obj) {
427
- if (obj === undefined || obj === null) {
428
- return obj;
429
- }
430
- const jsonSafe = JSON.parse(JSON.stringify(obj));
431
- if (typeof jsonSafe === 'string') {
432
- // Sanitize lone surrogates by round-tripping through UTF-8
433
- return new TextDecoder().decode(new TextEncoder().encode(jsonSafe));
434
- } else if (Array.isArray(jsonSafe)) {
435
- return jsonSafe.map(sanitizeValues);
436
- } else if (jsonSafe && typeof jsonSafe === 'object') {
437
- return Object.fromEntries(Object.entries(jsonSafe).map(([k, v]) => [k, sanitizeValues(v)]));
438
- }
439
- return jsonSafe;
382
+ if (obj === void 0 || obj === null) return obj;
383
+ const jsonSafe = JSON.parse(JSON.stringify(obj));
384
+ if (typeof jsonSafe === "string") return new TextDecoder().decode(new TextEncoder().encode(jsonSafe));
385
+ else if (Array.isArray(jsonSafe)) return jsonSafe.map(sanitizeValues);
386
+ else if (jsonSafe && typeof jsonSafe === "object") return Object.fromEntries(Object.entries(jsonSafe).map(([k, v]) => [k, sanitizeValues(v)]));
387
+ return jsonSafe;
440
388
  }
441
-
442
- var version = "8.9.3";
443
-
389
+ //#endregion
390
+ //#region package.json
391
+ var version = "8.10.1";
392
+ //#endregion
393
+ //#region src/serializeError.ts
444
394
  const DEFAULT_MAX_DEPTH = 3;
445
395
  const MAX_STACK_LINES = 20;
446
396
  function serializeError(value, depth = DEFAULT_MAX_DEPTH) {
447
- if (depth < 0 || value === null || typeof value !== 'object') {
448
- return value;
449
- }
450
- if (value instanceof Error) {
451
- const out = {
452
- name: value.name,
453
- message: value.message,
454
- stack: truncateStack(value.stack)
455
- };
456
- for (const key of Object.keys(value)) {
457
- out[key] = serializeError(value[key], depth - 1);
458
- }
459
- if (value.cause !== undefined) {
460
- out.cause = serializeError(value.cause, depth - 1);
461
- }
462
- return out;
463
- }
464
- if (Array.isArray(value)) {
465
- return value.map(item => serializeError(item, depth - 1));
466
- }
467
- return value;
397
+ if (depth < 0 || value === null || typeof value !== "object") return value;
398
+ if (value instanceof Error) {
399
+ const out = {
400
+ name: value.name,
401
+ message: value.message,
402
+ stack: truncateStack(value.stack)
403
+ };
404
+ for (const key of Object.keys(value)) out[key] = serializeError(value[key], depth - 1);
405
+ if (value.cause !== void 0) out.cause = serializeError(value.cause, depth - 1);
406
+ return out;
407
+ }
408
+ if (Array.isArray(value)) return value.map((item) => serializeError(item, depth - 1));
409
+ return value;
468
410
  }
469
411
  function stringifyError(error) {
470
- try {
471
- return JSON.stringify(sanitizeValues(serializeError(error)));
472
- } catch {
473
- if (error instanceof Error) {
474
- return JSON.stringify({
475
- name: error.name,
476
- message: error.message
477
- });
478
- }
479
- return JSON.stringify({
480
- message: String(error)
481
- });
482
- }
412
+ try {
413
+ return JSON.stringify(sanitizeValues(serializeError(error)));
414
+ } catch {
415
+ if (error instanceof Error) return JSON.stringify({
416
+ name: error.name,
417
+ message: error.message
418
+ });
419
+ return JSON.stringify({ message: String(error) });
420
+ }
483
421
  }
484
422
  function truncateStack(stack) {
485
- if (!stack) {
486
- return stack;
487
- }
488
- const lines = stack.split('\n');
489
- if (lines.length <= MAX_STACK_LINES) {
490
- return stack;
491
- }
492
- return [...lines.slice(0, MAX_STACK_LINES), '... (truncated)'].join('\n');
423
+ if (!stack) return stack;
424
+ const lines = stack.split("\n");
425
+ if (lines.length <= MAX_STACK_LINES) return stack;
426
+ return [...lines.slice(0, MAX_STACK_LINES), "... (truncated)"].join("\n");
493
427
  }
494
-
495
- // Warn when a wrapper's base_url points at the PostHog AI Gateway: the gateway
496
- // emits its own $ai_generation, so each call would be captured (and, for billable
497
- // products, billed) twice. We only warn — the wrapper's event carries data the
498
- // gateway never sees (groups, custom properties, trace hierarchy).
499
-
500
- // Keep in sync with the gateway's deployed hosts (see services/llm-gateway in the
501
- // main repo). gateway.us.posthog.com is live today; the rest are listed ahead of
502
- // any traffic moving to them.
503
- const POSTHOG_AI_GATEWAY_HOSTS = ['gateway.posthog.com', 'gateway.us.posthog.com', 'gateway.eu.posthog.com', 'ai-gateway.us.posthog.com', 'ai-gateway.eu.posthog.com'];
504
-
505
- // Swap for the dedicated AI Gateway page once it ships.
506
- const GATEWAY_DOCS_URL = 'https://posthog.com/docs/ai-observability';
507
- const extractHost = baseURL => {
508
- try {
509
- // Tolerate bare hosts that omit a scheme, e.g. "gateway.us.posthog.com/v1".
510
- const hasScheme = /^[a-z][a-z0-9+.-]*:\/\//i.test(baseURL);
511
- return new URL(hasScheme ? baseURL : `https://${baseURL}`).hostname.toLowerCase();
512
- } catch {
513
- return undefined;
514
- }
428
+ //#endregion
429
+ //#region src/gatewayWarning.ts
430
+ const POSTHOG_AI_GATEWAY_HOSTS = [
431
+ "gateway.posthog.com",
432
+ "gateway.us.posthog.com",
433
+ "gateway.eu.posthog.com",
434
+ "ai-gateway.us.posthog.com",
435
+ "ai-gateway.eu.posthog.com"
436
+ ];
437
+ const GATEWAY_DOCS_URL = "https://posthog.com/docs/ai-observability";
438
+ const extractHost = (baseURL) => {
439
+ try {
440
+ const hasScheme = /^[a-z][a-z0-9+.-]*:\/\//i.test(baseURL);
441
+ return new URL(hasScheme ? baseURL : `https://${baseURL}`).hostname.toLowerCase();
442
+ } catch {
443
+ return;
444
+ }
515
445
  };
516
- const isPostHogAiGatewayUrl = baseURL => {
517
- if (!baseURL) {
518
- return false;
519
- }
520
- const host = extractHost(baseURL);
521
- return host !== undefined && POSTHOG_AI_GATEWAY_HOSTS.includes(host);
446
+ const isPostHogAiGatewayUrl = (baseURL) => {
447
+ if (!baseURL) return false;
448
+ const host = extractHost(baseURL);
449
+ return host !== void 0 && POSTHOG_AI_GATEWAY_HOSTS.includes(host);
522
450
  };
523
-
524
- // Warns on every gateway call by design: the misconfiguration is impossible to
525
- // miss that way, and a doubled bill is worse than noisy logs.
526
- const warnIfPostHogAiGateway = baseURL => {
527
- if (!isPostHogAiGatewayUrl(baseURL)) {
528
- return;
529
- }
530
- console.warn('[PostHog] The PostHog AI wrapper is pointed at the PostHog AI Gateway. ' + 'Both capture $ai_generation, so every call is double-counted and double-billed. ' + `Use one or the other — see ${GATEWAY_DOCS_URL}.`);
451
+ const warnIfPostHogAiGateway = (baseURL) => {
452
+ if (!isPostHogAiGatewayUrl(baseURL)) return;
453
+ console.warn(`[PostHog] The PostHog AI wrapper is pointed at the PostHog AI Gateway. Both capture \$ai_generation, so every call is double-counted and double-billed. Use one or the other see ${GATEWAY_DOCS_URL}.`);
531
454
  };
532
-
455
+ //#endregion
456
+ //#region src/captureAiGeneration.ts
533
457
  /**
534
- * Options for `captureAiGeneration`. Mirrors the `$ai_generation` event shape
535
- * directly so that any caller — first-party SDK wrappers and external code
536
- * alike produces an identical event.
537
- */
538
-
539
- /**
540
- * Capture an `$ai_generation` (or `$ai_embedding`) event to PostHog.
541
- *
542
- * This is the canonical primitive that every `@posthog/ai` wrapper
543
- * (`withTracing`, `OpenAI`, `Anthropic`, `GoogleGenAI`, …) funnels through, so
544
- * external code can use it directly to instrument LLM calls made through
545
- * arbitrary clients (Cloudflare Workers AI, custom HTTP, etc.) and get the
546
- * same events the SDK wrappers produce.
547
- *
548
- * When `error` is set, the event is captured as an error. If the error is an
549
- * object, it is mutated in place to set `__posthog_previously_captured_error`
550
- * so callers can re-throw the original error reference safely.
551
- */
458
+ * Capture an `$ai_generation` (or `$ai_embedding`) event to PostHog.
459
+ *
460
+ * This is the canonical primitive that every `@posthog/ai` wrapper
461
+ * (`withTracing`, `OpenAI`, `Anthropic`, `GoogleGenAI`, …) funnels through, so
462
+ * external code can use it directly to instrument LLM calls made through
463
+ * arbitrary clients (Cloudflare Workers AI, custom HTTP, etc.) and get the
464
+ * same events the SDK wrappers produce.
465
+ *
466
+ * When `error` is set, the event is captured as an error. If the error is an
467
+ * object, it is mutated in place to set `__posthog_previously_captured_error`
468
+ * so callers can re-throw the original error reference safely.
469
+ */
552
470
  const captureAiGeneration = async (client, options) => {
553
- try {
554
- if (!client.capture) {
555
- return;
556
- }
557
- warnIfPostHogAiGateway(options.baseURL);
558
- const traceId = options.traceId ?? uuid.v4();
559
- const eventType = options.eventType ?? AIEvent.Generation;
560
- const privacyMode = options.privacyMode ?? false;
561
- const usage = options.usage ?? {};
562
-
563
- // Check privacy before reading or traversing input/output. Besides avoiding
564
- // needless work, this ensures hostile getters/proxies cannot observe a value
565
- // that the caller explicitly requested us to redact.
566
- const shouldRedact = withPrivacyMode(client, privacyMode, false) === null;
567
- const safeInput = shouldRedact ? null : core.toJsonSafeValue(options.input);
568
- const safeOutput = shouldRedact ? null : core.toJsonSafeValue(options.output);
569
- let httpStatus = options.httpStatus;
570
- let errorData = {};
571
- if (options.error) {
572
- if (httpStatus === undefined) {
573
- if (typeof options.error === 'object' && 'status' in options.error && typeof options.error.status === 'number') {
574
- httpStatus = options.error.status;
575
- } else if (typeof options.error === 'object' && 'statusCode' in options.error && typeof options.error.statusCode === 'number') {
576
- httpStatus = options.error.statusCode;
577
- } else {
578
- httpStatus = 500;
579
- }
580
- }
581
- let exceptionId;
582
- if (client.options?.enableExceptionAutocapture) {
583
- exceptionId = core.uuidv7();
584
- client.captureException(options.error, undefined, {
585
- $ai_trace_id: traceId
586
- }, exceptionId);
587
- if (typeof options.error === 'object') {
588
- ;
589
- options.error.__posthog_previously_captured_error = true;
590
- }
591
- }
592
- errorData = {
593
- $ai_is_error: true,
594
- $ai_error: stringifyError(options.error),
595
- $exception_event_id: exceptionId
596
- };
597
- }
598
- httpStatus = httpStatus ?? 200;
599
-
600
- // A configured price applies only to a count the provider reported, so a call with no
601
- // reported usage sends no cost instead of asserting $0. $ai_total_cost_usd sums the sides
602
- // that were priced, which makes it the cost of the known side alone when the other side
603
- // went unreported: a lower bound on the true total, not an assertion of it.
604
- const costOverrideData = {};
605
- if (options.costOverride) {
606
- if (usage.inputTokens !== undefined) {
607
- costOverrideData.$ai_input_cost_usd = (options.costOverride.inputCost ?? 0) * usage.inputTokens;
608
- }
609
- if (usage.outputTokens !== undefined) {
610
- costOverrideData.$ai_output_cost_usd = (options.costOverride.outputCost ?? 0) * usage.outputTokens;
611
- }
612
- if (Object.keys(costOverrideData).length > 0) {
613
- costOverrideData.$ai_total_cost_usd = (costOverrideData.$ai_input_cost_usd ?? 0) + (costOverrideData.$ai_output_cost_usd ?? 0);
614
- }
615
- }
616
-
617
- // The caller's own token counts override the SDK-derived ones further down, via the
618
- // `options.properties` spread.
619
- const tokensOverridden = hasTokenOverrides(options.properties);
620
- const additionalTokenValues = {
621
- ...(usage.reasoningTokens ? {
622
- $ai_reasoning_tokens: usage.reasoningTokens
623
- } : {}),
624
- ...(usage.cacheReadInputTokens ? {
625
- $ai_cache_read_input_tokens: usage.cacheReadInputTokens
626
- } : {}),
627
- ...(usage.cacheCreationInputTokens ? {
628
- $ai_cache_creation_input_tokens: usage.cacheCreationInputTokens
629
- } : {}),
630
- // Checked against undefined rather than truthiness, because false is the meaningful
631
- // value here and a truthiness guard would drop it.
632
- //
633
- // Dropped entirely when the caller overrides the token counts: the flag describes how
634
- // the SDK-derived counts relate to each other, so against passthrough counts it can be
635
- // wrong in the expensive direction. Declaring inclusive over counts that are actually
636
- // exclusive makes ingestion subtract the cache pool that was never in the input. A
637
- // caller who knows their own accounting model can still pass
638
- // `$ai_cache_reporting_exclusive` themselves, and that value wins.
639
- ...(usage.cacheReportingExclusive !== undefined && !tokensOverridden ? {
640
- $ai_cache_reporting_exclusive: usage.cacheReportingExclusive
641
- } : {}),
642
- ...(usage.webSearchCount ? {
643
- $ai_web_search_count: usage.webSearchCount
644
- } : {}),
645
- ...(usage.rawUsage ? {
646
- $ai_usage: usage.rawUsage
647
- } : {})
648
- };
649
- const properties = {
650
- $ai_lib: 'posthog-ai',
651
- $ai_lib_version: version,
652
- $ai_provider: options.providerOverride ?? options.provider,
653
- $ai_model: options.modelOverride ?? options.model,
654
- $ai_model_parameters: options.modelParameters ?? {},
655
- $ai_input: safeInput,
656
- $ai_output_choices: safeOutput,
657
- $ai_http_status: httpStatus,
658
- ...(usage.inputTokens !== undefined ? {
659
- $ai_input_tokens: usage.inputTokens
660
- } : {}),
661
- ...(usage.outputTokens !== undefined ? {
662
- $ai_output_tokens: usage.outputTokens
663
- } : {}),
664
- ...additionalTokenValues,
665
- ...(options.latency !== undefined ? {
666
- $ai_latency: options.latency
667
- } : {}),
668
- ...(options.timeToFirstToken !== undefined ? {
669
- $ai_time_to_first_token: options.timeToFirstToken
670
- } : {}),
671
- $ai_trace_id: traceId,
672
- $ai_base_url: options.baseURL ?? '',
673
- ...options.properties,
674
- $ai_tokens_source: getTokensSource(options.properties),
675
- ...(options.distinctId ? {} : {
676
- $process_person_profile: false
677
- }),
678
- ...(options.stopReason ? {
679
- $ai_stop_reason: options.stopReason
680
- } : {}),
681
- ...(options.tools ? {
682
- $ai_tools: options.tools
683
- } : {}),
684
- ...(options.completionId ? {
685
- $ai_completion_id: options.completionId
686
- } : {}),
687
- ...(options.providerMetadata && Object.keys(options.providerMetadata).length > 0 ? {
688
- $ai_provider_metadata: options.providerMetadata
689
- } : {}),
690
- ...errorData,
691
- ...costOverrideData
692
- };
693
- const event = {
694
- distinctId: options.distinctId ?? traceId,
695
- event: eventType,
696
- properties,
697
- groups: options.groups
698
- };
699
- if (options.captureImmediate) {
700
- await captureAiEventImmediate(client, event);
701
- } else {
702
- captureAiEvent(client, event);
703
- }
704
- } catch (error) {
705
- // Telemetry failures must never affect the instrumented provider call.
706
- console.warn('[PostHog AI] Failed to capture generation telemetry:', error);
707
- }
471
+ try {
472
+ if (!client.capture) return;
473
+ warnIfPostHogAiGateway(options.baseURL);
474
+ const traceId = options.traceId ?? (0, uuid.v4)();
475
+ const eventType = options.eventType ?? "$ai_generation";
476
+ const privacyMode = options.privacyMode ?? false;
477
+ const usage = options.usage ?? {};
478
+ const shouldRedact = withPrivacyMode(client, privacyMode, false) === null;
479
+ const safeInput = shouldRedact ? null : (0, _posthog_core.toJsonSafeValue)(options.input);
480
+ const safeOutput = shouldRedact ? null : (0, _posthog_core.toJsonSafeValue)(options.output);
481
+ let httpStatus = options.httpStatus;
482
+ let errorData = {};
483
+ if (options.error) {
484
+ if (httpStatus === void 0) {
485
+ if (typeof options.error === "object" && "status" in options.error && typeof options.error.status === "number") httpStatus = options.error.status;
486
+ else if (typeof options.error === "object" && "statusCode" in options.error && typeof options.error.statusCode === "number") httpStatus = options.error.statusCode;
487
+ else httpStatus = 500;
488
+ }
489
+ let exceptionId;
490
+ if (client.options?.enableExceptionAutocapture) {
491
+ exceptionId = (0, _posthog_core.uuidv7)();
492
+ client.captureException(options.error, void 0, { $ai_trace_id: traceId }, exceptionId);
493
+ if (typeof options.error === "object") options.error.__posthog_previously_captured_error = true;
494
+ }
495
+ errorData = {
496
+ $ai_is_error: true,
497
+ $ai_error: stringifyError(options.error),
498
+ $exception_event_id: exceptionId
499
+ };
500
+ }
501
+ httpStatus = httpStatus ?? 200;
502
+ const costOverrideData = {};
503
+ if (options.costOverride) {
504
+ if (usage.inputTokens !== void 0) costOverrideData.$ai_input_cost_usd = (options.costOverride.inputCost ?? 0) * usage.inputTokens;
505
+ if (usage.outputTokens !== void 0) costOverrideData.$ai_output_cost_usd = (options.costOverride.outputCost ?? 0) * usage.outputTokens;
506
+ if (Object.keys(costOverrideData).length > 0) costOverrideData.$ai_total_cost_usd = (costOverrideData.$ai_input_cost_usd ?? 0) + (costOverrideData.$ai_output_cost_usd ?? 0);
507
+ }
508
+ const tokensOverridden = hasTokenOverrides(options.properties);
509
+ const additionalTokenValues = {
510
+ ...usage.reasoningTokens ? { $ai_reasoning_tokens: usage.reasoningTokens } : {},
511
+ ...usage.cacheReadInputTokens ? { $ai_cache_read_input_tokens: usage.cacheReadInputTokens } : {},
512
+ ...usage.cacheCreationInputTokens ? { $ai_cache_creation_input_tokens: usage.cacheCreationInputTokens } : {},
513
+ ...usage.cacheReportingExclusive !== void 0 && !tokensOverridden ? { $ai_cache_reporting_exclusive: usage.cacheReportingExclusive } : {},
514
+ ...usage.webSearchCount ? { $ai_web_search_count: usage.webSearchCount } : {},
515
+ ...usage.rawUsage ? { $ai_usage: usage.rawUsage } : {}
516
+ };
517
+ const properties = {
518
+ $ai_lib: "posthog-ai",
519
+ $ai_lib_version: version,
520
+ $ai_provider: options.providerOverride ?? options.provider,
521
+ $ai_model: options.modelOverride ?? options.model,
522
+ $ai_model_parameters: options.modelParameters ?? {},
523
+ $ai_input: safeInput,
524
+ $ai_output_choices: safeOutput,
525
+ $ai_http_status: httpStatus,
526
+ ...usage.inputTokens !== void 0 ? { $ai_input_tokens: usage.inputTokens } : {},
527
+ ...usage.outputTokens !== void 0 ? { $ai_output_tokens: usage.outputTokens } : {},
528
+ ...additionalTokenValues,
529
+ ...options.latency !== void 0 ? { $ai_latency: options.latency } : {},
530
+ ...options.timeToFirstToken !== void 0 ? { $ai_time_to_first_token: options.timeToFirstToken } : {},
531
+ $ai_trace_id: traceId,
532
+ ...options.baseURL === null ? {} : { $ai_base_url: options.baseURL ?? "" },
533
+ ...options.properties,
534
+ $ai_tokens_source: getTokensSource(options.properties),
535
+ ...options.distinctId ? {} : { $process_person_profile: false },
536
+ ...options.stopReason ? { $ai_stop_reason: options.stopReason } : {},
537
+ ...options.tools ? { $ai_tools: options.tools } : {},
538
+ ...options.completionId ? { $ai_completion_id: options.completionId } : {},
539
+ ...options.providerMetadata && Object.keys(options.providerMetadata).length > 0 ? { $ai_provider_metadata: options.providerMetadata } : {},
540
+ ...errorData,
541
+ ...costOverrideData
542
+ };
543
+ const event = {
544
+ distinctId: options.distinctId ?? traceId,
545
+ event: eventType,
546
+ properties,
547
+ groups: options.groups
548
+ };
549
+ if (options.captureImmediate) await captureAiEventImmediate(client, event);
550
+ else captureAiEvent(client, event);
551
+ } catch (error) {
552
+ try {
553
+ options.onError?.(error);
554
+ } catch {}
555
+ console.warn("[PostHog AI] Failed to capture generation telemetry:", error);
556
+ }
708
557
  };
709
-
710
- // Union types for dual version support
711
-
712
- // Type guards
558
+ //#endregion
559
+ //#region src/vercel/middleware.ts
713
560
  function isV3Model(model) {
714
- return model.specificationVersion === 'v3';
561
+ return model.specificationVersion === "v3";
715
562
  }
716
563
  function getSpecificationVersion(model) {
717
- if (typeof model === 'object' && model !== null && 'specificationVersion' in model) {
718
- return model.specificationVersion;
719
- }
720
- return undefined;
564
+ if (typeof model === "object" && model !== null && "specificationVersion" in model) return model.specificationVersion;
721
565
  }
722
-
723
- // Content types for the output array
724
-
725
566
  const redactFileData = (data, mediaType, client) => {
726
- if (data instanceof URL) {
727
- return isFullAiCaptureEnabled(client) ? data.toString() : redactBase64DataUrl(data.toString(), data.protocol === 'data:' ? mediaType : undefined);
728
- }
729
- if (isString(data)) {
730
- return isFullAiCaptureEnabled(client) ? data : redactBase64DataUrl(data, mediaType);
731
- }
732
- return undefined;
567
+ if (data instanceof URL) return isFullAiCaptureEnabled(client) ? data.toString() : redactBase64DataUrl(data.toString(), data.protocol === "data:" ? mediaType : void 0);
568
+ if (isString(data)) return isFullAiCaptureEnabled(client) ? data : redactBase64DataUrl(data, mediaType);
733
569
  };
734
- const mapVercelParams = params => {
735
- return {
736
- temperature: params.temperature,
737
- max_output_tokens: params.maxOutputTokens,
738
- top_p: params.topP,
739
- frequency_penalty: params.frequencyPenalty,
740
- presence_penalty: params.presencePenalty,
741
- stop: params.stopSequences,
742
- stream: params.stream
743
- };
570
+ const mapVercelParams = (params) => {
571
+ return {
572
+ temperature: params.temperature,
573
+ max_output_tokens: params.maxOutputTokens,
574
+ top_p: params.topP,
575
+ frequency_penalty: params.frequencyPenalty,
576
+ presence_penalty: params.presencePenalty,
577
+ stop: params.stopSequences,
578
+ stream: params.stream
579
+ };
744
580
  };
745
581
  const mapVercelPrompt = (messages, client) => {
746
- // Map and truncate individual content
747
- const inputs = messages.map(message => {
748
- let content;
749
-
750
- // Handle system role which has string content
751
- if (message.role === 'system') {
752
- content = [{
753
- type: 'text',
754
- text: truncate(toContentString(message.content), client)
755
- }];
756
- } else {
757
- // Handle other roles which have array content
758
- if (Array.isArray(message.content)) {
759
- content = message.content.map(c => {
760
- if (c.type === 'text') {
761
- return {
762
- type: 'text',
763
- text: truncate(c.text, client)
764
- };
765
- } else if (c.type === 'file') {
766
- // Redact base64 data URLs and raw base64 to prevent oversized events
767
- const fileData = redactFileData(c.data, c.mediaType, client) ?? 'raw files not supported';
768
- return {
769
- type: 'file',
770
- file: fileData,
771
- mediaType: c.mediaType
772
- };
773
- } else if (c.type === 'reasoning') {
774
- return {
775
- type: 'reasoning',
776
- text: truncate(c.text, client)
777
- };
778
- } else if (c.type === 'tool-call') {
779
- return {
780
- type: 'tool-call',
781
- toolCallId: c.toolCallId,
782
- toolName: c.toolName,
783
- input: c.input
784
- };
785
- } else if (c.type === 'tool-result') {
786
- return {
787
- type: 'tool-result',
788
- toolCallId: c.toolCallId,
789
- toolName: c.toolName,
790
- output: sanitizeVercel(c.output, client),
791
- isError: c.isError
792
- };
793
- }
794
- return {
795
- type: 'text',
796
- text: ''
797
- };
798
- });
799
- } else {
800
- // Fallback for non-array content
801
- content = [{
802
- type: 'text',
803
- text: truncate(toContentString(message.content), client)
804
- }];
805
- }
806
- }
807
- return {
808
- role: message.role,
809
- content
810
- };
811
- });
812
-
813
- // Full AI capture means no truncation of any kind; the aggregate trim below exists
814
- // only to keep the default-mode payload under MAX_OUTPUT_SIZE.
815
- if (isFullAiCaptureEnabled(client)) {
816
- return inputs;
817
- }
818
- try {
819
- // Trim the inputs array until its serialized JSON size fits within MAX_OUTPUT_SIZE.
820
- // Pre-compute each message's byte size once so we can shift by accumulated budget
821
- // in a single linear pass, instead of re-stringifying the whole array per iteration.
822
- const messageSizes = inputs.map(m => utf8ByteLength(JSON.stringify(m)));
823
- // Account for the surrounding `[` `]` plus a comma between each pair of elements.
824
- let totalBytes = 2 + Math.max(0, messageSizes.length - 1);
825
- for (const size of messageSizes) {
826
- totalBytes += size;
827
- }
828
- let removedCount = 0;
829
- while (totalBytes > MAX_OUTPUT_SIZE && removedCount < messageSizes.length) {
830
- totalBytes -= messageSizes[removedCount];
831
- // Each removed message past the first also drops the comma that joined it.
832
- if (removedCount < messageSizes.length - 1) {
833
- totalBytes -= 1;
834
- }
835
- removedCount++;
836
- }
837
- if (removedCount > 0) {
838
- inputs.splice(0, removedCount);
839
- // Add one placeholder to indicate how many were removed
840
- inputs.unshift({
841
- role: 'posthog',
842
- content: `[${removedCount} message${removedCount === 1 ? '' : 's'} removed due to size limit]`
843
- });
844
- }
845
- } catch (error) {
846
- console.error('Error stringifying inputs', error);
847
- return [{
848
- role: 'posthog',
849
- content: 'An error occurred while processing your request. Please try again.'
850
- }];
851
- }
852
- return inputs;
582
+ const inputs = messages.map((message) => {
583
+ let content;
584
+ if (message.role === "system") content = [{
585
+ type: "text",
586
+ text: truncate(toContentString(message.content), client)
587
+ }];
588
+ else if (Array.isArray(message.content)) content = message.content.map((c) => {
589
+ if (c.type === "text") return {
590
+ type: "text",
591
+ text: truncate(c.text, client)
592
+ };
593
+ else if (c.type === "file") return {
594
+ type: "file",
595
+ file: redactFileData(c.data, c.mediaType, client) ?? "raw files not supported",
596
+ mediaType: c.mediaType
597
+ };
598
+ else if (c.type === "reasoning") return {
599
+ type: "reasoning",
600
+ text: truncate(c.text, client)
601
+ };
602
+ else if (c.type === "tool-call") return {
603
+ type: "tool-call",
604
+ toolCallId: c.toolCallId,
605
+ toolName: c.toolName,
606
+ input: c.input
607
+ };
608
+ else if (c.type === "tool-result") return {
609
+ type: "tool-result",
610
+ toolCallId: c.toolCallId,
611
+ toolName: c.toolName,
612
+ output: sanitizeVercel(c.output, client),
613
+ isError: c.isError
614
+ };
615
+ return {
616
+ type: "text",
617
+ text: ""
618
+ };
619
+ });
620
+ else content = [{
621
+ type: "text",
622
+ text: truncate(toContentString(message.content), client)
623
+ }];
624
+ return {
625
+ role: message.role,
626
+ content
627
+ };
628
+ });
629
+ if (isFullAiCaptureEnabled(client)) return inputs;
630
+ try {
631
+ const messageSizes = inputs.map((m) => utf8ByteLength(JSON.stringify(m)));
632
+ let totalBytes = 2 + Math.max(0, messageSizes.length - 1);
633
+ for (const size of messageSizes) totalBytes += size;
634
+ let removedCount = 0;
635
+ while (totalBytes > 2e5 && removedCount < messageSizes.length) {
636
+ totalBytes -= messageSizes[removedCount];
637
+ if (removedCount < messageSizes.length - 1) totalBytes -= 1;
638
+ removedCount++;
639
+ }
640
+ if (removedCount > 0) {
641
+ inputs.splice(0, removedCount);
642
+ inputs.unshift({
643
+ role: "posthog",
644
+ content: `[${removedCount} message${removedCount === 1 ? "" : "s"} removed due to size limit]`
645
+ });
646
+ }
647
+ } catch (error) {
648
+ console.error("Error stringifying inputs", error);
649
+ return [{
650
+ role: "posthog",
651
+ content: "An error occurred while processing your request. Please try again."
652
+ }];
653
+ }
654
+ return inputs;
853
655
  };
854
656
  const mapVercelOutput = (result, client) => {
855
- const content = result.map(item => {
856
- if (item.type === 'text') {
857
- return {
858
- type: 'text',
859
- text: truncate(item.text, client)
860
- };
861
- }
862
- if (item.type === 'tool-call') {
863
- const toolCall = item;
864
- const rawArgs = toolCall.input ?? toolCall.args ?? toolCall.arguments ?? {};
865
- return {
866
- type: 'tool-call',
867
- id: item.toolCallId,
868
- function: {
869
- name: item.toolName,
870
- arguments: typeof rawArgs === 'string' ? rawArgs : JSON.stringify(rawArgs)
871
- }
872
- };
873
- }
874
- if (item.type === 'reasoning') {
875
- return {
876
- type: 'reasoning',
877
- text: truncate(item.text, client)
878
- };
879
- }
880
- if (item.type === 'file') {
881
- // Handle files similar to input mapping - avoid large base64 data
882
- let fileData = redactFileData(item.data, item.mediaType, client) ?? `[binary ${item.mediaType} file]`;
883
-
884
- // Skipped under full AI capture: media stays untouched, so no placeholder swap either.
885
- if (!isFullAiCaptureEnabled(client) && typeof item.data === 'string' && fileData === item.data && item.data.length > 1000) {
886
- fileData = `[${item.mediaType} file - ${item.data.length} bytes]`;
887
- }
888
- return {
889
- type: 'file',
890
- name: 'generated_file',
891
- mediaType: item.mediaType,
892
- data: fileData
893
- };
894
- }
895
- if (item.type === 'source') {
896
- return {
897
- type: 'source',
898
- sourceType: item.sourceType,
899
- id: item.id,
900
- url: item.url || '',
901
- title: item.title || ''
902
- };
903
- }
904
- // Fallback for unknown types - try to extract text if possible
905
- return {
906
- type: 'text',
907
- text: truncate(JSON.stringify(item), client)
908
- };
909
- });
910
- if (content.length > 0) {
911
- return [{
912
- role: 'assistant',
913
- content: content.length === 1 && content[0].type === 'text' ? content[0].text : content
914
- }];
915
- }
916
- // otherwise stringify and truncate
917
- try {
918
- const jsonOutput = JSON.stringify(result);
919
- return [{
920
- content: truncate(jsonOutput, client),
921
- role: 'assistant'
922
- }];
923
- } catch {
924
- console.error('Error stringifying output');
925
- return [];
926
- }
657
+ const content = result.map((item) => {
658
+ if (item.type === "text") return {
659
+ type: "text",
660
+ text: truncate(item.text, client)
661
+ };
662
+ if (item.type === "tool-call") {
663
+ const toolCall = item;
664
+ const rawArgs = toolCall.input ?? toolCall.args ?? toolCall.arguments ?? {};
665
+ return {
666
+ type: "tool-call",
667
+ id: item.toolCallId,
668
+ function: {
669
+ name: item.toolName,
670
+ arguments: typeof rawArgs === "string" ? rawArgs : JSON.stringify(rawArgs)
671
+ }
672
+ };
673
+ }
674
+ if (item.type === "reasoning") return {
675
+ type: "reasoning",
676
+ text: truncate(item.text, client)
677
+ };
678
+ if (item.type === "file") {
679
+ let fileData = redactFileData(item.data, item.mediaType, client) ?? `[binary ${item.mediaType} file]`;
680
+ if (!isFullAiCaptureEnabled(client) && typeof item.data === "string" && fileData === item.data && item.data.length > 1e3) fileData = `[${item.mediaType} file - ${item.data.length} bytes]`;
681
+ return {
682
+ type: "file",
683
+ name: "generated_file",
684
+ mediaType: item.mediaType,
685
+ data: fileData
686
+ };
687
+ }
688
+ if (item.type === "source") return {
689
+ type: "source",
690
+ sourceType: item.sourceType,
691
+ id: item.id,
692
+ url: item.url || "",
693
+ title: item.title || ""
694
+ };
695
+ return {
696
+ type: "text",
697
+ text: truncate(JSON.stringify(item), client)
698
+ };
699
+ });
700
+ if (content.length > 0) return [{
701
+ role: "assistant",
702
+ content: content.length === 1 && content[0].type === "text" ? content[0].text : content
703
+ }];
704
+ try {
705
+ const jsonOutput = JSON.stringify(result);
706
+ return [{
707
+ content: truncate(jsonOutput, client),
708
+ role: "assistant"
709
+ }];
710
+ } catch {
711
+ console.error("Error stringifying output");
712
+ return [];
713
+ }
927
714
  };
928
- const extractProvider = model => {
929
- const provider = model.provider.toLowerCase();
930
- const providerName = provider.split('.')[0];
931
- return providerName;
715
+ const extractProvider = (model) => {
716
+ return model.provider.toLowerCase().split(".")[0];
932
717
  };
933
-
934
718
  /**
935
- * Recover the base URL so gateway calls self-identify via `$ai_base_url` (dedup
936
- * keys on it). The spec exposes none, so we read the off-spec provider `config`:
937
- * `@ai-sdk/anthropic` keeps a `config.baseURL` string; `@ai-sdk/openai`/
938
- * `openai-compatible` bury it in a `config.url({ path })` closure. Unknown shapes
939
- * degrade to `''` — those providers (or a custom `fetch`) stay invisible to dedup.
940
- */
941
- const extractBaseURL = model => {
942
- try {
943
- const config = model.config;
944
- if (!isObject(config)) {
945
- return '';
946
- }
947
- if (isString(config.baseURL)) {
948
- return config.baseURL;
949
- }
950
- const urlFn = config.url;
951
- if (typeof urlFn === 'function') {
952
- const url = urlFn({
953
- path: '',
954
- modelId: model.modelId
955
- });
956
- return isString(url) ? url : '';
957
- }
958
- } catch {
959
- // Unknown config shape or url() threw.
960
- }
961
- return '';
719
+ * Recover the base URL so gateway calls self-identify via `$ai_base_url` (dedup
720
+ * keys on it). The spec exposes none, so we read the off-spec provider `config`:
721
+ * `@ai-sdk/anthropic` keeps a `config.baseURL` string; `@ai-sdk/openai`/
722
+ * `openai-compatible` bury it in a `config.url({ path })` closure. Unknown shapes
723
+ * degrade to `''` — those providers (or a custom `fetch`) stay invisible to dedup.
724
+ */
725
+ const extractBaseURL = (model) => {
726
+ try {
727
+ const config = model.config;
728
+ if (!isObject(config)) return "";
729
+ if (isString(config.baseURL)) return config.baseURL;
730
+ const urlFn = config.url;
731
+ if (typeof urlFn === "function") {
732
+ const url = urlFn({
733
+ path: "",
734
+ modelId: model.modelId
735
+ });
736
+ return isString(url) ? url : "";
737
+ }
738
+ } catch {}
739
+ return "";
962
740
  };
963
-
964
- // Extract web search count from provider metadata (works for both V2 and V3)
965
741
  const extractWebSearchCount = (providerMetadata, usage) => {
966
- // Try Anthropic-specific extraction
967
- if (providerMetadata && typeof providerMetadata === 'object' && 'anthropic' in providerMetadata && providerMetadata.anthropic && typeof providerMetadata.anthropic === 'object' && 'server_tool_use' in providerMetadata.anthropic) {
968
- const serverToolUse = providerMetadata.anthropic.server_tool_use;
969
- if (serverToolUse && typeof serverToolUse === 'object' && 'web_search_requests' in serverToolUse && typeof serverToolUse.web_search_requests === 'number') {
970
- return serverToolUse.web_search_requests;
971
- }
972
- }
973
-
974
- // Fall back to generic calculation
975
- return calculateWebSearchCount({
976
- usage,
977
- providerMetadata
978
- });
742
+ if (providerMetadata && typeof providerMetadata === "object" && "anthropic" in providerMetadata && providerMetadata.anthropic && typeof providerMetadata.anthropic === "object" && "server_tool_use" in providerMetadata.anthropic) {
743
+ const serverToolUse = providerMetadata.anthropic.server_tool_use;
744
+ if (serverToolUse && typeof serverToolUse === "object" && "web_search_requests" in serverToolUse && typeof serverToolUse.web_search_requests === "number") return serverToolUse.web_search_requests;
745
+ }
746
+ return calculateWebSearchCount({
747
+ usage,
748
+ providerMetadata
749
+ });
979
750
  };
980
-
981
- // Helper to extract numeric token value from V2 (number) or V3 (object with .total) usage formats
982
- const extractTokenCount = value => {
983
- if (typeof value === 'number') {
984
- return value;
985
- }
986
- if (value && typeof value === 'object' && 'total' in value && typeof value.total === 'number') {
987
- return value.total;
988
- }
989
- return undefined;
751
+ const extractTokenCount = (value) => {
752
+ if (typeof value === "number") return value;
753
+ if (value && typeof value === "object" && "total" in value && typeof value.total === "number") return value.total;
990
754
  };
991
755
  const extractUsageToken = (usage, topLevelKey, nestedObjectKey, nestedValueKey) => {
992
- if (topLevelKey in usage) {
993
- return usage[topLevelKey];
994
- }
995
- const nestedTokens = usage[nestedObjectKey];
996
- if (nestedTokens && typeof nestedTokens === 'object' && nestedValueKey in nestedTokens) {
997
- return nestedTokens[nestedValueKey];
998
- }
999
- return undefined;
756
+ if (topLevelKey in usage) return usage[topLevelKey];
757
+ const nestedTokens = usage[nestedObjectKey];
758
+ if (nestedTokens && typeof nestedTokens === "object" && nestedValueKey in nestedTokens) return nestedTokens[nestedValueKey];
1000
759
  };
1001
-
1002
- // Helper to extract reasoning tokens from V2 (usage.reasoningTokens) or V3 (usage.outputTokens.reasoning)
1003
- const extractReasoningTokens = usage => extractUsageToken(usage, 'reasoningTokens', 'outputTokens', 'reasoning');
1004
-
1005
- // Helper to extract cached input tokens from V2 (usage.cachedInputTokens) or V3 (usage.inputTokens.cacheRead)
1006
- const extractCacheReadTokens = usage => extractUsageToken(usage, 'cachedInputTokens', 'inputTokens', 'cacheRead');
1007
-
1008
- // Helper to extract cache write tokens from V3 (usage.inputTokens.cacheWrite). Providers like
1009
- // Amazon Bedrock populate this standardized field instead of providerMetadata.anthropic.
1010
- const extractCacheWriteTokens = usage => {
1011
- if ('inputTokens' in usage && usage.inputTokens && typeof usage.inputTokens === 'object' && 'cacheWrite' in usage.inputTokens) {
1012
- return usage.inputTokens.cacheWrite;
1013
- }
1014
- return undefined;
760
+ const extractReasoningTokens = (usage) => extractUsageToken(usage, "reasoningTokens", "outputTokens", "reasoning");
761
+ const extractCacheReadTokens = (usage) => extractUsageToken(usage, "cachedInputTokens", "inputTokens", "cacheRead");
762
+ const extractCacheWriteTokens = (usage) => {
763
+ if ("inputTokens" in usage && usage.inputTokens && typeof usage.inputTokens === "object" && "cacheWrite" in usage.inputTokens) return usage.inputTokens.cacheWrite;
1015
764
  };
1016
-
1017
- // Extract additional token values from provider metadata, with a V3 standardized fallback
1018
- // (e.g. Amazon Bedrock exposes cache write tokens via usage.inputTokens.cacheWrite rather
1019
- // than providerMetadata.anthropic.cacheCreationInputTokens). A cacheWrite of 0 is treated
1020
- // as absent so we preserve the pre-fallback event shape on providers that simply omit the
1021
- // field — consumers downstream saw `$ai_cache_creation_input_tokens` missing, not 0.
1022
765
  const extractAdditionalTokenValues = (providerMetadata, usage) => {
1023
- if (providerMetadata && typeof providerMetadata === 'object' && 'anthropic' in providerMetadata && providerMetadata.anthropic && typeof providerMetadata.anthropic === 'object' && 'cacheCreationInputTokens' in providerMetadata.anthropic) {
1024
- return {
1025
- cacheCreationInputTokens: providerMetadata.anthropic.cacheCreationInputTokens
1026
- };
1027
- }
1028
- if (usage && typeof usage === 'object') {
1029
- const cacheWrite = extractCacheWriteTokens(usage);
1030
- if (typeof cacheWrite === 'number' && cacheWrite > 0) {
1031
- return {
1032
- cacheCreationInputTokens: cacheWrite
1033
- };
1034
- }
1035
- }
1036
- return {};
766
+ if (providerMetadata && typeof providerMetadata === "object" && "anthropic" in providerMetadata && providerMetadata.anthropic && typeof providerMetadata.anthropic === "object" && "cacheCreationInputTokens" in providerMetadata.anthropic) return { cacheCreationInputTokens: providerMetadata.anthropic.cacheCreationInputTokens };
767
+ if (usage && typeof usage === "object") {
768
+ const cacheWrite = extractCacheWriteTokens(usage);
769
+ if (typeof cacheWrite === "number" && cacheWrite > 0) return { cacheCreationInputTokens: cacheWrite };
770
+ }
771
+ return {};
1037
772
  };
1038
-
1039
- // Detects Anthropic Claude regardless of host (direct Anthropic, Amazon Bedrock, Google Vertex, etc.).
1040
- // The server applies exclusive cache token accounting based on the model name, so any Claude model
1041
- // needs its V3 input tokens adjusted to exclude cache tokens — not just those routed through a
1042
- // provider whose name contains "anthropic". Accepts the resolved modelId string (not the raw model)
1043
- // so it sees the same id the server does after posthogModelOverride / response.modelId fallbacks.
1044
773
  const isAnthropicClaudeModel = (modelId, provider) => {
1045
- if (provider.toLowerCase().includes('anthropic')) {
1046
- return true;
1047
- }
1048
- return /claude|anthropic/i.test(modelId);
774
+ if (provider.toLowerCase().includes("anthropic")) return true;
775
+ return /claude|anthropic/i.test(modelId);
1049
776
  };
1050
-
1051
- // For Anthropic providers in V3, inputTokens.total is the sum of all tokens (uncached + cache read + cache write).
1052
- // Our cost calculation expects inputTokens to be only the uncached portion for Anthropic.
1053
- // This helper subtracts cache tokens from inputTokens for Anthropic V3 models.
1054
777
  const adjustAnthropicV3CacheTokens = (model, modelId, provider, usage) => {
1055
- if (isV3Model(model) && isAnthropicClaudeModel(modelId, provider)) {
1056
- const cacheReadTokens = usage.cacheReadInputTokens || 0;
1057
- const cacheWriteTokens = usage.cacheCreationInputTokens || 0;
1058
- const cacheTokens = cacheReadTokens + cacheWriteTokens;
1059
- if (usage.inputTokens && cacheTokens > 0) {
1060
- usage.inputTokens = Math.max(usage.inputTokens - cacheTokens, 0);
1061
- }
1062
- }
778
+ if (isV3Model(model) && isAnthropicClaudeModel(modelId, provider)) {
779
+ const cacheTokens = (usage.cacheReadInputTokens || 0) + (usage.cacheCreationInputTokens || 0);
780
+ if (usage.inputTokens && cacheTokens > 0) usage.inputTokens = Math.max(usage.inputTokens - cacheTokens, 0);
781
+ }
1063
782
  };
1064
-
1065
783
  /**
1066
- * Wraps a Vercel AI SDK language model (V2 or V3) with PostHog tracing.
1067
- * Automatically detects the model version and applies appropriate instrumentation.
1068
- */
784
+ * Wraps a Vercel AI SDK language model (V2 or V3) with PostHog tracing.
785
+ * Automatically detects the model version and applies appropriate instrumentation.
786
+ */
1069
787
  const wrapVercelLanguageModel = (model, phClient, options) => {
1070
- const specificationVersion = getSpecificationVersion(model);
1071
- if (specificationVersion !== 'v2' && specificationVersion !== 'v3') {
1072
- throw new Error(`[PostHog AI] withTracing supports Vercel AI SDK v5 and v6 models only. ` + `Use @ai-sdk/otel with @posthog/ai/otel for AI SDK v7 models.`);
1073
- }
1074
- const traceId = options.posthogTraceId ?? uuid.v4();
1075
- const mergedOptions = {
1076
- ...options,
1077
- posthogTraceId: traceId,
1078
- posthogDistinctId: options.posthogDistinctId,
1079
- posthogProperties: {
1080
- ...options.posthogProperties,
1081
- $ai_framework: 'vercel',
1082
- $ai_framework_version: model.specificationVersion === 'v3' ? '6' : '5'
1083
- }
1084
- };
1085
-
1086
- // Shared `captureAiGeneration` options for every call site in this wrapper.
1087
- const baseOptions = {
1088
- distinctId: mergedOptions.posthogDistinctId,
1089
- traceId,
1090
- properties: mergedOptions.posthogProperties,
1091
- groups: mergedOptions.posthogGroups,
1092
- privacyMode: mergedOptions.posthogPrivacyMode,
1093
- modelOverride: mergedOptions.posthogModelOverride,
1094
- providerOverride: mergedOptions.posthogProviderOverride,
1095
- costOverride: mergedOptions.posthogCostOverride,
1096
- captureImmediate: mergedOptions.posthogCaptureImmediate
1097
- };
1098
-
1099
- // Create wrapped model using Object.create to preserve the prototype chain
1100
- // This automatically inherits all properties (including getters) from the model
1101
- const wrappedModel = Object.create(model, {
1102
- doGenerate: {
1103
- value: async params => {
1104
- const startTime = Date.now();
1105
- const mergedParams = {
1106
- ...mergedOptions,
1107
- ...mapVercelParams(params)
1108
- };
1109
- const availableTools = extractAvailableToolCalls('vercel', params);
1110
- const baseURL = extractBaseURL(model);
1111
- try {
1112
- const result = await model.doGenerate(params);
1113
- const modelId = mergedOptions.posthogModelOverride ?? (result.response?.modelId ? result.response.modelId : model.modelId);
1114
- const provider = mergedOptions.posthogProviderOverride ?? extractProvider(model);
1115
- // result.content is undefined when the model returns only tool calls with no text output
1116
- const content = mapVercelOutput(result.content ?? [], phClient);
1117
- const latency = (Date.now() - startTime) / 1000;
1118
- const providerMetadata = result.providerMetadata;
1119
- const additionalTokenValues = extractAdditionalTokenValues(providerMetadata, result.usage);
1120
- const webSearchCount = extractWebSearchCount(providerMetadata, result.usage);
1121
-
1122
- // V2 usage has simple numbers, V3 has objects with .total - normalize both
1123
- const usageObj = result.usage;
1124
-
1125
- // Extract raw response for providers that include detailed usage metadata
1126
- // For Gemini, candidatesTokensDetails is in result.response.body.usageMetadata
1127
- const rawUsageData = {
1128
- usage: result.usage,
1129
- providerMetadata
1130
- };
1131
-
1132
- // Include response body usageMetadata if it contains detailed token breakdown (e.g., candidatesTokensDetails)
1133
- if (result.response && typeof result.response === 'object') {
1134
- const responseBody = result.response.body;
1135
- if (responseBody && typeof responseBody === 'object' && 'usageMetadata' in responseBody) {
1136
- rawUsageData.rawResponse = {
1137
- usageMetadata: responseBody.usageMetadata
1138
- };
1139
- }
1140
- }
1141
- const usage = {
1142
- inputTokens: extractTokenCount(result.usage.inputTokens),
1143
- outputTokens: extractTokenCount(result.usage.outputTokens),
1144
- reasoningTokens: extractReasoningTokens(usageObj),
1145
- cacheReadInputTokens: extractCacheReadTokens(usageObj),
1146
- webSearchCount,
1147
- ...additionalTokenValues,
1148
- rawUsage: rawUsageData
1149
- };
1150
- adjustAnthropicV3CacheTokens(model, modelId, provider, usage);
1151
-
1152
- // Extract finish reason - V2 returns a string, V3 returns an object with .unified
1153
- const rawFinishReason = result.finishReason;
1154
- const finishReasonStr = typeof rawFinishReason === 'string' ? rawFinishReason : rawFinishReason && typeof rawFinishReason === 'object' && 'unified' in rawFinishReason ? String(rawFinishReason.unified) : undefined;
1155
- await captureAiGeneration(phClient, {
1156
- ...baseOptions,
1157
- model: modelId,
1158
- provider: provider,
1159
- input: mergedOptions.posthogPrivacyMode ? '' : mapVercelPrompt(params.prompt, phClient),
1160
- output: content,
1161
- latency,
1162
- baseURL,
1163
- modelParameters: getModelParams(mergedParams),
1164
- httpStatus: 200,
1165
- usage,
1166
- stopReason: finishReasonStr,
1167
- tools: availableTools
1168
- });
1169
- return result;
1170
- } catch (error) {
1171
- const modelId = model.modelId;
1172
- await captureAiGeneration(phClient, {
1173
- ...baseOptions,
1174
- model: modelId,
1175
- provider: model.provider,
1176
- input: mergedOptions.posthogPrivacyMode ? '' : mapVercelPrompt(params.prompt, phClient),
1177
- output: [],
1178
- latency: (Date.now() - startTime) / 1000,
1179
- baseURL,
1180
- modelParameters: getModelParams(mergedParams),
1181
- usage: {},
1182
- error: error,
1183
- tools: availableTools
1184
- });
1185
- throw error;
1186
- }
1187
- },
1188
- writable: true,
1189
- configurable: true,
1190
- enumerable: false
1191
- },
1192
- doStream: {
1193
- value: async params => {
1194
- const startTime = Date.now();
1195
- let firstTokenTime;
1196
- let generatedText = '';
1197
- let reasoningText = '';
1198
- let stopReason;
1199
- let usage = {};
1200
- let providerMetadata = undefined;
1201
- const mergedParams = {
1202
- ...mergedOptions,
1203
- ...mapVercelParams(params)
1204
- };
1205
- const modelId = mergedOptions.posthogModelOverride ?? model.modelId;
1206
- const provider = mergedOptions.posthogProviderOverride ?? extractProvider(model);
1207
- const availableTools = extractAvailableToolCalls('vercel', params);
1208
- const baseURL = extractBaseURL(model);
1209
-
1210
- // Map to track in-progress tool calls
1211
- const toolCallsInProgress = new Map();
1212
- const captureStreamGeneration = async captureOptions => {
1213
- try {
1214
- await captureAiGeneration(phClient, captureOptions);
1215
- } catch (error) {
1216
- // Telemetry must never change the provider stream's behavior.
1217
- console.warn('[PostHog AI] Failed to capture Vercel stream telemetry:', error);
1218
- }
1219
- };
1220
- try {
1221
- const {
1222
- stream,
1223
- ...rest
1224
- } = await model.doStream(params);
1225
- const reader = stream.getReader();
1226
- let inBandError;
1227
- let hasInBandError = false;
1228
- let finalizationPromise;
1229
- const observeChunk = chunk => {
1230
- // Handle streaming patterns - compatible with both V2 and V3
1231
- if (chunk.type === 'text-delta') {
1232
- if (firstTokenTime === undefined) {
1233
- firstTokenTime = Date.now();
1234
- }
1235
- generatedText += chunk.delta;
1236
- }
1237
- if (chunk.type === 'reasoning-delta') {
1238
- if (firstTokenTime === undefined) {
1239
- firstTokenTime = Date.now();
1240
- }
1241
- reasoningText += chunk.delta;
1242
- }
1243
-
1244
- // Handle tool call chunks
1245
- if (chunk.type === 'tool-input-start') {
1246
- if (firstTokenTime === undefined) {
1247
- firstTokenTime = Date.now();
1248
- }
1249
- toolCallsInProgress.set(chunk.id, {
1250
- toolCallId: chunk.id,
1251
- toolName: chunk.toolName,
1252
- input: ''
1253
- });
1254
- }
1255
- if (chunk.type === 'tool-input-delta') {
1256
- const toolCall = toolCallsInProgress.get(chunk.id);
1257
- if (toolCall) {
1258
- toolCall.input += chunk.delta;
1259
- }
1260
- }
1261
- if (chunk.type === 'tool-call') {
1262
- if (firstTokenTime === undefined) {
1263
- firstTokenTime = Date.now();
1264
- }
1265
- toolCallsInProgress.set(chunk.toolCallId, {
1266
- toolCallId: chunk.toolCallId,
1267
- toolName: chunk.toolName,
1268
- input: chunk.input
1269
- });
1270
- }
1271
- if (chunk.type === 'error') {
1272
- hasInBandError = true;
1273
- inBandError = chunk.error;
1274
- }
1275
- if (chunk.type === 'finish') {
1276
- providerMetadata = chunk.providerMetadata;
1277
- const chunkUsage = chunk.usage || {};
1278
- const additionalTokenValues = extractAdditionalTokenValues(providerMetadata, chunkUsage);
1279
- usage = {
1280
- inputTokens: extractTokenCount(chunk.usage?.inputTokens),
1281
- outputTokens: extractTokenCount(chunk.usage?.outputTokens),
1282
- reasoningTokens: extractReasoningTokens(chunkUsage),
1283
- cacheReadInputTokens: extractCacheReadTokens(chunkUsage),
1284
- ...additionalTokenValues
1285
- };
1286
-
1287
- // Extract finish reason - V2 returns a string, V3 returns an object with .unified
1288
- const rawFinishReason = chunk.finishReason;
1289
- if (typeof rawFinishReason === 'string') {
1290
- stopReason = rawFinishReason;
1291
- } else if (rawFinishReason && typeof rawFinishReason === 'object' && 'unified' in rawFinishReason) {
1292
- stopReason = String(rawFinishReason.unified);
1293
- }
1294
- }
1295
- };
1296
- const finalize = (terminalError, isError = false) => {
1297
- if (finalizationPromise) {
1298
- return finalizationPromise;
1299
- }
1300
- finalizationPromise = (async () => {
1301
- const latency = (Date.now() - startTime) / 1000;
1302
- const timeToFirstToken = firstTokenTime !== undefined ? (firstTokenTime - startTime) / 1000 : undefined;
1303
- const content = [];
1304
- if (reasoningText) {
1305
- content.push({
1306
- type: 'reasoning',
1307
- text: truncate(reasoningText, phClient)
1308
- });
1309
- }
1310
- if (generatedText) {
1311
- content.push({
1312
- type: 'text',
1313
- text: truncate(generatedText, phClient)
1314
- });
1315
- }
1316
- for (const toolCall of toolCallsInProgress.values()) {
1317
- if (toolCall.toolName) {
1318
- content.push({
1319
- type: 'tool-call',
1320
- id: toolCall.toolCallId,
1321
- function: {
1322
- name: toolCall.toolName,
1323
- arguments: toolCall.input
1324
- }
1325
- });
1326
- }
1327
- }
1328
- const output = content.length > 0 ? [{
1329
- role: 'assistant',
1330
- content: content.length === 1 && content[0].type === 'text' ? content[0].text : content
1331
- }] : [];
1332
- const webSearchCount = extractWebSearchCount(providerMetadata, usage);
1333
- const finalUsage = {
1334
- ...usage,
1335
- webSearchCount,
1336
- rawUsage: {
1337
- usage,
1338
- providerMetadata
1339
- }
1340
- };
1341
- adjustAnthropicV3CacheTokens(model, modelId, provider, finalUsage);
1342
- const finishError = stopReason === 'error' ? new Error('Vercel AI SDK stream finished with an error') : undefined;
1343
- const error = isError ? terminalError ?? new Error('Vercel AI SDK stream failed') : hasInBandError ? inBandError ?? new Error('Vercel AI SDK stream emitted an error chunk') : finishError;
1344
- await captureStreamGeneration({
1345
- ...baseOptions,
1346
- model: modelId,
1347
- provider: provider,
1348
- input: mergedOptions.posthogPrivacyMode ? '' : mapVercelPrompt(params.prompt, phClient),
1349
- output,
1350
- latency,
1351
- timeToFirstToken,
1352
- baseURL,
1353
- modelParameters: getModelParams(mergedParams),
1354
- httpStatus: error ? undefined : 200,
1355
- usage: finalUsage,
1356
- stopReason,
1357
- error,
1358
- tools: availableTools
1359
- });
1360
- })().catch(error => {
1361
- // Building telemetry must not change the provider stream's behavior.
1362
- console.warn('[PostHog AI] Failed to capture Vercel stream telemetry:', error);
1363
- });
1364
- return finalizationPromise;
1365
- };
1366
- const instrumentedStream = new ReadableStream({
1367
- async pull(controller) {
1368
- let result;
1369
- try {
1370
- result = await reader.read();
1371
- } catch (error) {
1372
- void finalize(error, true);
1373
- controller.error(error);
1374
- return;
1375
- }
1376
- if (result.done) {
1377
- controller.close();
1378
- void finalize();
1379
- return;
1380
- }
1381
- try {
1382
- observeChunk(result.value);
1383
- } catch {
1384
- // Instrumentation must not alter or suppress provider chunks.
1385
- }
1386
- controller.enqueue(result.value);
1387
- },
1388
- cancel(reason) {
1389
- void finalize(reason ?? new Error('Vercel AI SDK stream was cancelled'), true);
1390
- return reader.cancel(reason);
1391
- }
1392
- }, {
1393
- highWaterMark: 0
1394
- });
1395
- return {
1396
- stream: instrumentedStream,
1397
- ...rest
1398
- };
1399
- } catch (error) {
1400
- await captureStreamGeneration({
1401
- ...baseOptions,
1402
- model: modelId,
1403
- provider: provider,
1404
- input: mergedOptions.posthogPrivacyMode ? '' : mapVercelPrompt(params.prompt, phClient),
1405
- output: [],
1406
- latency: (Date.now() - startTime) / 1000,
1407
- baseURL,
1408
- modelParameters: getModelParams(mergedParams),
1409
- usage: {},
1410
- error: error,
1411
- tools: availableTools
1412
- });
1413
- throw error;
1414
- }
1415
- },
1416
- writable: true,
1417
- configurable: true,
1418
- enumerable: false
1419
- }
1420
- });
1421
- return wrappedModel;
788
+ const specificationVersion = getSpecificationVersion(model);
789
+ if (specificationVersion !== "v2" && specificationVersion !== "v3") throw new Error("[PostHog AI] withTracing supports Vercel AI SDK v5 and v6 models only. Use @ai-sdk/otel with @posthog/ai/otel for AI SDK v7 models.");
790
+ const traceId = options.posthogTraceId ?? (0, uuid.v4)();
791
+ const mergedOptions = {
792
+ ...options,
793
+ posthogTraceId: traceId,
794
+ posthogDistinctId: options.posthogDistinctId,
795
+ posthogProperties: {
796
+ ...options.posthogProperties,
797
+ $ai_framework: "vercel",
798
+ $ai_framework_version: model.specificationVersion === "v3" ? "6" : "5"
799
+ }
800
+ };
801
+ const baseOptions = {
802
+ distinctId: mergedOptions.posthogDistinctId,
803
+ traceId,
804
+ properties: mergedOptions.posthogProperties,
805
+ groups: mergedOptions.posthogGroups,
806
+ privacyMode: mergedOptions.posthogPrivacyMode,
807
+ modelOverride: mergedOptions.posthogModelOverride,
808
+ providerOverride: mergedOptions.posthogProviderOverride,
809
+ costOverride: mergedOptions.posthogCostOverride,
810
+ captureImmediate: mergedOptions.posthogCaptureImmediate
811
+ };
812
+ return Object.create(model, {
813
+ doGenerate: {
814
+ value: async (params) => {
815
+ const startTime = Date.now();
816
+ const mergedParams = {
817
+ ...mergedOptions,
818
+ ...mapVercelParams(params)
819
+ };
820
+ const availableTools = extractAvailableToolCalls("vercel", params);
821
+ const baseURL = extractBaseURL(model);
822
+ try {
823
+ const result = await model.doGenerate(params);
824
+ const modelId = mergedOptions.posthogModelOverride ?? (result.response?.modelId ? result.response.modelId : model.modelId);
825
+ const provider = mergedOptions.posthogProviderOverride ?? extractProvider(model);
826
+ const content = mapVercelOutput(result.content ?? [], phClient);
827
+ const latency = (Date.now() - startTime) / 1e3;
828
+ const providerMetadata = result.providerMetadata;
829
+ const additionalTokenValues = extractAdditionalTokenValues(providerMetadata, result.usage);
830
+ const webSearchCount = extractWebSearchCount(providerMetadata, result.usage);
831
+ const usageObj = result.usage;
832
+ const rawUsageData = {
833
+ usage: result.usage,
834
+ providerMetadata
835
+ };
836
+ if (result.response && typeof result.response === "object") {
837
+ const responseBody = result.response.body;
838
+ if (responseBody && typeof responseBody === "object" && "usageMetadata" in responseBody) rawUsageData.rawResponse = { usageMetadata: responseBody.usageMetadata };
839
+ }
840
+ const usage = {
841
+ inputTokens: extractTokenCount(result.usage.inputTokens),
842
+ outputTokens: extractTokenCount(result.usage.outputTokens),
843
+ reasoningTokens: extractReasoningTokens(usageObj),
844
+ cacheReadInputTokens: extractCacheReadTokens(usageObj),
845
+ webSearchCount,
846
+ ...additionalTokenValues,
847
+ rawUsage: rawUsageData
848
+ };
849
+ adjustAnthropicV3CacheTokens(model, modelId, provider, usage);
850
+ const rawFinishReason = result.finishReason;
851
+ const finishReasonStr = typeof rawFinishReason === "string" ? rawFinishReason : rawFinishReason && typeof rawFinishReason === "object" && "unified" in rawFinishReason ? String(rawFinishReason.unified) : void 0;
852
+ await captureAiGeneration(phClient, {
853
+ ...baseOptions,
854
+ model: modelId,
855
+ provider,
856
+ input: mergedOptions.posthogPrivacyMode ? "" : mapVercelPrompt(params.prompt, phClient),
857
+ output: content,
858
+ latency,
859
+ baseURL,
860
+ modelParameters: getModelParams(mergedParams),
861
+ httpStatus: 200,
862
+ usage,
863
+ stopReason: finishReasonStr,
864
+ tools: availableTools
865
+ });
866
+ return result;
867
+ } catch (error) {
868
+ const modelId = model.modelId;
869
+ await captureAiGeneration(phClient, {
870
+ ...baseOptions,
871
+ model: modelId,
872
+ provider: model.provider,
873
+ input: mergedOptions.posthogPrivacyMode ? "" : mapVercelPrompt(params.prompt, phClient),
874
+ output: [],
875
+ latency: (Date.now() - startTime) / 1e3,
876
+ baseURL,
877
+ modelParameters: getModelParams(mergedParams),
878
+ usage: {},
879
+ error,
880
+ tools: availableTools
881
+ });
882
+ throw error;
883
+ }
884
+ },
885
+ writable: true,
886
+ configurable: true,
887
+ enumerable: false
888
+ },
889
+ doStream: {
890
+ value: async (params) => {
891
+ const startTime = Date.now();
892
+ let firstTokenTime;
893
+ let generatedText = "";
894
+ let reasoningText = "";
895
+ let stopReason;
896
+ let usage = {};
897
+ let providerMetadata = void 0;
898
+ const mergedParams = {
899
+ ...mergedOptions,
900
+ ...mapVercelParams(params)
901
+ };
902
+ const modelId = mergedOptions.posthogModelOverride ?? model.modelId;
903
+ const provider = mergedOptions.posthogProviderOverride ?? extractProvider(model);
904
+ const availableTools = extractAvailableToolCalls("vercel", params);
905
+ const baseURL = extractBaseURL(model);
906
+ const toolCallsInProgress = /* @__PURE__ */ new Map();
907
+ const captureStreamGeneration = async (captureOptions) => {
908
+ try {
909
+ await captureAiGeneration(phClient, captureOptions);
910
+ } catch (error) {
911
+ console.warn("[PostHog AI] Failed to capture Vercel stream telemetry:", error);
912
+ }
913
+ };
914
+ try {
915
+ const { stream, ...rest } = await model.doStream(params);
916
+ const reader = stream.getReader();
917
+ let inBandError;
918
+ let hasInBandError = false;
919
+ let finalizationPromise;
920
+ const observeChunk = (chunk) => {
921
+ if (chunk.type === "text-delta") {
922
+ if (firstTokenTime === void 0) firstTokenTime = Date.now();
923
+ generatedText += chunk.delta;
924
+ }
925
+ if (chunk.type === "reasoning-delta") {
926
+ if (firstTokenTime === void 0) firstTokenTime = Date.now();
927
+ reasoningText += chunk.delta;
928
+ }
929
+ if (chunk.type === "tool-input-start") {
930
+ if (firstTokenTime === void 0) firstTokenTime = Date.now();
931
+ toolCallsInProgress.set(chunk.id, {
932
+ toolCallId: chunk.id,
933
+ toolName: chunk.toolName,
934
+ input: ""
935
+ });
936
+ }
937
+ if (chunk.type === "tool-input-delta") {
938
+ const toolCall = toolCallsInProgress.get(chunk.id);
939
+ if (toolCall) toolCall.input += chunk.delta;
940
+ }
941
+ if (chunk.type === "tool-call") {
942
+ if (firstTokenTime === void 0) firstTokenTime = Date.now();
943
+ toolCallsInProgress.set(chunk.toolCallId, {
944
+ toolCallId: chunk.toolCallId,
945
+ toolName: chunk.toolName,
946
+ input: chunk.input
947
+ });
948
+ }
949
+ if (chunk.type === "error") {
950
+ hasInBandError = true;
951
+ inBandError = chunk.error;
952
+ }
953
+ if (chunk.type === "finish") {
954
+ providerMetadata = chunk.providerMetadata;
955
+ const chunkUsage = chunk.usage || {};
956
+ const additionalTokenValues = extractAdditionalTokenValues(providerMetadata, chunkUsage);
957
+ usage = {
958
+ inputTokens: extractTokenCount(chunk.usage?.inputTokens),
959
+ outputTokens: extractTokenCount(chunk.usage?.outputTokens),
960
+ reasoningTokens: extractReasoningTokens(chunkUsage),
961
+ cacheReadInputTokens: extractCacheReadTokens(chunkUsage),
962
+ ...additionalTokenValues
963
+ };
964
+ const rawFinishReason = chunk.finishReason;
965
+ if (typeof rawFinishReason === "string") stopReason = rawFinishReason;
966
+ else if (rawFinishReason && typeof rawFinishReason === "object" && "unified" in rawFinishReason) stopReason = String(rawFinishReason.unified);
967
+ }
968
+ };
969
+ const finalize = (terminalError, isError = false) => {
970
+ if (finalizationPromise) return finalizationPromise;
971
+ finalizationPromise = (async () => {
972
+ const latency = (Date.now() - startTime) / 1e3;
973
+ const timeToFirstToken = firstTokenTime !== void 0 ? (firstTokenTime - startTime) / 1e3 : void 0;
974
+ const content = [];
975
+ if (reasoningText) content.push({
976
+ type: "reasoning",
977
+ text: truncate(reasoningText, phClient)
978
+ });
979
+ if (generatedText) content.push({
980
+ type: "text",
981
+ text: truncate(generatedText, phClient)
982
+ });
983
+ for (const toolCall of toolCallsInProgress.values()) if (toolCall.toolName) content.push({
984
+ type: "tool-call",
985
+ id: toolCall.toolCallId,
986
+ function: {
987
+ name: toolCall.toolName,
988
+ arguments: toolCall.input
989
+ }
990
+ });
991
+ const output = content.length > 0 ? [{
992
+ role: "assistant",
993
+ content: content.length === 1 && content[0].type === "text" ? content[0].text : content
994
+ }] : [];
995
+ const webSearchCount = extractWebSearchCount(providerMetadata, usage);
996
+ const finalUsage = {
997
+ ...usage,
998
+ webSearchCount,
999
+ rawUsage: {
1000
+ usage,
1001
+ providerMetadata
1002
+ }
1003
+ };
1004
+ adjustAnthropicV3CacheTokens(model, modelId, provider, finalUsage);
1005
+ const error = isError ? terminalError ?? /* @__PURE__ */ new Error("Vercel AI SDK stream failed") : hasInBandError ? inBandError ?? /* @__PURE__ */ new Error("Vercel AI SDK stream emitted an error chunk") : stopReason === "error" ? /* @__PURE__ */ new Error("Vercel AI SDK stream finished with an error") : void 0;
1006
+ await captureStreamGeneration({
1007
+ ...baseOptions,
1008
+ model: modelId,
1009
+ provider,
1010
+ input: mergedOptions.posthogPrivacyMode ? "" : mapVercelPrompt(params.prompt, phClient),
1011
+ output,
1012
+ latency,
1013
+ timeToFirstToken,
1014
+ baseURL,
1015
+ modelParameters: getModelParams(mergedParams),
1016
+ httpStatus: error ? void 0 : 200,
1017
+ usage: finalUsage,
1018
+ stopReason,
1019
+ error,
1020
+ tools: availableTools
1021
+ });
1022
+ })().catch((error) => {
1023
+ console.warn("[PostHog AI] Failed to capture Vercel stream telemetry:", error);
1024
+ });
1025
+ return finalizationPromise;
1026
+ };
1027
+ return {
1028
+ stream: new ReadableStream({
1029
+ async pull(controller) {
1030
+ let result;
1031
+ try {
1032
+ result = await reader.read();
1033
+ } catch (error) {
1034
+ finalize(error, true);
1035
+ controller.error(error);
1036
+ return;
1037
+ }
1038
+ if (result.done) {
1039
+ controller.close();
1040
+ finalize();
1041
+ return;
1042
+ }
1043
+ try {
1044
+ observeChunk(result.value);
1045
+ } catch {}
1046
+ controller.enqueue(result.value);
1047
+ },
1048
+ cancel(reason) {
1049
+ finalize(reason ?? /* @__PURE__ */ new Error("Vercel AI SDK stream was cancelled"), true);
1050
+ return reader.cancel(reason);
1051
+ }
1052
+ }, { highWaterMark: 0 }),
1053
+ ...rest
1054
+ };
1055
+ } catch (error) {
1056
+ await captureStreamGeneration({
1057
+ ...baseOptions,
1058
+ model: modelId,
1059
+ provider,
1060
+ input: mergedOptions.posthogPrivacyMode ? "" : mapVercelPrompt(params.prompt, phClient),
1061
+ output: [],
1062
+ latency: (Date.now() - startTime) / 1e3,
1063
+ baseURL,
1064
+ modelParameters: getModelParams(mergedParams),
1065
+ usage: {},
1066
+ error,
1067
+ tools: availableTools
1068
+ });
1069
+ throw error;
1070
+ }
1071
+ },
1072
+ writable: true,
1073
+ configurable: true,
1074
+ enumerable: false
1075
+ }
1076
+ });
1422
1077
  };
1423
-
1078
+ //#endregion
1424
1079
  exports.withTracing = wrapVercelLanguageModel;
1425
- //# sourceMappingURL=index.cjs.map
1080
+
1081
+ //# sourceMappingURL=index.cjs.map