@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.
- package/dist/adk/index.cjs +977 -0
- package/dist/adk/index.cjs.map +1 -0
- package/dist/adk/index.d.ts +149 -0
- package/dist/adk/index.mjs +976 -0
- package/dist/adk/index.mjs.map +1 -0
- package/dist/anthropic/index.cjs +927 -1104
- package/dist/anthropic/index.cjs.map +1 -1
- package/dist/anthropic/index.d.ts +34 -33
- package/dist/anthropic/index.mjs +899 -1095
- package/dist/anthropic/index.mjs.map +1 -1
- package/dist/gemini/index.cjs +867 -1112
- package/dist/gemini/index.cjs.map +1 -1
- package/dist/gemini/index.d.ts +38 -35
- package/dist/gemini/index.mjs +862 -1107
- package/dist/gemini/index.mjs.map +1 -1
- package/dist/index.cjs +1218 -1539
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +170 -157
- package/dist/index.mjs +1216 -1537
- package/dist/index.mjs.map +1 -1
- package/dist/langchain/index.cjs +851 -1029
- package/dist/langchain/index.cjs.map +1 -1
- package/dist/langchain/index.d.ts +75 -75
- package/dist/langchain/index.mjs +850 -1027
- package/dist/langchain/index.mjs.map +1 -1
- package/dist/langchain/middleware/index.cjs +1016 -1225
- package/dist/langchain/middleware/index.cjs.map +1 -1
- package/dist/langchain/middleware/index.d.ts +29 -25
- package/dist/langchain/middleware/index.mjs +1015 -1223
- package/dist/langchain/middleware/index.mjs.map +1 -1
- package/dist/openai/index.cjs +1990 -2516
- package/dist/openai/index.cjs.map +1 -1
- package/dist/openai/index.d.ts +106 -104
- package/dist/openai/index.mjs +1985 -2511
- package/dist/openai/index.mjs.map +1 -1
- package/dist/openai-agents/index.cjs +745 -827
- package/dist/openai-agents/index.cjs.map +1 -1
- package/dist/openai-agents/index.d.ts +48 -47
- package/dist/openai-agents/index.mjs +744 -825
- package/dist/openai-agents/index.mjs.map +1 -1
- package/dist/otel/index.cjs +427 -486
- package/dist/otel/index.cjs.map +1 -1
- package/dist/otel/index.d.ts +36 -35
- package/dist/otel/index.mjs +426 -484
- package/dist/otel/index.mjs.map +1 -1
- package/dist/vercel/index.cjs +992 -1336
- package/dist/vercel/index.cjs.map +1 -1
- package/dist/vercel/index.d.ts +21 -16
- package/dist/vercel/index.mjs +991 -1334
- package/dist/vercel/index.mjs.map +1 -1
- package/package.json +23 -12
package/dist/vercel/index.cjs
CHANGED
|
@@ -1,1425 +1,1081 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
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
|
-
|
|
8
|
+
const isObject = (value) => {
|
|
9
|
+
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
13
10
|
};
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
/** @internal */
|
|
18
|
-
|
|
11
|
+
//#endregion
|
|
12
|
+
//#region src/captureAiEvent.ts
|
|
19
13
|
/** @internal */
|
|
20
14
|
function isFullAiCaptureEnabled(client) {
|
|
21
|
-
|
|
15
|
+
return client?.enableFullAiCapture === true;
|
|
22
16
|
}
|
|
23
|
-
|
|
24
17
|
/** @internal */
|
|
25
18
|
function captureAiEvent(client, event) {
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
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
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
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
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
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
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
203
|
-
|
|
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
|
-
|
|
230
|
+
return !!posthogProperties && Object.keys(posthogProperties).some((key) => TOKEN_PROPERTY_KEYS.has(key));
|
|
207
231
|
}
|
|
208
232
|
function getTokensSource(posthogProperties) {
|
|
209
|
-
|
|
233
|
+
return hasTokenOverrides(posthogProperties) ? "passthrough" : "sdk";
|
|
210
234
|
}
|
|
211
|
-
|
|
212
|
-
|
|
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
|
-
|
|
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
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
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
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
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
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
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
|
-
|
|
283
|
+
return client.privacy_mode || privacyMode ? null : input;
|
|
264
284
|
};
|
|
265
285
|
function toSafeString(input) {
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
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
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
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
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
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
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
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
|
-
|
|
411
|
-
|
|
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
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
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
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
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
|
-
|
|
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
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
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
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
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
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
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
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
const
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
const
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
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
|
-
|
|
518
|
-
|
|
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
|
-
|
|
525
|
-
|
|
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
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
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
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
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
|
-
|
|
711
|
-
|
|
712
|
-
// Type guards
|
|
558
|
+
//#endregion
|
|
559
|
+
//#region src/vercel/middleware.ts
|
|
713
560
|
function isV3Model(model) {
|
|
714
|
-
|
|
561
|
+
return model.specificationVersion === "v3";
|
|
715
562
|
}
|
|
716
563
|
function getSpecificationVersion(model) {
|
|
717
|
-
|
|
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
|
-
|
|
727
|
-
|
|
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
|
-
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
|
|
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
|
-
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
|
|
780
|
-
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
|
|
784
|
-
|
|
785
|
-
|
|
786
|
-
|
|
787
|
-
|
|
788
|
-
|
|
789
|
-
|
|
790
|
-
|
|
791
|
-
|
|
792
|
-
|
|
793
|
-
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
|
|
797
|
-
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
|
|
808
|
-
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
|
|
814
|
-
|
|
815
|
-
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
|
|
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
|
-
|
|
856
|
-
|
|
857
|
-
|
|
858
|
-
|
|
859
|
-
|
|
860
|
-
|
|
861
|
-
|
|
862
|
-
|
|
863
|
-
|
|
864
|
-
|
|
865
|
-
|
|
866
|
-
|
|
867
|
-
|
|
868
|
-
|
|
869
|
-
|
|
870
|
-
|
|
871
|
-
|
|
872
|
-
|
|
873
|
-
|
|
874
|
-
|
|
875
|
-
|
|
876
|
-
|
|
877
|
-
|
|
878
|
-
|
|
879
|
-
|
|
880
|
-
|
|
881
|
-
|
|
882
|
-
|
|
883
|
-
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
|
|
887
|
-
|
|
888
|
-
|
|
889
|
-
|
|
890
|
-
|
|
891
|
-
|
|
892
|
-
|
|
893
|
-
|
|
894
|
-
|
|
895
|
-
|
|
896
|
-
|
|
897
|
-
|
|
898
|
-
|
|
899
|
-
|
|
900
|
-
|
|
901
|
-
|
|
902
|
-
|
|
903
|
-
|
|
904
|
-
|
|
905
|
-
|
|
906
|
-
|
|
907
|
-
|
|
908
|
-
|
|
909
|
-
|
|
910
|
-
|
|
911
|
-
|
|
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
|
-
|
|
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
|
-
|
|
936
|
-
|
|
937
|
-
|
|
938
|
-
|
|
939
|
-
|
|
940
|
-
|
|
941
|
-
const extractBaseURL = model => {
|
|
942
|
-
|
|
943
|
-
|
|
944
|
-
|
|
945
|
-
|
|
946
|
-
|
|
947
|
-
|
|
948
|
-
|
|
949
|
-
|
|
950
|
-
|
|
951
|
-
|
|
952
|
-
|
|
953
|
-
|
|
954
|
-
|
|
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
|
-
|
|
967
|
-
|
|
968
|
-
|
|
969
|
-
|
|
970
|
-
|
|
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
|
-
|
|
982
|
-
|
|
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
|
-
|
|
993
|
-
|
|
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
|
-
|
|
1003
|
-
const
|
|
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
|
-
|
|
1024
|
-
|
|
1025
|
-
|
|
1026
|
-
|
|
1027
|
-
|
|
1028
|
-
|
|
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
|
-
|
|
1046
|
-
|
|
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
|
-
|
|
1056
|
-
|
|
1057
|
-
|
|
1058
|
-
|
|
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
|
-
|
|
1067
|
-
|
|
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
|
-
|
|
1071
|
-
|
|
1072
|
-
|
|
1073
|
-
|
|
1074
|
-
|
|
1075
|
-
|
|
1076
|
-
|
|
1077
|
-
|
|
1078
|
-
|
|
1079
|
-
|
|
1080
|
-
|
|
1081
|
-
|
|
1082
|
-
|
|
1083
|
-
|
|
1084
|
-
|
|
1085
|
-
|
|
1086
|
-
|
|
1087
|
-
|
|
1088
|
-
|
|
1089
|
-
|
|
1090
|
-
|
|
1091
|
-
|
|
1092
|
-
|
|
1093
|
-
|
|
1094
|
-
|
|
1095
|
-
|
|
1096
|
-
|
|
1097
|
-
|
|
1098
|
-
|
|
1099
|
-
|
|
1100
|
-
|
|
1101
|
-
|
|
1102
|
-
|
|
1103
|
-
|
|
1104
|
-
|
|
1105
|
-
|
|
1106
|
-
|
|
1107
|
-
|
|
1108
|
-
|
|
1109
|
-
|
|
1110
|
-
|
|
1111
|
-
|
|
1112
|
-
|
|
1113
|
-
|
|
1114
|
-
|
|
1115
|
-
|
|
1116
|
-
|
|
1117
|
-
|
|
1118
|
-
|
|
1119
|
-
|
|
1120
|
-
|
|
1121
|
-
|
|
1122
|
-
|
|
1123
|
-
|
|
1124
|
-
|
|
1125
|
-
|
|
1126
|
-
|
|
1127
|
-
|
|
1128
|
-
|
|
1129
|
-
|
|
1130
|
-
|
|
1131
|
-
|
|
1132
|
-
|
|
1133
|
-
|
|
1134
|
-
|
|
1135
|
-
|
|
1136
|
-
|
|
1137
|
-
|
|
1138
|
-
|
|
1139
|
-
|
|
1140
|
-
|
|
1141
|
-
|
|
1142
|
-
|
|
1143
|
-
|
|
1144
|
-
|
|
1145
|
-
|
|
1146
|
-
|
|
1147
|
-
|
|
1148
|
-
|
|
1149
|
-
|
|
1150
|
-
|
|
1151
|
-
|
|
1152
|
-
|
|
1153
|
-
|
|
1154
|
-
|
|
1155
|
-
|
|
1156
|
-
|
|
1157
|
-
|
|
1158
|
-
|
|
1159
|
-
|
|
1160
|
-
|
|
1161
|
-
|
|
1162
|
-
|
|
1163
|
-
|
|
1164
|
-
|
|
1165
|
-
|
|
1166
|
-
|
|
1167
|
-
|
|
1168
|
-
|
|
1169
|
-
|
|
1170
|
-
|
|
1171
|
-
|
|
1172
|
-
|
|
1173
|
-
|
|
1174
|
-
|
|
1175
|
-
|
|
1176
|
-
|
|
1177
|
-
|
|
1178
|
-
|
|
1179
|
-
|
|
1180
|
-
|
|
1181
|
-
|
|
1182
|
-
|
|
1183
|
-
|
|
1184
|
-
|
|
1185
|
-
|
|
1186
|
-
|
|
1187
|
-
|
|
1188
|
-
|
|
1189
|
-
|
|
1190
|
-
|
|
1191
|
-
|
|
1192
|
-
|
|
1193
|
-
|
|
1194
|
-
|
|
1195
|
-
|
|
1196
|
-
|
|
1197
|
-
|
|
1198
|
-
|
|
1199
|
-
|
|
1200
|
-
|
|
1201
|
-
|
|
1202
|
-
|
|
1203
|
-
|
|
1204
|
-
|
|
1205
|
-
|
|
1206
|
-
|
|
1207
|
-
|
|
1208
|
-
|
|
1209
|
-
|
|
1210
|
-
|
|
1211
|
-
|
|
1212
|
-
|
|
1213
|
-
|
|
1214
|
-
|
|
1215
|
-
|
|
1216
|
-
|
|
1217
|
-
|
|
1218
|
-
|
|
1219
|
-
|
|
1220
|
-
|
|
1221
|
-
|
|
1222
|
-
|
|
1223
|
-
|
|
1224
|
-
|
|
1225
|
-
|
|
1226
|
-
|
|
1227
|
-
|
|
1228
|
-
|
|
1229
|
-
|
|
1230
|
-
|
|
1231
|
-
|
|
1232
|
-
|
|
1233
|
-
|
|
1234
|
-
|
|
1235
|
-
|
|
1236
|
-
|
|
1237
|
-
|
|
1238
|
-
|
|
1239
|
-
|
|
1240
|
-
|
|
1241
|
-
|
|
1242
|
-
|
|
1243
|
-
|
|
1244
|
-
|
|
1245
|
-
|
|
1246
|
-
|
|
1247
|
-
|
|
1248
|
-
|
|
1249
|
-
|
|
1250
|
-
|
|
1251
|
-
|
|
1252
|
-
|
|
1253
|
-
|
|
1254
|
-
|
|
1255
|
-
|
|
1256
|
-
|
|
1257
|
-
|
|
1258
|
-
|
|
1259
|
-
|
|
1260
|
-
|
|
1261
|
-
|
|
1262
|
-
|
|
1263
|
-
|
|
1264
|
-
|
|
1265
|
-
|
|
1266
|
-
|
|
1267
|
-
|
|
1268
|
-
|
|
1269
|
-
|
|
1270
|
-
|
|
1271
|
-
|
|
1272
|
-
|
|
1273
|
-
|
|
1274
|
-
|
|
1275
|
-
|
|
1276
|
-
|
|
1277
|
-
|
|
1278
|
-
|
|
1279
|
-
|
|
1280
|
-
|
|
1281
|
-
|
|
1282
|
-
|
|
1283
|
-
|
|
1284
|
-
|
|
1285
|
-
|
|
1286
|
-
|
|
1287
|
-
|
|
1288
|
-
|
|
1289
|
-
|
|
1290
|
-
|
|
1291
|
-
|
|
1292
|
-
|
|
1293
|
-
|
|
1294
|
-
|
|
1295
|
-
|
|
1296
|
-
|
|
1297
|
-
|
|
1298
|
-
|
|
1299
|
-
|
|
1300
|
-
|
|
1301
|
-
|
|
1302
|
-
|
|
1303
|
-
|
|
1304
|
-
|
|
1305
|
-
|
|
1306
|
-
|
|
1307
|
-
|
|
1308
|
-
|
|
1309
|
-
|
|
1310
|
-
|
|
1311
|
-
|
|
1312
|
-
|
|
1313
|
-
|
|
1314
|
-
|
|
1315
|
-
|
|
1316
|
-
|
|
1317
|
-
|
|
1318
|
-
|
|
1319
|
-
|
|
1320
|
-
|
|
1321
|
-
|
|
1322
|
-
|
|
1323
|
-
|
|
1324
|
-
|
|
1325
|
-
|
|
1326
|
-
|
|
1327
|
-
|
|
1328
|
-
|
|
1329
|
-
|
|
1330
|
-
|
|
1331
|
-
|
|
1332
|
-
|
|
1333
|
-
|
|
1334
|
-
|
|
1335
|
-
|
|
1336
|
-
|
|
1337
|
-
|
|
1338
|
-
|
|
1339
|
-
|
|
1340
|
-
|
|
1341
|
-
|
|
1342
|
-
|
|
1343
|
-
|
|
1344
|
-
|
|
1345
|
-
|
|
1346
|
-
|
|
1347
|
-
|
|
1348
|
-
|
|
1349
|
-
|
|
1350
|
-
|
|
1351
|
-
|
|
1352
|
-
|
|
1353
|
-
|
|
1354
|
-
|
|
1355
|
-
|
|
1356
|
-
|
|
1357
|
-
|
|
1358
|
-
|
|
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
|
-
|
|
1080
|
+
|
|
1081
|
+
//# sourceMappingURL=index.cjs.map
|