@posthog/ai 8.10.0 → 8.10.2
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 +908 -1198
- package/dist/adk/index.cjs.map +1 -1
- package/dist/adk/index.d.ts +109 -109
- package/dist/adk/index.mjs +907 -1196
- package/dist/adk/index.mjs.map +1 -1
- package/dist/anthropic/index.cjs +927 -1111
- package/dist/anthropic/index.cjs.map +1 -1
- package/dist/anthropic/index.d.ts +34 -33
- package/dist/anthropic/index.mjs +899 -1102
- package/dist/anthropic/index.mjs.map +1 -1
- package/dist/gemini/index.cjs +863 -1108
- package/dist/gemini/index.cjs.map +1 -1
- package/dist/gemini/index.d.ts +38 -35
- package/dist/gemini/index.mjs +858 -1103
- package/dist/gemini/index.mjs.map +1 -1
- package/dist/index.cjs +1218 -1546
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +170 -163
- package/dist/index.mjs +1216 -1544
- 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 -2523
- package/dist/openai/index.cjs.map +1 -1
- package/dist/openai/index.d.ts +106 -104
- package/dist/openai/index.mjs +1985 -2518
- 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 -1343
- package/dist/vercel/index.cjs.map +1 -1
- package/dist/vercel/index.d.ts +21 -16
- package/dist/vercel/index.mjs +991 -1341
- package/dist/vercel/index.mjs.map +1 -1
- package/package.json +15 -14
package/dist/vercel/index.mjs
CHANGED
|
@@ -1,1430 +1,1080 @@
|
|
|
1
|
-
import { v4 } from
|
|
2
|
-
import { toJsonSafeValue, uuidv7 } from
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
const isString = value => {
|
|
7
|
-
return typeof value === 'string';
|
|
1
|
+
import { v4 } from "uuid";
|
|
2
|
+
import { toJsonSafeValue, uuidv7 } from "@posthog/core";
|
|
3
|
+
//#region src/typeGuards.ts
|
|
4
|
+
const isString = (value) => {
|
|
5
|
+
return typeof value === "string";
|
|
8
6
|
};
|
|
9
|
-
const isObject = value => {
|
|
10
|
-
|
|
7
|
+
const isObject = (value) => {
|
|
8
|
+
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
11
9
|
};
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
/** @internal */
|
|
16
|
-
|
|
10
|
+
//#endregion
|
|
11
|
+
//#region src/captureAiEvent.ts
|
|
17
12
|
/** @internal */
|
|
18
13
|
function isFullAiCaptureEnabled(client) {
|
|
19
|
-
|
|
14
|
+
return client?.enableFullAiCapture === true;
|
|
20
15
|
}
|
|
21
|
-
|
|
22
16
|
/** @internal */
|
|
23
17
|
function captureAiEvent(client, event) {
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
18
|
+
if (isFullAiCaptureEnabled(client) && typeof client.captureAi === "function") {
|
|
19
|
+
client.captureAi(event);
|
|
20
|
+
return;
|
|
21
|
+
}
|
|
22
|
+
client.capture(event);
|
|
29
23
|
}
|
|
30
|
-
|
|
31
24
|
/** @internal */
|
|
32
25
|
async function captureAiEventImmediate(client, event) {
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
26
|
+
if (isFullAiCaptureEnabled(client) && typeof client.captureAiImmediate === "function") {
|
|
27
|
+
await client.captureAiImmediate(event);
|
|
28
|
+
return;
|
|
29
|
+
}
|
|
30
|
+
await client.captureImmediate(event);
|
|
38
31
|
}
|
|
39
|
-
|
|
32
|
+
//#endregion
|
|
33
|
+
//#region src/sanitization/base64_recognizer.ts
|
|
40
34
|
const DATA_URL_PREFIX_RE = /^data:([^;,\s]+)(?:;[^;,\s]+)*;base64,/i;
|
|
41
35
|
const BASE64_ALPHABET_RE = /^[A-Za-z0-9+/_=-]+$/;
|
|
42
|
-
|
|
43
|
-
|
|
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
|
-
|
|
36
|
+
var Base64Recognizer = class {
|
|
37
|
+
recognize(value, minLength) {
|
|
38
|
+
const dataUrl = DATA_URL_PREFIX_RE.exec(value);
|
|
39
|
+
if (dataUrl) return {
|
|
40
|
+
kind: "data-url",
|
|
41
|
+
mediaType: dataUrl[1]
|
|
42
|
+
};
|
|
43
|
+
if (value.length < minLength) return { kind: "none" };
|
|
44
|
+
const confidencePrefix = value.slice(0, minLength);
|
|
45
|
+
if (BASE64_ALPHABET_RE.test(confidencePrefix)) return { kind: "raw" };
|
|
46
|
+
else return { kind: "none" };
|
|
47
|
+
}
|
|
48
|
+
};
|
|
49
|
+
//#endregion
|
|
50
|
+
//#region src/sanitization/media_type_context.ts
|
|
51
|
+
const MIME_HINT_KEYS = [
|
|
52
|
+
"mediaType",
|
|
53
|
+
"media_type",
|
|
54
|
+
"mimeType",
|
|
55
|
+
"mime_type"
|
|
56
|
+
];
|
|
57
|
+
const STRONG_CONTEXT_KEYS = /* @__PURE__ */ new Set([
|
|
58
|
+
"data",
|
|
59
|
+
"file_data",
|
|
60
|
+
"fileData",
|
|
61
|
+
"image_url",
|
|
62
|
+
"imageUrl",
|
|
63
|
+
"video_url",
|
|
64
|
+
"videoUrl",
|
|
65
|
+
"audio",
|
|
66
|
+
"audio_data",
|
|
67
|
+
"audioData",
|
|
68
|
+
"inline_data",
|
|
69
|
+
"inlineData",
|
|
70
|
+
"source",
|
|
71
|
+
"result"
|
|
72
|
+
]);
|
|
73
|
+
const STRONG_CONTEXT_TYPES = /* @__PURE__ */ new Set([
|
|
74
|
+
"image",
|
|
75
|
+
"image_url",
|
|
76
|
+
"input_image",
|
|
77
|
+
"audio",
|
|
78
|
+
"input_audio",
|
|
79
|
+
"video",
|
|
80
|
+
"video_url",
|
|
81
|
+
"file",
|
|
82
|
+
"input_file",
|
|
83
|
+
"document",
|
|
84
|
+
"media",
|
|
85
|
+
"file-data"
|
|
86
|
+
]);
|
|
87
|
+
const FILE_FAMILY_TYPES = /* @__PURE__ */ new Set([
|
|
88
|
+
"file",
|
|
89
|
+
"input_file",
|
|
90
|
+
"document",
|
|
91
|
+
"media",
|
|
92
|
+
"file-data"
|
|
93
|
+
]);
|
|
94
|
+
const KNOWN_AUDIO_FORMATS = /* @__PURE__ */ new Set([
|
|
95
|
+
"wav",
|
|
96
|
+
"mp3",
|
|
97
|
+
"ogg",
|
|
98
|
+
"flac",
|
|
99
|
+
"m4a",
|
|
100
|
+
"aac",
|
|
101
|
+
"webm"
|
|
102
|
+
]);
|
|
103
|
+
var MediaTypeContext = class MediaTypeContext {
|
|
104
|
+
static {
|
|
105
|
+
this.EMPTY = new MediaTypeContext(void 0, void 0);
|
|
106
|
+
}
|
|
107
|
+
constructor(parent, key, explicitMediaType) {
|
|
108
|
+
this.parent = parent;
|
|
109
|
+
this.key = key;
|
|
110
|
+
this.explicitMediaType = explicitMediaType;
|
|
111
|
+
}
|
|
112
|
+
inferMediaType() {
|
|
113
|
+
return this.inferFromSiblingMime() ?? this.inferFromSiblingFormat() ?? this.inferFromParentType() ?? this.inferFromKey();
|
|
114
|
+
}
|
|
115
|
+
inferFromSiblingMime() {
|
|
116
|
+
if (this.explicitMediaType) return this.explicitMediaType;
|
|
117
|
+
if (!this.parent) return void 0;
|
|
118
|
+
for (const hint of MIME_HINT_KEYS) {
|
|
119
|
+
const v = this.parent[hint];
|
|
120
|
+
if (typeof v === "string") return v;
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
inferFromSiblingFormat() {
|
|
124
|
+
if (!this.parent) return void 0;
|
|
125
|
+
const fmt = this.parent.format;
|
|
126
|
+
if (typeof fmt === "string" && KNOWN_AUDIO_FORMATS.has(fmt.toLowerCase())) return `audio/${fmt.toLowerCase()}`;
|
|
127
|
+
}
|
|
128
|
+
inferFromParentType() {
|
|
129
|
+
if (!this.parent) return void 0;
|
|
130
|
+
const t = this.parent.type;
|
|
131
|
+
if (typeof t !== "string") return void 0;
|
|
132
|
+
if (t === "image" || t === "image_url" || t === "input_image") return "image";
|
|
133
|
+
if (t === "audio" || t === "input_audio") return "audio";
|
|
134
|
+
if (t === "video" || t === "video_url") return "video";
|
|
135
|
+
if (FILE_FAMILY_TYPES.has(t)) return "application/octet-stream";
|
|
136
|
+
}
|
|
137
|
+
inferFromKey() {
|
|
138
|
+
if (!this.key) return void 0;
|
|
139
|
+
const key = this.key.toLowerCase();
|
|
140
|
+
if (key.includes("audio")) return "audio";
|
|
141
|
+
if (key.includes("video")) return "video";
|
|
142
|
+
if (key.includes("image")) return "image";
|
|
143
|
+
if (key.includes("file") || key.includes("document")) return "application/octet-stream";
|
|
144
|
+
}
|
|
145
|
+
hasExplicitBinaryMediaType() {
|
|
146
|
+
if (!this.explicitMediaType && (!this.parent || !this.key || !STRONG_CONTEXT_KEYS.has(this.key))) return false;
|
|
147
|
+
const mediaType = this.inferFromSiblingMime();
|
|
148
|
+
return mediaType !== void 0 && !mediaType.toLowerCase().startsWith("text/");
|
|
149
|
+
}
|
|
150
|
+
signalsBinary() {
|
|
151
|
+
if (this.explicitMediaType) return true;
|
|
152
|
+
if (this.parent) {
|
|
153
|
+
for (const hint of MIME_HINT_KEYS) if (typeof this.parent[hint] === "string") return true;
|
|
154
|
+
const fmt = this.parent.format;
|
|
155
|
+
if (typeof fmt === "string" && KNOWN_AUDIO_FORMATS.has(fmt.toLowerCase())) return true;
|
|
156
|
+
const t = this.parent.type;
|
|
157
|
+
if (typeof t === "string" && STRONG_CONTEXT_TYPES.has(t)) return true;
|
|
158
|
+
}
|
|
159
|
+
if (this.key && STRONG_CONTEXT_KEYS.has(this.key)) return true;
|
|
160
|
+
return false;
|
|
161
|
+
}
|
|
162
|
+
};
|
|
163
|
+
//#endregion
|
|
164
|
+
//#region src/sanitization/binary_content_redactor.ts
|
|
137
165
|
const STRONG_CONTEXT_MIN_LENGTH = 64;
|
|
138
166
|
const WEAK_CONTEXT_MIN_LENGTH = 1024;
|
|
139
|
-
|
|
140
|
-
|
|
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
|
-
return value;
|
|
181
|
-
}
|
|
182
|
-
}
|
|
183
|
-
placeholderFor(mediaType) {
|
|
184
|
-
if (!mediaType) return '[base64 redacted]';
|
|
185
|
-
if (mediaType === 'application/octet-stream') return '[base64 file redacted]';
|
|
186
|
-
return `[base64 ${mediaType} redacted]`;
|
|
187
|
-
}
|
|
188
|
-
}
|
|
189
|
-
|
|
167
|
+
var BinaryContentRedactor = class {
|
|
168
|
+
constructor(recognizer = new Base64Recognizer()) {
|
|
169
|
+
this.recognizer = recognizer;
|
|
170
|
+
this.visited = /* @__PURE__ */ new WeakSet();
|
|
171
|
+
}
|
|
172
|
+
redact(value, mediaType) {
|
|
173
|
+
this.visited = /* @__PURE__ */ new WeakSet();
|
|
174
|
+
return this.walk(value, mediaType ? new MediaTypeContext(void 0, void 0, mediaType) : MediaTypeContext.EMPTY);
|
|
175
|
+
}
|
|
176
|
+
walk(value, ctx) {
|
|
177
|
+
if (value === null || value === void 0) return value;
|
|
178
|
+
if (typeof value === "string") return this.redactString(value, ctx);
|
|
179
|
+
if (typeof value !== "object") return value;
|
|
180
|
+
if (typeof Uint8Array !== "undefined" && value instanceof Uint8Array) return this.placeholderFor(ctx.inferMediaType());
|
|
181
|
+
if (this.visited.has(value)) return null;
|
|
182
|
+
this.visited.add(value);
|
|
183
|
+
if (Array.isArray(value)) return value.map((item) => this.walk(item, ctx));
|
|
184
|
+
const obj = value;
|
|
185
|
+
const out = {};
|
|
186
|
+
for (const k of Object.keys(obj)) out[k] = this.walk(obj[k], new MediaTypeContext(obj, k));
|
|
187
|
+
return out;
|
|
188
|
+
}
|
|
189
|
+
redactString(value, ctx) {
|
|
190
|
+
const hasExplicitBinaryMediaType = ctx.hasExplicitBinaryMediaType();
|
|
191
|
+
const recognitionValue = hasExplicitBinaryMediaType ? value.replace(/[\r\n]/g, "") : value;
|
|
192
|
+
const minLength = hasExplicitBinaryMediaType ? Math.min(recognitionValue.length, STRONG_CONTEXT_MIN_LENGTH) : ctx.signalsBinary() ? STRONG_CONTEXT_MIN_LENGTH : WEAK_CONTEXT_MIN_LENGTH;
|
|
193
|
+
const recognition = this.recognizer.recognize(recognitionValue, minLength);
|
|
194
|
+
switch (recognition.kind) {
|
|
195
|
+
case "data-url": return this.placeholderFor(recognition.mediaType);
|
|
196
|
+
case "raw": return this.placeholderFor(ctx.inferMediaType());
|
|
197
|
+
case "none": return value;
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
placeholderFor(mediaType) {
|
|
201
|
+
if (!mediaType) return "[base64 redacted]";
|
|
202
|
+
if (mediaType === "application/octet-stream") return "[base64 file redacted]";
|
|
203
|
+
return `[base64 ${mediaType} redacted]`;
|
|
204
|
+
}
|
|
205
|
+
};
|
|
206
|
+
//#endregion
|
|
207
|
+
//#region src/sanitization.ts
|
|
190
208
|
const redactor = new BinaryContentRedactor();
|
|
191
209
|
function redactBase64DataUrl(str, mediaType) {
|
|
192
|
-
|
|
210
|
+
return redactor.redact(str, mediaType);
|
|
193
211
|
}
|
|
194
212
|
const sanitize = (data, client) => isFullAiCaptureEnabled(client) ? data : redactor.redact(data);
|
|
195
213
|
const sanitizeVercel = (data, client) => sanitize(data, client);
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
214
|
+
//#endregion
|
|
215
|
+
//#region src/utils.ts
|
|
216
|
+
const TOKEN_PROPERTY_KEYS = /* @__PURE__ */ new Set([
|
|
217
|
+
"$ai_input_tokens",
|
|
218
|
+
"$ai_output_tokens",
|
|
219
|
+
"$ai_cache_read_input_tokens",
|
|
220
|
+
"$ai_cache_creation_input_tokens",
|
|
221
|
+
"$ai_total_tokens",
|
|
222
|
+
"$ai_reasoning_tokens"
|
|
223
|
+
]);
|
|
199
224
|
/**
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
225
|
+
* Whether the caller supplied their own token counts, which override the ones the SDK
|
|
226
|
+
* derived from the provider response.
|
|
227
|
+
*/
|
|
203
228
|
function hasTokenOverrides(posthogProperties) {
|
|
204
|
-
|
|
229
|
+
return !!posthogProperties && Object.keys(posthogProperties).some((key) => TOKEN_PROPERTY_KEYS.has(key));
|
|
205
230
|
}
|
|
206
231
|
function getTokensSource(posthogProperties) {
|
|
207
|
-
|
|
232
|
+
return hasTokenOverrides(posthogProperties) ? "passthrough" : "sdk";
|
|
208
233
|
}
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
const MAX_OUTPUT_SIZE = 200000;
|
|
212
|
-
const STRING_FORMAT = 'utf8';
|
|
213
|
-
|
|
214
|
-
// Reused across calls to avoid per-invocation allocation; truncate() runs
|
|
215
|
-
// hundreds of times for prompts with many parts.
|
|
234
|
+
const MAX_OUTPUT_SIZE = 2e5;
|
|
235
|
+
const STRING_FORMAT = "utf8";
|
|
216
236
|
const sharedTextEncoder = new TextEncoder();
|
|
217
|
-
const sharedTextDecoder = new TextDecoder(STRING_FORMAT, {
|
|
218
|
-
|
|
219
|
-
});
|
|
220
|
-
const utf8ByteLength = str => sharedTextEncoder.encode(str).byteLength;
|
|
221
|
-
|
|
237
|
+
const sharedTextDecoder = new TextDecoder(STRING_FORMAT, { fatal: false });
|
|
238
|
+
const utf8ByteLength = (str) => sharedTextEncoder.encode(str).byteLength;
|
|
222
239
|
/**
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
240
|
+
* Safely converts content to a string, preserving structure for objects/arrays.
|
|
241
|
+
* - If content is already a string, returns it as-is
|
|
242
|
+
* - If content is an object or array, stringifies it with JSON.stringify to preserve structure
|
|
243
|
+
* - Otherwise, converts to string with String()
|
|
244
|
+
*
|
|
245
|
+
* This prevents the "[object Object]" bug when objects are naively converted to strings.
|
|
246
|
+
*
|
|
247
|
+
* @param content - The content to convert to a string
|
|
248
|
+
* @returns A string representation that preserves structure for complex types
|
|
249
|
+
*/
|
|
233
250
|
function toContentString(content) {
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
// Fallback for circular refs, BigInt, or objects with throwing toJSON
|
|
242
|
-
return String(content);
|
|
243
|
-
}
|
|
244
|
-
}
|
|
245
|
-
return String(content);
|
|
251
|
+
if (typeof content === "string") return content;
|
|
252
|
+
if (content !== void 0 && content !== null && typeof content === "object") try {
|
|
253
|
+
return JSON.stringify(content);
|
|
254
|
+
} catch {
|
|
255
|
+
return String(content);
|
|
256
|
+
}
|
|
257
|
+
return String(content);
|
|
246
258
|
}
|
|
247
259
|
const getModelParams = (params, responseServiceTier) => {
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
260
|
+
if (!params) return {};
|
|
261
|
+
const modelParams = {};
|
|
262
|
+
for (const key of [
|
|
263
|
+
"temperature",
|
|
264
|
+
"max_tokens",
|
|
265
|
+
"max_completion_tokens",
|
|
266
|
+
"top_p",
|
|
267
|
+
"frequency_penalty",
|
|
268
|
+
"presence_penalty",
|
|
269
|
+
"n",
|
|
270
|
+
"stop",
|
|
271
|
+
"stream",
|
|
272
|
+
"streaming",
|
|
273
|
+
"language",
|
|
274
|
+
"response_format",
|
|
275
|
+
"timestamp_granularities",
|
|
276
|
+
"service_tier"
|
|
277
|
+
]) if (key in params && params[key] !== void 0) modelParams[key] = params[key];
|
|
278
|
+
if (responseServiceTier != null) modelParams.service_tier = responseServiceTier;
|
|
279
|
+
return modelParams;
|
|
259
280
|
};
|
|
260
281
|
const withPrivacyMode = (client, privacyMode, input) => {
|
|
261
|
-
|
|
282
|
+
return client.privacy_mode || privacyMode ? null : input;
|
|
262
283
|
};
|
|
263
284
|
function toSafeString(input) {
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
} catch {
|
|
273
|
-
console.warn('Failed to stringify input', input);
|
|
274
|
-
return '';
|
|
275
|
-
}
|
|
285
|
+
if (input === void 0 || input === null) return "";
|
|
286
|
+
if (typeof input === "string") return input;
|
|
287
|
+
try {
|
|
288
|
+
return JSON.stringify(input);
|
|
289
|
+
} catch {
|
|
290
|
+
console.warn("Failed to stringify input", input);
|
|
291
|
+
return "";
|
|
292
|
+
}
|
|
276
293
|
}
|
|
277
294
|
const truncate = (input, client) => {
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
const buffer = sharedTextEncoder.encode(str);
|
|
288
|
-
if (buffer.length <= MAX_OUTPUT_SIZE) {
|
|
289
|
-
// Ensure STRING_FORMAT is respected
|
|
290
|
-
return sharedTextDecoder.decode(buffer);
|
|
291
|
-
}
|
|
292
|
-
|
|
293
|
-
// Truncate the buffer and ensure a valid string is returned.
|
|
294
|
-
// fatal: false means we get U+FFFD at the end if truncation broke the encoding.
|
|
295
|
-
const truncatedBuffer = buffer.slice(0, MAX_OUTPUT_SIZE);
|
|
296
|
-
let truncatedStr = sharedTextDecoder.decode(truncatedBuffer);
|
|
297
|
-
if (truncatedStr.endsWith('\uFFFD')) {
|
|
298
|
-
truncatedStr = truncatedStr.slice(0, -1);
|
|
299
|
-
}
|
|
300
|
-
return `${truncatedStr}... [truncated]`;
|
|
295
|
+
const str = toSafeString(input);
|
|
296
|
+
if (str === "") return "";
|
|
297
|
+
if (isFullAiCaptureEnabled(client)) return str;
|
|
298
|
+
const buffer = sharedTextEncoder.encode(str);
|
|
299
|
+
if (buffer.length <= 2e5) return sharedTextDecoder.decode(buffer);
|
|
300
|
+
const truncatedBuffer = buffer.slice(0, MAX_OUTPUT_SIZE);
|
|
301
|
+
let truncatedStr = sharedTextDecoder.decode(truncatedBuffer);
|
|
302
|
+
if (truncatedStr.endsWith("�")) truncatedStr = truncatedStr.slice(0, -1);
|
|
303
|
+
return `${truncatedStr}... [truncated]`;
|
|
301
304
|
};
|
|
302
|
-
|
|
303
305
|
/**
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
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
|
+
*/
|
|
313
315
|
function calculateWebSearchCount(result) {
|
|
314
|
-
|
|
315
|
-
|
|
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
|
-
if (typeof content === 'object' && content !== null && 'annotations' in content) {
|
|
358
|
-
const annotations = content.annotations;
|
|
359
|
-
if (Array.isArray(annotations)) {
|
|
360
|
-
const hasUrlCitation = annotations.some(ann => {
|
|
361
|
-
return typeof ann === 'object' && ann !== null && 'type' in ann && ann.type === 'url_citation';
|
|
362
|
-
});
|
|
363
|
-
if (hasUrlCitation) {
|
|
364
|
-
return 1;
|
|
365
|
-
}
|
|
366
|
-
}
|
|
367
|
-
}
|
|
368
|
-
}
|
|
369
|
-
}
|
|
370
|
-
}
|
|
371
|
-
|
|
372
|
-
// Check for annotations in output[].content[] (OpenAI Responses API)
|
|
373
|
-
if ('output' in result && Array.isArray(result.output)) {
|
|
374
|
-
for (const item of result.output) {
|
|
375
|
-
if (typeof item === 'object' && item !== null && 'content' in item) {
|
|
376
|
-
const content = item.content;
|
|
377
|
-
if (Array.isArray(content)) {
|
|
378
|
-
for (const contentItem of content) {
|
|
379
|
-
if (typeof contentItem === 'object' && contentItem !== null && 'annotations' in contentItem) {
|
|
380
|
-
const annotations = contentItem.annotations;
|
|
381
|
-
if (Array.isArray(annotations)) {
|
|
382
|
-
const hasUrlCitation = annotations.some(ann => {
|
|
383
|
-
return typeof ann === 'object' && ann !== null && 'type' in ann && ann.type === 'url_citation';
|
|
384
|
-
});
|
|
385
|
-
if (hasUrlCitation) {
|
|
386
|
-
return 1;
|
|
387
|
-
}
|
|
388
|
-
}
|
|
389
|
-
}
|
|
390
|
-
}
|
|
391
|
-
}
|
|
392
|
-
}
|
|
393
|
-
}
|
|
394
|
-
}
|
|
395
|
-
|
|
396
|
-
// Check for grounding_metadata (Gemini)
|
|
397
|
-
if ('candidates' in result && Array.isArray(result.candidates)) {
|
|
398
|
-
for (const candidate of result.candidates) {
|
|
399
|
-
if (typeof candidate === 'object' && candidate !== null && 'grounding_metadata' in candidate && candidate.grounding_metadata) {
|
|
400
|
-
return 1;
|
|
401
|
-
}
|
|
402
|
-
}
|
|
403
|
-
}
|
|
404
|
-
return 0;
|
|
316
|
+
if (!result || typeof result !== "object") return 0;
|
|
317
|
+
if ("output" in result && Array.isArray(result.output)) {
|
|
318
|
+
let count = 0;
|
|
319
|
+
for (const item of result.output) if (typeof item === "object" && item !== null && "type" in item && item.type === "web_search_call") count++;
|
|
320
|
+
if (count > 0) return count;
|
|
321
|
+
}
|
|
322
|
+
if ("citations" in result && Array.isArray(result.citations) && result.citations.length > 0) return 1;
|
|
323
|
+
if ("search_results" in result && Array.isArray(result.search_results) && result.search_results.length > 0) return 1;
|
|
324
|
+
if ("usage" in result && typeof result.usage === "object" && result.usage !== null) {
|
|
325
|
+
if ("search_context_size" in result.usage && result.usage.search_context_size) return 1;
|
|
326
|
+
}
|
|
327
|
+
if ("choices" in result && Array.isArray(result.choices)) {
|
|
328
|
+
for (const choice of result.choices) if (typeof choice === "object" && choice !== null) {
|
|
329
|
+
const content = ("message" in choice ? choice.message : null) || ("delta" in choice ? choice.delta : null);
|
|
330
|
+
if (typeof content === "object" && content !== null && "annotations" in content) {
|
|
331
|
+
const annotations = content.annotations;
|
|
332
|
+
if (Array.isArray(annotations)) {
|
|
333
|
+
if (annotations.some((ann) => {
|
|
334
|
+
return typeof ann === "object" && ann !== null && "type" in ann && ann.type === "url_citation";
|
|
335
|
+
})) return 1;
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
if ("output" in result && Array.isArray(result.output)) {
|
|
341
|
+
for (const item of result.output) if (typeof item === "object" && item !== null && "content" in item) {
|
|
342
|
+
const content = item.content;
|
|
343
|
+
if (Array.isArray(content)) {
|
|
344
|
+
for (const contentItem of content) if (typeof contentItem === "object" && contentItem !== null && "annotations" in contentItem) {
|
|
345
|
+
const annotations = contentItem.annotations;
|
|
346
|
+
if (Array.isArray(annotations)) {
|
|
347
|
+
if (annotations.some((ann) => {
|
|
348
|
+
return typeof ann === "object" && ann !== null && "type" in ann && ann.type === "url_citation";
|
|
349
|
+
})) return 1;
|
|
350
|
+
}
|
|
351
|
+
}
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
}
|
|
355
|
+
if ("candidates" in result && Array.isArray(result.candidates)) {
|
|
356
|
+
for (const candidate of result.candidates) if (typeof candidate === "object" && candidate !== null && "grounding_metadata" in candidate && candidate.grounding_metadata) return 1;
|
|
357
|
+
}
|
|
358
|
+
return 0;
|
|
405
359
|
}
|
|
406
|
-
|
|
407
360
|
/**
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
361
|
+
* Extract available tool calls from the request parameters.
|
|
362
|
+
* These are the tools provided to the LLM, not the tool calls in the response.
|
|
363
|
+
*/
|
|
411
364
|
const extractAvailableToolCalls = (provider, params) => {
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
365
|
+
if (provider === "anthropic") {
|
|
366
|
+
if (params.tools) return params.tools;
|
|
367
|
+
return null;
|
|
368
|
+
} else if (provider === "gemini") {
|
|
369
|
+
if (params.config && params.config.tools) return params.config.tools;
|
|
370
|
+
return null;
|
|
371
|
+
} else if (provider === "openai") {
|
|
372
|
+
if (params.tools) return params.tools;
|
|
373
|
+
return null;
|
|
374
|
+
} else if (provider === "vercel") {
|
|
375
|
+
if (params.tools) return params.tools;
|
|
376
|
+
return null;
|
|
377
|
+
}
|
|
378
|
+
return null;
|
|
418
379
|
};
|
|
419
|
-
let AIEvent = /*#__PURE__*/function (AIEvent) {
|
|
420
|
-
AIEvent["Generation"] = "$ai_generation";
|
|
421
|
-
AIEvent["Embedding"] = "$ai_embedding";
|
|
422
|
-
return AIEvent;
|
|
423
|
-
}({});
|
|
424
380
|
function sanitizeValues(obj) {
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
return new TextDecoder().decode(new TextEncoder().encode(jsonSafe));
|
|
432
|
-
} else if (Array.isArray(jsonSafe)) {
|
|
433
|
-
return jsonSafe.map(sanitizeValues);
|
|
434
|
-
} else if (jsonSafe && typeof jsonSafe === 'object') {
|
|
435
|
-
return Object.fromEntries(Object.entries(jsonSafe).map(([k, v]) => [k, sanitizeValues(v)]));
|
|
436
|
-
}
|
|
437
|
-
return jsonSafe;
|
|
381
|
+
if (obj === void 0 || obj === null) return obj;
|
|
382
|
+
const jsonSafe = JSON.parse(JSON.stringify(obj));
|
|
383
|
+
if (typeof jsonSafe === "string") return new TextDecoder().decode(new TextEncoder().encode(jsonSafe));
|
|
384
|
+
else if (Array.isArray(jsonSafe)) return jsonSafe.map(sanitizeValues);
|
|
385
|
+
else if (jsonSafe && typeof jsonSafe === "object") return Object.fromEntries(Object.entries(jsonSafe).map(([k, v]) => [k, sanitizeValues(v)]));
|
|
386
|
+
return jsonSafe;
|
|
438
387
|
}
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
388
|
+
//#endregion
|
|
389
|
+
//#region package.json
|
|
390
|
+
var version = "8.10.2";
|
|
391
|
+
//#endregion
|
|
392
|
+
//#region src/serializeError.ts
|
|
442
393
|
const DEFAULT_MAX_DEPTH = 3;
|
|
443
394
|
const MAX_STACK_LINES = 20;
|
|
444
395
|
function serializeError(value, depth = DEFAULT_MAX_DEPTH) {
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
out.cause = serializeError(value.cause, depth - 1);
|
|
459
|
-
}
|
|
460
|
-
return out;
|
|
461
|
-
}
|
|
462
|
-
if (Array.isArray(value)) {
|
|
463
|
-
return value.map(item => serializeError(item, depth - 1));
|
|
464
|
-
}
|
|
465
|
-
return value;
|
|
396
|
+
if (depth < 0 || value === null || typeof value !== "object") return value;
|
|
397
|
+
if (value instanceof Error) {
|
|
398
|
+
const out = {
|
|
399
|
+
name: value.name,
|
|
400
|
+
message: value.message,
|
|
401
|
+
stack: truncateStack(value.stack)
|
|
402
|
+
};
|
|
403
|
+
for (const key of Object.keys(value)) out[key] = serializeError(value[key], depth - 1);
|
|
404
|
+
if (value.cause !== void 0) out.cause = serializeError(value.cause, depth - 1);
|
|
405
|
+
return out;
|
|
406
|
+
}
|
|
407
|
+
if (Array.isArray(value)) return value.map((item) => serializeError(item, depth - 1));
|
|
408
|
+
return value;
|
|
466
409
|
}
|
|
467
410
|
function stringifyError(error) {
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
return JSON.stringify({
|
|
478
|
-
message: String(error)
|
|
479
|
-
});
|
|
480
|
-
}
|
|
411
|
+
try {
|
|
412
|
+
return JSON.stringify(sanitizeValues(serializeError(error)));
|
|
413
|
+
} catch {
|
|
414
|
+
if (error instanceof Error) return JSON.stringify({
|
|
415
|
+
name: error.name,
|
|
416
|
+
message: error.message
|
|
417
|
+
});
|
|
418
|
+
return JSON.stringify({ message: String(error) });
|
|
419
|
+
}
|
|
481
420
|
}
|
|
482
421
|
function truncateStack(stack) {
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
if (lines.length <= MAX_STACK_LINES) {
|
|
488
|
-
return stack;
|
|
489
|
-
}
|
|
490
|
-
return [...lines.slice(0, MAX_STACK_LINES), '... (truncated)'].join('\n');
|
|
422
|
+
if (!stack) return stack;
|
|
423
|
+
const lines = stack.split("\n");
|
|
424
|
+
if (lines.length <= MAX_STACK_LINES) return stack;
|
|
425
|
+
return [...lines.slice(0, MAX_STACK_LINES), "... (truncated)"].join("\n");
|
|
491
426
|
}
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
const
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
const
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
return new URL(hasScheme ? baseURL : `https://${baseURL}`).hostname.toLowerCase();
|
|
510
|
-
} catch {
|
|
511
|
-
return undefined;
|
|
512
|
-
}
|
|
427
|
+
//#endregion
|
|
428
|
+
//#region src/gatewayWarning.ts
|
|
429
|
+
const POSTHOG_AI_GATEWAY_HOSTS = [
|
|
430
|
+
"gateway.posthog.com",
|
|
431
|
+
"gateway.us.posthog.com",
|
|
432
|
+
"gateway.eu.posthog.com",
|
|
433
|
+
"ai-gateway.us.posthog.com",
|
|
434
|
+
"ai-gateway.eu.posthog.com"
|
|
435
|
+
];
|
|
436
|
+
const GATEWAY_DOCS_URL = "https://posthog.com/docs/ai-observability";
|
|
437
|
+
const extractHost = (baseURL) => {
|
|
438
|
+
try {
|
|
439
|
+
const hasScheme = /^[a-z][a-z0-9+.-]*:\/\//i.test(baseURL);
|
|
440
|
+
return new URL(hasScheme ? baseURL : `https://${baseURL}`).hostname.toLowerCase();
|
|
441
|
+
} catch {
|
|
442
|
+
return;
|
|
443
|
+
}
|
|
513
444
|
};
|
|
514
|
-
const isPostHogAiGatewayUrl = baseURL => {
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
const host = extractHost(baseURL);
|
|
519
|
-
return host !== undefined && POSTHOG_AI_GATEWAY_HOSTS.includes(host);
|
|
445
|
+
const isPostHogAiGatewayUrl = (baseURL) => {
|
|
446
|
+
if (!baseURL) return false;
|
|
447
|
+
const host = extractHost(baseURL);
|
|
448
|
+
return host !== void 0 && POSTHOG_AI_GATEWAY_HOSTS.includes(host);
|
|
520
449
|
};
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
const warnIfPostHogAiGateway = baseURL => {
|
|
525
|
-
if (!isPostHogAiGatewayUrl(baseURL)) {
|
|
526
|
-
return;
|
|
527
|
-
}
|
|
528
|
-
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}.`);
|
|
450
|
+
const warnIfPostHogAiGateway = (baseURL) => {
|
|
451
|
+
if (!isPostHogAiGatewayUrl(baseURL)) return;
|
|
452
|
+
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}.`);
|
|
529
453
|
};
|
|
530
|
-
|
|
454
|
+
//#endregion
|
|
455
|
+
//#region src/captureAiGeneration.ts
|
|
531
456
|
/**
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
* same events the SDK wrappers produce.
|
|
545
|
-
*
|
|
546
|
-
* When `error` is set, the event is captured as an error. If the error is an
|
|
547
|
-
* object, it is mutated in place to set `__posthog_previously_captured_error`
|
|
548
|
-
* so callers can re-throw the original error reference safely.
|
|
549
|
-
*/
|
|
457
|
+
* Capture an `$ai_generation` (or `$ai_embedding`) event to PostHog.
|
|
458
|
+
*
|
|
459
|
+
* This is the canonical primitive that every `@posthog/ai` wrapper
|
|
460
|
+
* (`withTracing`, `OpenAI`, `Anthropic`, `GoogleGenAI`, …) funnels through, so
|
|
461
|
+
* external code can use it directly to instrument LLM calls made through
|
|
462
|
+
* arbitrary clients (Cloudflare Workers AI, custom HTTP, etc.) and get the
|
|
463
|
+
* same events the SDK wrappers produce.
|
|
464
|
+
*
|
|
465
|
+
* When `error` is set, the event is captured as an error. If the error is an
|
|
466
|
+
* object, it is mutated in place to set `__posthog_previously_captured_error`
|
|
467
|
+
* so callers can re-throw the original error reference safely.
|
|
468
|
+
*/
|
|
550
469
|
const captureAiGeneration = async (client, options) => {
|
|
551
|
-
|
|
552
|
-
|
|
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
|
-
...(usage.cacheReportingExclusive !== undefined && !tokensOverridden ? {
|
|
638
|
-
$ai_cache_reporting_exclusive: usage.cacheReportingExclusive
|
|
639
|
-
} : {}),
|
|
640
|
-
...(usage.webSearchCount ? {
|
|
641
|
-
$ai_web_search_count: usage.webSearchCount
|
|
642
|
-
} : {}),
|
|
643
|
-
...(usage.rawUsage ? {
|
|
644
|
-
$ai_usage: usage.rawUsage
|
|
645
|
-
} : {})
|
|
646
|
-
};
|
|
647
|
-
const properties = {
|
|
648
|
-
$ai_lib: 'posthog-ai',
|
|
649
|
-
$ai_lib_version: version,
|
|
650
|
-
$ai_provider: options.providerOverride ?? options.provider,
|
|
651
|
-
$ai_model: options.modelOverride ?? options.model,
|
|
652
|
-
$ai_model_parameters: options.modelParameters ?? {},
|
|
653
|
-
$ai_input: safeInput,
|
|
654
|
-
$ai_output_choices: safeOutput,
|
|
655
|
-
$ai_http_status: httpStatus,
|
|
656
|
-
...(usage.inputTokens !== undefined ? {
|
|
657
|
-
$ai_input_tokens: usage.inputTokens
|
|
658
|
-
} : {}),
|
|
659
|
-
...(usage.outputTokens !== undefined ? {
|
|
660
|
-
$ai_output_tokens: usage.outputTokens
|
|
661
|
-
} : {}),
|
|
662
|
-
...additionalTokenValues,
|
|
663
|
-
...(options.latency !== undefined ? {
|
|
664
|
-
$ai_latency: options.latency
|
|
665
|
-
} : {}),
|
|
666
|
-
...(options.timeToFirstToken !== undefined ? {
|
|
667
|
-
$ai_time_to_first_token: options.timeToFirstToken
|
|
668
|
-
} : {}),
|
|
669
|
-
$ai_trace_id: traceId,
|
|
670
|
-
...(options.baseURL === null ? {} : {
|
|
671
|
-
$ai_base_url: options.baseURL ?? ''
|
|
672
|
-
}),
|
|
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
|
-
try {
|
|
707
|
-
options.onError?.(error);
|
|
708
|
-
} catch {
|
|
709
|
-
// Error reporting must not affect the instrumented provider call either.
|
|
710
|
-
}
|
|
711
|
-
console.warn('[PostHog AI] Failed to capture generation telemetry:', error);
|
|
712
|
-
}
|
|
470
|
+
try {
|
|
471
|
+
if (!client.capture) return;
|
|
472
|
+
warnIfPostHogAiGateway(options.baseURL);
|
|
473
|
+
const traceId = options.traceId ?? v4();
|
|
474
|
+
const eventType = options.eventType ?? "$ai_generation";
|
|
475
|
+
const privacyMode = options.privacyMode ?? false;
|
|
476
|
+
const usage = options.usage ?? {};
|
|
477
|
+
const shouldRedact = withPrivacyMode(client, privacyMode, false) === null;
|
|
478
|
+
const safeInput = shouldRedact ? null : toJsonSafeValue(options.input);
|
|
479
|
+
const safeOutput = shouldRedact ? null : toJsonSafeValue(options.output);
|
|
480
|
+
let httpStatus = options.httpStatus;
|
|
481
|
+
let errorData = {};
|
|
482
|
+
if (options.error) {
|
|
483
|
+
if (httpStatus === void 0) {
|
|
484
|
+
if (typeof options.error === "object" && "status" in options.error && typeof options.error.status === "number") httpStatus = options.error.status;
|
|
485
|
+
else if (typeof options.error === "object" && "statusCode" in options.error && typeof options.error.statusCode === "number") httpStatus = options.error.statusCode;
|
|
486
|
+
else httpStatus = 500;
|
|
487
|
+
}
|
|
488
|
+
let exceptionId;
|
|
489
|
+
if (client.options?.enableExceptionAutocapture) {
|
|
490
|
+
exceptionId = uuidv7();
|
|
491
|
+
client.captureException(options.error, void 0, { $ai_trace_id: traceId }, exceptionId);
|
|
492
|
+
if (typeof options.error === "object") options.error.__posthog_previously_captured_error = true;
|
|
493
|
+
}
|
|
494
|
+
errorData = {
|
|
495
|
+
$ai_is_error: true,
|
|
496
|
+
$ai_error: stringifyError(options.error),
|
|
497
|
+
$exception_event_id: exceptionId
|
|
498
|
+
};
|
|
499
|
+
}
|
|
500
|
+
httpStatus = httpStatus ?? 200;
|
|
501
|
+
const costOverrideData = {};
|
|
502
|
+
if (options.costOverride) {
|
|
503
|
+
if (usage.inputTokens !== void 0) costOverrideData.$ai_input_cost_usd = (options.costOverride.inputCost ?? 0) * usage.inputTokens;
|
|
504
|
+
if (usage.outputTokens !== void 0) costOverrideData.$ai_output_cost_usd = (options.costOverride.outputCost ?? 0) * usage.outputTokens;
|
|
505
|
+
if (Object.keys(costOverrideData).length > 0) costOverrideData.$ai_total_cost_usd = (costOverrideData.$ai_input_cost_usd ?? 0) + (costOverrideData.$ai_output_cost_usd ?? 0);
|
|
506
|
+
}
|
|
507
|
+
const tokensOverridden = hasTokenOverrides(options.properties);
|
|
508
|
+
const additionalTokenValues = {
|
|
509
|
+
...usage.reasoningTokens ? { $ai_reasoning_tokens: usage.reasoningTokens } : {},
|
|
510
|
+
...usage.cacheReadInputTokens ? { $ai_cache_read_input_tokens: usage.cacheReadInputTokens } : {},
|
|
511
|
+
...usage.cacheCreationInputTokens ? { $ai_cache_creation_input_tokens: usage.cacheCreationInputTokens } : {},
|
|
512
|
+
...usage.cacheReportingExclusive !== void 0 && !tokensOverridden ? { $ai_cache_reporting_exclusive: usage.cacheReportingExclusive } : {},
|
|
513
|
+
...usage.webSearchCount ? { $ai_web_search_count: usage.webSearchCount } : {},
|
|
514
|
+
...usage.rawUsage ? { $ai_usage: usage.rawUsage } : {}
|
|
515
|
+
};
|
|
516
|
+
const properties = {
|
|
517
|
+
$ai_lib: "posthog-ai",
|
|
518
|
+
$ai_lib_version: version,
|
|
519
|
+
$ai_provider: options.providerOverride ?? options.provider,
|
|
520
|
+
$ai_model: options.modelOverride ?? options.model,
|
|
521
|
+
$ai_model_parameters: options.modelParameters ?? {},
|
|
522
|
+
$ai_input: safeInput,
|
|
523
|
+
$ai_output_choices: safeOutput,
|
|
524
|
+
$ai_http_status: httpStatus,
|
|
525
|
+
...usage.inputTokens !== void 0 ? { $ai_input_tokens: usage.inputTokens } : {},
|
|
526
|
+
...usage.outputTokens !== void 0 ? { $ai_output_tokens: usage.outputTokens } : {},
|
|
527
|
+
...additionalTokenValues,
|
|
528
|
+
...options.latency !== void 0 ? { $ai_latency: options.latency } : {},
|
|
529
|
+
...options.timeToFirstToken !== void 0 ? { $ai_time_to_first_token: options.timeToFirstToken } : {},
|
|
530
|
+
$ai_trace_id: traceId,
|
|
531
|
+
...options.baseURL === null ? {} : { $ai_base_url: options.baseURL ?? "" },
|
|
532
|
+
...options.properties,
|
|
533
|
+
$ai_tokens_source: getTokensSource(options.properties),
|
|
534
|
+
...options.distinctId ? {} : { $process_person_profile: false },
|
|
535
|
+
...options.stopReason ? { $ai_stop_reason: options.stopReason } : {},
|
|
536
|
+
...options.tools ? { $ai_tools: options.tools } : {},
|
|
537
|
+
...options.completionId ? { $ai_completion_id: options.completionId } : {},
|
|
538
|
+
...options.providerMetadata && Object.keys(options.providerMetadata).length > 0 ? { $ai_provider_metadata: options.providerMetadata } : {},
|
|
539
|
+
...errorData,
|
|
540
|
+
...costOverrideData
|
|
541
|
+
};
|
|
542
|
+
const event = {
|
|
543
|
+
distinctId: options.distinctId ?? traceId,
|
|
544
|
+
event: eventType,
|
|
545
|
+
properties,
|
|
546
|
+
groups: options.groups
|
|
547
|
+
};
|
|
548
|
+
if (options.captureImmediate) await captureAiEventImmediate(client, event);
|
|
549
|
+
else captureAiEvent(client, event);
|
|
550
|
+
} catch (error) {
|
|
551
|
+
try {
|
|
552
|
+
options.onError?.(error);
|
|
553
|
+
} catch {}
|
|
554
|
+
console.warn("[PostHog AI] Failed to capture generation telemetry:", error);
|
|
555
|
+
}
|
|
713
556
|
};
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
// Type guards
|
|
557
|
+
//#endregion
|
|
558
|
+
//#region src/vercel/middleware.ts
|
|
718
559
|
function isV3Model(model) {
|
|
719
|
-
|
|
560
|
+
return model.specificationVersion === "v3";
|
|
720
561
|
}
|
|
721
562
|
function getSpecificationVersion(model) {
|
|
722
|
-
|
|
723
|
-
return model.specificationVersion;
|
|
724
|
-
}
|
|
725
|
-
return undefined;
|
|
563
|
+
if (typeof model === "object" && model !== null && "specificationVersion" in model) return model.specificationVersion;
|
|
726
564
|
}
|
|
727
|
-
|
|
728
|
-
// Content types for the output array
|
|
729
|
-
|
|
730
565
|
const redactFileData = (data, mediaType, client) => {
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
}
|
|
734
|
-
if (isString(data)) {
|
|
735
|
-
return isFullAiCaptureEnabled(client) ? data : redactBase64DataUrl(data, mediaType);
|
|
736
|
-
}
|
|
737
|
-
return undefined;
|
|
566
|
+
if (data instanceof URL) return isFullAiCaptureEnabled(client) ? data.toString() : redactBase64DataUrl(data.toString(), data.protocol === "data:" ? mediaType : void 0);
|
|
567
|
+
if (isString(data)) return isFullAiCaptureEnabled(client) ? data : redactBase64DataUrl(data, mediaType);
|
|
738
568
|
};
|
|
739
|
-
const mapVercelParams = params => {
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
|
|
569
|
+
const mapVercelParams = (params) => {
|
|
570
|
+
return {
|
|
571
|
+
temperature: params.temperature,
|
|
572
|
+
max_output_tokens: params.maxOutputTokens,
|
|
573
|
+
top_p: params.topP,
|
|
574
|
+
frequency_penalty: params.frequencyPenalty,
|
|
575
|
+
presence_penalty: params.presencePenalty,
|
|
576
|
+
stop: params.stopSequences,
|
|
577
|
+
stream: params.stream
|
|
578
|
+
};
|
|
749
579
|
};
|
|
750
580
|
const mapVercelPrompt = (messages, client) => {
|
|
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
|
-
|
|
820
|
-
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
|
|
824
|
-
// Trim the inputs array until its serialized JSON size fits within MAX_OUTPUT_SIZE.
|
|
825
|
-
// Pre-compute each message's byte size once so we can shift by accumulated budget
|
|
826
|
-
// in a single linear pass, instead of re-stringifying the whole array per iteration.
|
|
827
|
-
const messageSizes = inputs.map(m => utf8ByteLength(JSON.stringify(m)));
|
|
828
|
-
// Account for the surrounding `[` `]` plus a comma between each pair of elements.
|
|
829
|
-
let totalBytes = 2 + Math.max(0, messageSizes.length - 1);
|
|
830
|
-
for (const size of messageSizes) {
|
|
831
|
-
totalBytes += size;
|
|
832
|
-
}
|
|
833
|
-
let removedCount = 0;
|
|
834
|
-
while (totalBytes > MAX_OUTPUT_SIZE && removedCount < messageSizes.length) {
|
|
835
|
-
totalBytes -= messageSizes[removedCount];
|
|
836
|
-
// Each removed message past the first also drops the comma that joined it.
|
|
837
|
-
if (removedCount < messageSizes.length - 1) {
|
|
838
|
-
totalBytes -= 1;
|
|
839
|
-
}
|
|
840
|
-
removedCount++;
|
|
841
|
-
}
|
|
842
|
-
if (removedCount > 0) {
|
|
843
|
-
inputs.splice(0, removedCount);
|
|
844
|
-
// Add one placeholder to indicate how many were removed
|
|
845
|
-
inputs.unshift({
|
|
846
|
-
role: 'posthog',
|
|
847
|
-
content: `[${removedCount} message${removedCount === 1 ? '' : 's'} removed due to size limit]`
|
|
848
|
-
});
|
|
849
|
-
}
|
|
850
|
-
} catch (error) {
|
|
851
|
-
console.error('Error stringifying inputs', error);
|
|
852
|
-
return [{
|
|
853
|
-
role: 'posthog',
|
|
854
|
-
content: 'An error occurred while processing your request. Please try again.'
|
|
855
|
-
}];
|
|
856
|
-
}
|
|
857
|
-
return inputs;
|
|
581
|
+
const inputs = messages.map((message) => {
|
|
582
|
+
let content;
|
|
583
|
+
if (message.role === "system") content = [{
|
|
584
|
+
type: "text",
|
|
585
|
+
text: truncate(toContentString(message.content), client)
|
|
586
|
+
}];
|
|
587
|
+
else if (Array.isArray(message.content)) content = message.content.map((c) => {
|
|
588
|
+
if (c.type === "text") return {
|
|
589
|
+
type: "text",
|
|
590
|
+
text: truncate(c.text, client)
|
|
591
|
+
};
|
|
592
|
+
else if (c.type === "file") return {
|
|
593
|
+
type: "file",
|
|
594
|
+
file: redactFileData(c.data, c.mediaType, client) ?? "raw files not supported",
|
|
595
|
+
mediaType: c.mediaType
|
|
596
|
+
};
|
|
597
|
+
else if (c.type === "reasoning") return {
|
|
598
|
+
type: "reasoning",
|
|
599
|
+
text: truncate(c.text, client)
|
|
600
|
+
};
|
|
601
|
+
else if (c.type === "tool-call") return {
|
|
602
|
+
type: "tool-call",
|
|
603
|
+
toolCallId: c.toolCallId,
|
|
604
|
+
toolName: c.toolName,
|
|
605
|
+
input: c.input
|
|
606
|
+
};
|
|
607
|
+
else if (c.type === "tool-result") return {
|
|
608
|
+
type: "tool-result",
|
|
609
|
+
toolCallId: c.toolCallId,
|
|
610
|
+
toolName: c.toolName,
|
|
611
|
+
output: sanitizeVercel(c.output, client),
|
|
612
|
+
isError: c.isError
|
|
613
|
+
};
|
|
614
|
+
return {
|
|
615
|
+
type: "text",
|
|
616
|
+
text: ""
|
|
617
|
+
};
|
|
618
|
+
});
|
|
619
|
+
else content = [{
|
|
620
|
+
type: "text",
|
|
621
|
+
text: truncate(toContentString(message.content), client)
|
|
622
|
+
}];
|
|
623
|
+
return {
|
|
624
|
+
role: message.role,
|
|
625
|
+
content
|
|
626
|
+
};
|
|
627
|
+
});
|
|
628
|
+
if (isFullAiCaptureEnabled(client)) return inputs;
|
|
629
|
+
try {
|
|
630
|
+
const messageSizes = inputs.map((m) => utf8ByteLength(JSON.stringify(m)));
|
|
631
|
+
let totalBytes = 2 + Math.max(0, messageSizes.length - 1);
|
|
632
|
+
for (const size of messageSizes) totalBytes += size;
|
|
633
|
+
let removedCount = 0;
|
|
634
|
+
while (totalBytes > 2e5 && removedCount < messageSizes.length) {
|
|
635
|
+
totalBytes -= messageSizes[removedCount];
|
|
636
|
+
if (removedCount < messageSizes.length - 1) totalBytes -= 1;
|
|
637
|
+
removedCount++;
|
|
638
|
+
}
|
|
639
|
+
if (removedCount > 0) {
|
|
640
|
+
inputs.splice(0, removedCount);
|
|
641
|
+
inputs.unshift({
|
|
642
|
+
role: "posthog",
|
|
643
|
+
content: `[${removedCount} message${removedCount === 1 ? "" : "s"} removed due to size limit]`
|
|
644
|
+
});
|
|
645
|
+
}
|
|
646
|
+
} catch (error) {
|
|
647
|
+
console.error("Error stringifying inputs", error);
|
|
648
|
+
return [{
|
|
649
|
+
role: "posthog",
|
|
650
|
+
content: "An error occurred while processing your request. Please try again."
|
|
651
|
+
}];
|
|
652
|
+
}
|
|
653
|
+
return inputs;
|
|
858
654
|
};
|
|
859
655
|
const mapVercelOutput = (result, client) => {
|
|
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
|
-
|
|
913
|
-
|
|
914
|
-
|
|
915
|
-
|
|
916
|
-
|
|
917
|
-
role: 'assistant',
|
|
918
|
-
content: content.length === 1 && content[0].type === 'text' ? content[0].text : content
|
|
919
|
-
}];
|
|
920
|
-
}
|
|
921
|
-
// otherwise stringify and truncate
|
|
922
|
-
try {
|
|
923
|
-
const jsonOutput = JSON.stringify(result);
|
|
924
|
-
return [{
|
|
925
|
-
content: truncate(jsonOutput, client),
|
|
926
|
-
role: 'assistant'
|
|
927
|
-
}];
|
|
928
|
-
} catch {
|
|
929
|
-
console.error('Error stringifying output');
|
|
930
|
-
return [];
|
|
931
|
-
}
|
|
656
|
+
const content = result.map((item) => {
|
|
657
|
+
if (item.type === "text") return {
|
|
658
|
+
type: "text",
|
|
659
|
+
text: truncate(item.text, client)
|
|
660
|
+
};
|
|
661
|
+
if (item.type === "tool-call") {
|
|
662
|
+
const toolCall = item;
|
|
663
|
+
const rawArgs = toolCall.input ?? toolCall.args ?? toolCall.arguments ?? {};
|
|
664
|
+
return {
|
|
665
|
+
type: "tool-call",
|
|
666
|
+
id: item.toolCallId,
|
|
667
|
+
function: {
|
|
668
|
+
name: item.toolName,
|
|
669
|
+
arguments: typeof rawArgs === "string" ? rawArgs : JSON.stringify(rawArgs)
|
|
670
|
+
}
|
|
671
|
+
};
|
|
672
|
+
}
|
|
673
|
+
if (item.type === "reasoning") return {
|
|
674
|
+
type: "reasoning",
|
|
675
|
+
text: truncate(item.text, client)
|
|
676
|
+
};
|
|
677
|
+
if (item.type === "file") {
|
|
678
|
+
let fileData = redactFileData(item.data, item.mediaType, client) ?? `[binary ${item.mediaType} file]`;
|
|
679
|
+
if (!isFullAiCaptureEnabled(client) && typeof item.data === "string" && fileData === item.data && item.data.length > 1e3) fileData = `[${item.mediaType} file - ${item.data.length} bytes]`;
|
|
680
|
+
return {
|
|
681
|
+
type: "file",
|
|
682
|
+
name: "generated_file",
|
|
683
|
+
mediaType: item.mediaType,
|
|
684
|
+
data: fileData
|
|
685
|
+
};
|
|
686
|
+
}
|
|
687
|
+
if (item.type === "source") return {
|
|
688
|
+
type: "source",
|
|
689
|
+
sourceType: item.sourceType,
|
|
690
|
+
id: item.id,
|
|
691
|
+
url: item.url || "",
|
|
692
|
+
title: item.title || ""
|
|
693
|
+
};
|
|
694
|
+
return {
|
|
695
|
+
type: "text",
|
|
696
|
+
text: truncate(JSON.stringify(item), client)
|
|
697
|
+
};
|
|
698
|
+
});
|
|
699
|
+
if (content.length > 0) return [{
|
|
700
|
+
role: "assistant",
|
|
701
|
+
content: content.length === 1 && content[0].type === "text" ? content[0].text : content
|
|
702
|
+
}];
|
|
703
|
+
try {
|
|
704
|
+
const jsonOutput = JSON.stringify(result);
|
|
705
|
+
return [{
|
|
706
|
+
content: truncate(jsonOutput, client),
|
|
707
|
+
role: "assistant"
|
|
708
|
+
}];
|
|
709
|
+
} catch {
|
|
710
|
+
console.error("Error stringifying output");
|
|
711
|
+
return [];
|
|
712
|
+
}
|
|
932
713
|
};
|
|
933
|
-
const extractProvider = model => {
|
|
934
|
-
|
|
935
|
-
const providerName = provider.split('.')[0];
|
|
936
|
-
return providerName;
|
|
714
|
+
const extractProvider = (model) => {
|
|
715
|
+
return model.provider.toLowerCase().split(".")[0];
|
|
937
716
|
};
|
|
938
|
-
|
|
939
717
|
/**
|
|
940
|
-
|
|
941
|
-
|
|
942
|
-
|
|
943
|
-
|
|
944
|
-
|
|
945
|
-
|
|
946
|
-
const extractBaseURL = model => {
|
|
947
|
-
|
|
948
|
-
|
|
949
|
-
|
|
950
|
-
|
|
951
|
-
|
|
952
|
-
|
|
953
|
-
|
|
954
|
-
|
|
955
|
-
|
|
956
|
-
|
|
957
|
-
|
|
958
|
-
|
|
959
|
-
|
|
960
|
-
|
|
961
|
-
return isString(url) ? url : '';
|
|
962
|
-
}
|
|
963
|
-
} catch {
|
|
964
|
-
// Unknown config shape or url() threw.
|
|
965
|
-
}
|
|
966
|
-
return '';
|
|
718
|
+
* Recover the base URL so gateway calls self-identify via `$ai_base_url` (dedup
|
|
719
|
+
* keys on it). The spec exposes none, so we read the off-spec provider `config`:
|
|
720
|
+
* `@ai-sdk/anthropic` keeps a `config.baseURL` string; `@ai-sdk/openai`/
|
|
721
|
+
* `openai-compatible` bury it in a `config.url({ path })` closure. Unknown shapes
|
|
722
|
+
* degrade to `''` — those providers (or a custom `fetch`) stay invisible to dedup.
|
|
723
|
+
*/
|
|
724
|
+
const extractBaseURL = (model) => {
|
|
725
|
+
try {
|
|
726
|
+
const config = model.config;
|
|
727
|
+
if (!isObject(config)) return "";
|
|
728
|
+
if (isString(config.baseURL)) return config.baseURL;
|
|
729
|
+
const urlFn = config.url;
|
|
730
|
+
if (typeof urlFn === "function") {
|
|
731
|
+
const url = urlFn({
|
|
732
|
+
path: "",
|
|
733
|
+
modelId: model.modelId
|
|
734
|
+
});
|
|
735
|
+
return isString(url) ? url : "";
|
|
736
|
+
}
|
|
737
|
+
} catch {}
|
|
738
|
+
return "";
|
|
967
739
|
};
|
|
968
|
-
|
|
969
|
-
// Extract web search count from provider metadata (works for both V2 and V3)
|
|
970
740
|
const extractWebSearchCount = (providerMetadata, usage) => {
|
|
971
|
-
|
|
972
|
-
|
|
973
|
-
|
|
974
|
-
|
|
975
|
-
|
|
976
|
-
|
|
977
|
-
|
|
978
|
-
|
|
979
|
-
// Fall back to generic calculation
|
|
980
|
-
return calculateWebSearchCount({
|
|
981
|
-
usage,
|
|
982
|
-
providerMetadata
|
|
983
|
-
});
|
|
741
|
+
if (providerMetadata && typeof providerMetadata === "object" && "anthropic" in providerMetadata && providerMetadata.anthropic && typeof providerMetadata.anthropic === "object" && "server_tool_use" in providerMetadata.anthropic) {
|
|
742
|
+
const serverToolUse = providerMetadata.anthropic.server_tool_use;
|
|
743
|
+
if (serverToolUse && typeof serverToolUse === "object" && "web_search_requests" in serverToolUse && typeof serverToolUse.web_search_requests === "number") return serverToolUse.web_search_requests;
|
|
744
|
+
}
|
|
745
|
+
return calculateWebSearchCount({
|
|
746
|
+
usage,
|
|
747
|
+
providerMetadata
|
|
748
|
+
});
|
|
984
749
|
};
|
|
985
|
-
|
|
986
|
-
|
|
987
|
-
|
|
988
|
-
if (typeof value === 'number') {
|
|
989
|
-
return value;
|
|
990
|
-
}
|
|
991
|
-
if (value && typeof value === 'object' && 'total' in value && typeof value.total === 'number') {
|
|
992
|
-
return value.total;
|
|
993
|
-
}
|
|
994
|
-
return undefined;
|
|
750
|
+
const extractTokenCount = (value) => {
|
|
751
|
+
if (typeof value === "number") return value;
|
|
752
|
+
if (value && typeof value === "object" && "total" in value && typeof value.total === "number") return value.total;
|
|
995
753
|
};
|
|
996
754
|
const extractUsageToken = (usage, topLevelKey, nestedObjectKey, nestedValueKey) => {
|
|
997
|
-
|
|
998
|
-
|
|
999
|
-
|
|
1000
|
-
const nestedTokens = usage[nestedObjectKey];
|
|
1001
|
-
if (nestedTokens && typeof nestedTokens === 'object' && nestedValueKey in nestedTokens) {
|
|
1002
|
-
return nestedTokens[nestedValueKey];
|
|
1003
|
-
}
|
|
1004
|
-
return undefined;
|
|
755
|
+
if (topLevelKey in usage) return usage[topLevelKey];
|
|
756
|
+
const nestedTokens = usage[nestedObjectKey];
|
|
757
|
+
if (nestedTokens && typeof nestedTokens === "object" && nestedValueKey in nestedTokens) return nestedTokens[nestedValueKey];
|
|
1005
758
|
};
|
|
1006
|
-
|
|
1007
|
-
|
|
1008
|
-
const
|
|
1009
|
-
|
|
1010
|
-
// Helper to extract cached input tokens from V2 (usage.cachedInputTokens) or V3 (usage.inputTokens.cacheRead)
|
|
1011
|
-
const extractCacheReadTokens = usage => extractUsageToken(usage, 'cachedInputTokens', 'inputTokens', 'cacheRead');
|
|
1012
|
-
|
|
1013
|
-
// Helper to extract cache write tokens from V3 (usage.inputTokens.cacheWrite). Providers like
|
|
1014
|
-
// Amazon Bedrock populate this standardized field instead of providerMetadata.anthropic.
|
|
1015
|
-
const extractCacheWriteTokens = usage => {
|
|
1016
|
-
if ('inputTokens' in usage && usage.inputTokens && typeof usage.inputTokens === 'object' && 'cacheWrite' in usage.inputTokens) {
|
|
1017
|
-
return usage.inputTokens.cacheWrite;
|
|
1018
|
-
}
|
|
1019
|
-
return undefined;
|
|
759
|
+
const extractReasoningTokens = (usage) => extractUsageToken(usage, "reasoningTokens", "outputTokens", "reasoning");
|
|
760
|
+
const extractCacheReadTokens = (usage) => extractUsageToken(usage, "cachedInputTokens", "inputTokens", "cacheRead");
|
|
761
|
+
const extractCacheWriteTokens = (usage) => {
|
|
762
|
+
if ("inputTokens" in usage && usage.inputTokens && typeof usage.inputTokens === "object" && "cacheWrite" in usage.inputTokens) return usage.inputTokens.cacheWrite;
|
|
1020
763
|
};
|
|
1021
|
-
|
|
1022
|
-
// Extract additional token values from provider metadata, with a V3 standardized fallback
|
|
1023
|
-
// (e.g. Amazon Bedrock exposes cache write tokens via usage.inputTokens.cacheWrite rather
|
|
1024
|
-
// than providerMetadata.anthropic.cacheCreationInputTokens). A cacheWrite of 0 is treated
|
|
1025
|
-
// as absent so we preserve the pre-fallback event shape on providers that simply omit the
|
|
1026
|
-
// field — consumers downstream saw `$ai_cache_creation_input_tokens` missing, not 0.
|
|
1027
764
|
const extractAdditionalTokenValues = (providerMetadata, usage) => {
|
|
1028
|
-
|
|
1029
|
-
|
|
1030
|
-
|
|
1031
|
-
|
|
1032
|
-
|
|
1033
|
-
|
|
1034
|
-
const cacheWrite = extractCacheWriteTokens(usage);
|
|
1035
|
-
if (typeof cacheWrite === 'number' && cacheWrite > 0) {
|
|
1036
|
-
return {
|
|
1037
|
-
cacheCreationInputTokens: cacheWrite
|
|
1038
|
-
};
|
|
1039
|
-
}
|
|
1040
|
-
}
|
|
1041
|
-
return {};
|
|
765
|
+
if (providerMetadata && typeof providerMetadata === "object" && "anthropic" in providerMetadata && providerMetadata.anthropic && typeof providerMetadata.anthropic === "object" && "cacheCreationInputTokens" in providerMetadata.anthropic) return { cacheCreationInputTokens: providerMetadata.anthropic.cacheCreationInputTokens };
|
|
766
|
+
if (usage && typeof usage === "object") {
|
|
767
|
+
const cacheWrite = extractCacheWriteTokens(usage);
|
|
768
|
+
if (typeof cacheWrite === "number" && cacheWrite > 0) return { cacheCreationInputTokens: cacheWrite };
|
|
769
|
+
}
|
|
770
|
+
return {};
|
|
1042
771
|
};
|
|
1043
|
-
|
|
1044
|
-
// Detects Anthropic Claude regardless of host (direct Anthropic, Amazon Bedrock, Google Vertex, etc.).
|
|
1045
|
-
// The server applies exclusive cache token accounting based on the model name, so any Claude model
|
|
1046
|
-
// needs its V3 input tokens adjusted to exclude cache tokens — not just those routed through a
|
|
1047
|
-
// provider whose name contains "anthropic". Accepts the resolved modelId string (not the raw model)
|
|
1048
|
-
// so it sees the same id the server does after posthogModelOverride / response.modelId fallbacks.
|
|
1049
772
|
const isAnthropicClaudeModel = (modelId, provider) => {
|
|
1050
|
-
|
|
1051
|
-
|
|
1052
|
-
}
|
|
1053
|
-
return /claude|anthropic/i.test(modelId);
|
|
773
|
+
if (provider.toLowerCase().includes("anthropic")) return true;
|
|
774
|
+
return /claude|anthropic/i.test(modelId);
|
|
1054
775
|
};
|
|
1055
|
-
|
|
1056
|
-
// For Anthropic providers in V3, inputTokens.total is the sum of all tokens (uncached + cache read + cache write).
|
|
1057
|
-
// Our cost calculation expects inputTokens to be only the uncached portion for Anthropic.
|
|
1058
|
-
// This helper subtracts cache tokens from inputTokens for Anthropic V3 models.
|
|
1059
776
|
const adjustAnthropicV3CacheTokens = (model, modelId, provider, usage) => {
|
|
1060
|
-
|
|
1061
|
-
|
|
1062
|
-
|
|
1063
|
-
|
|
1064
|
-
if (usage.inputTokens && cacheTokens > 0) {
|
|
1065
|
-
usage.inputTokens = Math.max(usage.inputTokens - cacheTokens, 0);
|
|
1066
|
-
}
|
|
1067
|
-
}
|
|
777
|
+
if (isV3Model(model) && isAnthropicClaudeModel(modelId, provider)) {
|
|
778
|
+
const cacheTokens = (usage.cacheReadInputTokens || 0) + (usage.cacheCreationInputTokens || 0);
|
|
779
|
+
if (usage.inputTokens && cacheTokens > 0) usage.inputTokens = Math.max(usage.inputTokens - cacheTokens, 0);
|
|
780
|
+
}
|
|
1068
781
|
};
|
|
1069
|
-
|
|
1070
782
|
/**
|
|
1071
|
-
|
|
1072
|
-
|
|
1073
|
-
|
|
783
|
+
* Wraps a Vercel AI SDK language model (V2 or V3) with PostHog tracing.
|
|
784
|
+
* Automatically detects the model version and applies appropriate instrumentation.
|
|
785
|
+
*/
|
|
1074
786
|
const wrapVercelLanguageModel = (model, phClient, options) => {
|
|
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
|
-
|
|
1361
|
-
|
|
1362
|
-
|
|
1363
|
-
|
|
1364
|
-
});
|
|
1365
|
-
})().catch(error => {
|
|
1366
|
-
// Building telemetry must not change the provider stream's behavior.
|
|
1367
|
-
console.warn('[PostHog AI] Failed to capture Vercel stream telemetry:', error);
|
|
1368
|
-
});
|
|
1369
|
-
return finalizationPromise;
|
|
1370
|
-
};
|
|
1371
|
-
const instrumentedStream = new ReadableStream({
|
|
1372
|
-
async pull(controller) {
|
|
1373
|
-
let result;
|
|
1374
|
-
try {
|
|
1375
|
-
result = await reader.read();
|
|
1376
|
-
} catch (error) {
|
|
1377
|
-
void finalize(error, true);
|
|
1378
|
-
controller.error(error);
|
|
1379
|
-
return;
|
|
1380
|
-
}
|
|
1381
|
-
if (result.done) {
|
|
1382
|
-
controller.close();
|
|
1383
|
-
void finalize();
|
|
1384
|
-
return;
|
|
1385
|
-
}
|
|
1386
|
-
try {
|
|
1387
|
-
observeChunk(result.value);
|
|
1388
|
-
} catch {
|
|
1389
|
-
// Instrumentation must not alter or suppress provider chunks.
|
|
1390
|
-
}
|
|
1391
|
-
controller.enqueue(result.value);
|
|
1392
|
-
},
|
|
1393
|
-
cancel(reason) {
|
|
1394
|
-
void finalize(reason ?? new Error('Vercel AI SDK stream was cancelled'), true);
|
|
1395
|
-
return reader.cancel(reason);
|
|
1396
|
-
}
|
|
1397
|
-
}, {
|
|
1398
|
-
highWaterMark: 0
|
|
1399
|
-
});
|
|
1400
|
-
return {
|
|
1401
|
-
stream: instrumentedStream,
|
|
1402
|
-
...rest
|
|
1403
|
-
};
|
|
1404
|
-
} catch (error) {
|
|
1405
|
-
await captureStreamGeneration({
|
|
1406
|
-
...baseOptions,
|
|
1407
|
-
model: modelId,
|
|
1408
|
-
provider: provider,
|
|
1409
|
-
input: mergedOptions.posthogPrivacyMode ? '' : mapVercelPrompt(params.prompt, phClient),
|
|
1410
|
-
output: [],
|
|
1411
|
-
latency: (Date.now() - startTime) / 1000,
|
|
1412
|
-
baseURL,
|
|
1413
|
-
modelParameters: getModelParams(mergedParams),
|
|
1414
|
-
usage: {},
|
|
1415
|
-
error: error,
|
|
1416
|
-
tools: availableTools
|
|
1417
|
-
});
|
|
1418
|
-
throw error;
|
|
1419
|
-
}
|
|
1420
|
-
},
|
|
1421
|
-
writable: true,
|
|
1422
|
-
configurable: true,
|
|
1423
|
-
enumerable: false
|
|
1424
|
-
}
|
|
1425
|
-
});
|
|
1426
|
-
return wrappedModel;
|
|
787
|
+
const specificationVersion = getSpecificationVersion(model);
|
|
788
|
+
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.");
|
|
789
|
+
const traceId = options.posthogTraceId ?? v4();
|
|
790
|
+
const mergedOptions = {
|
|
791
|
+
...options,
|
|
792
|
+
posthogTraceId: traceId,
|
|
793
|
+
posthogDistinctId: options.posthogDistinctId,
|
|
794
|
+
posthogProperties: {
|
|
795
|
+
...options.posthogProperties,
|
|
796
|
+
$ai_framework: "vercel",
|
|
797
|
+
$ai_framework_version: model.specificationVersion === "v3" ? "6" : "5"
|
|
798
|
+
}
|
|
799
|
+
};
|
|
800
|
+
const baseOptions = {
|
|
801
|
+
distinctId: mergedOptions.posthogDistinctId,
|
|
802
|
+
traceId,
|
|
803
|
+
properties: mergedOptions.posthogProperties,
|
|
804
|
+
groups: mergedOptions.posthogGroups,
|
|
805
|
+
privacyMode: mergedOptions.posthogPrivacyMode,
|
|
806
|
+
modelOverride: mergedOptions.posthogModelOverride,
|
|
807
|
+
providerOverride: mergedOptions.posthogProviderOverride,
|
|
808
|
+
costOverride: mergedOptions.posthogCostOverride,
|
|
809
|
+
captureImmediate: mergedOptions.posthogCaptureImmediate
|
|
810
|
+
};
|
|
811
|
+
return Object.create(model, {
|
|
812
|
+
doGenerate: {
|
|
813
|
+
value: async (params) => {
|
|
814
|
+
const startTime = Date.now();
|
|
815
|
+
const mergedParams = {
|
|
816
|
+
...mergedOptions,
|
|
817
|
+
...mapVercelParams(params)
|
|
818
|
+
};
|
|
819
|
+
const availableTools = extractAvailableToolCalls("vercel", params);
|
|
820
|
+
const baseURL = extractBaseURL(model);
|
|
821
|
+
try {
|
|
822
|
+
const result = await model.doGenerate(params);
|
|
823
|
+
const modelId = mergedOptions.posthogModelOverride ?? (result.response?.modelId ? result.response.modelId : model.modelId);
|
|
824
|
+
const provider = mergedOptions.posthogProviderOverride ?? extractProvider(model);
|
|
825
|
+
const content = mapVercelOutput(result.content ?? [], phClient);
|
|
826
|
+
const latency = (Date.now() - startTime) / 1e3;
|
|
827
|
+
const providerMetadata = result.providerMetadata;
|
|
828
|
+
const additionalTokenValues = extractAdditionalTokenValues(providerMetadata, result.usage);
|
|
829
|
+
const webSearchCount = extractWebSearchCount(providerMetadata, result.usage);
|
|
830
|
+
const usageObj = result.usage;
|
|
831
|
+
const rawUsageData = {
|
|
832
|
+
usage: result.usage,
|
|
833
|
+
providerMetadata
|
|
834
|
+
};
|
|
835
|
+
if (result.response && typeof result.response === "object") {
|
|
836
|
+
const responseBody = result.response.body;
|
|
837
|
+
if (responseBody && typeof responseBody === "object" && "usageMetadata" in responseBody) rawUsageData.rawResponse = { usageMetadata: responseBody.usageMetadata };
|
|
838
|
+
}
|
|
839
|
+
const usage = {
|
|
840
|
+
inputTokens: extractTokenCount(result.usage.inputTokens),
|
|
841
|
+
outputTokens: extractTokenCount(result.usage.outputTokens),
|
|
842
|
+
reasoningTokens: extractReasoningTokens(usageObj),
|
|
843
|
+
cacheReadInputTokens: extractCacheReadTokens(usageObj),
|
|
844
|
+
webSearchCount,
|
|
845
|
+
...additionalTokenValues,
|
|
846
|
+
rawUsage: rawUsageData
|
|
847
|
+
};
|
|
848
|
+
adjustAnthropicV3CacheTokens(model, modelId, provider, usage);
|
|
849
|
+
const rawFinishReason = result.finishReason;
|
|
850
|
+
const finishReasonStr = typeof rawFinishReason === "string" ? rawFinishReason : rawFinishReason && typeof rawFinishReason === "object" && "unified" in rawFinishReason ? String(rawFinishReason.unified) : void 0;
|
|
851
|
+
await captureAiGeneration(phClient, {
|
|
852
|
+
...baseOptions,
|
|
853
|
+
model: modelId,
|
|
854
|
+
provider,
|
|
855
|
+
input: mergedOptions.posthogPrivacyMode ? "" : mapVercelPrompt(params.prompt, phClient),
|
|
856
|
+
output: content,
|
|
857
|
+
latency,
|
|
858
|
+
baseURL,
|
|
859
|
+
modelParameters: getModelParams(mergedParams),
|
|
860
|
+
httpStatus: 200,
|
|
861
|
+
usage,
|
|
862
|
+
stopReason: finishReasonStr,
|
|
863
|
+
tools: availableTools
|
|
864
|
+
});
|
|
865
|
+
return result;
|
|
866
|
+
} catch (error) {
|
|
867
|
+
const modelId = model.modelId;
|
|
868
|
+
await captureAiGeneration(phClient, {
|
|
869
|
+
...baseOptions,
|
|
870
|
+
model: modelId,
|
|
871
|
+
provider: model.provider,
|
|
872
|
+
input: mergedOptions.posthogPrivacyMode ? "" : mapVercelPrompt(params.prompt, phClient),
|
|
873
|
+
output: [],
|
|
874
|
+
latency: (Date.now() - startTime) / 1e3,
|
|
875
|
+
baseURL,
|
|
876
|
+
modelParameters: getModelParams(mergedParams),
|
|
877
|
+
usage: {},
|
|
878
|
+
error,
|
|
879
|
+
tools: availableTools
|
|
880
|
+
});
|
|
881
|
+
throw error;
|
|
882
|
+
}
|
|
883
|
+
},
|
|
884
|
+
writable: true,
|
|
885
|
+
configurable: true,
|
|
886
|
+
enumerable: false
|
|
887
|
+
},
|
|
888
|
+
doStream: {
|
|
889
|
+
value: async (params) => {
|
|
890
|
+
const startTime = Date.now();
|
|
891
|
+
let firstTokenTime;
|
|
892
|
+
let generatedText = "";
|
|
893
|
+
let reasoningText = "";
|
|
894
|
+
let stopReason;
|
|
895
|
+
let usage = {};
|
|
896
|
+
let providerMetadata = void 0;
|
|
897
|
+
const mergedParams = {
|
|
898
|
+
...mergedOptions,
|
|
899
|
+
...mapVercelParams(params)
|
|
900
|
+
};
|
|
901
|
+
const modelId = mergedOptions.posthogModelOverride ?? model.modelId;
|
|
902
|
+
const provider = mergedOptions.posthogProviderOverride ?? extractProvider(model);
|
|
903
|
+
const availableTools = extractAvailableToolCalls("vercel", params);
|
|
904
|
+
const baseURL = extractBaseURL(model);
|
|
905
|
+
const toolCallsInProgress = /* @__PURE__ */ new Map();
|
|
906
|
+
const captureStreamGeneration = async (captureOptions) => {
|
|
907
|
+
try {
|
|
908
|
+
await captureAiGeneration(phClient, captureOptions);
|
|
909
|
+
} catch (error) {
|
|
910
|
+
console.warn("[PostHog AI] Failed to capture Vercel stream telemetry:", error);
|
|
911
|
+
}
|
|
912
|
+
};
|
|
913
|
+
try {
|
|
914
|
+
const { stream, ...rest } = await model.doStream(params);
|
|
915
|
+
const reader = stream.getReader();
|
|
916
|
+
let inBandError;
|
|
917
|
+
let hasInBandError = false;
|
|
918
|
+
let finalizationPromise;
|
|
919
|
+
const observeChunk = (chunk) => {
|
|
920
|
+
if (chunk.type === "text-delta") {
|
|
921
|
+
if (firstTokenTime === void 0) firstTokenTime = Date.now();
|
|
922
|
+
generatedText += chunk.delta;
|
|
923
|
+
}
|
|
924
|
+
if (chunk.type === "reasoning-delta") {
|
|
925
|
+
if (firstTokenTime === void 0) firstTokenTime = Date.now();
|
|
926
|
+
reasoningText += chunk.delta;
|
|
927
|
+
}
|
|
928
|
+
if (chunk.type === "tool-input-start") {
|
|
929
|
+
if (firstTokenTime === void 0) firstTokenTime = Date.now();
|
|
930
|
+
toolCallsInProgress.set(chunk.id, {
|
|
931
|
+
toolCallId: chunk.id,
|
|
932
|
+
toolName: chunk.toolName,
|
|
933
|
+
input: ""
|
|
934
|
+
});
|
|
935
|
+
}
|
|
936
|
+
if (chunk.type === "tool-input-delta") {
|
|
937
|
+
const toolCall = toolCallsInProgress.get(chunk.id);
|
|
938
|
+
if (toolCall) toolCall.input += chunk.delta;
|
|
939
|
+
}
|
|
940
|
+
if (chunk.type === "tool-call") {
|
|
941
|
+
if (firstTokenTime === void 0) firstTokenTime = Date.now();
|
|
942
|
+
toolCallsInProgress.set(chunk.toolCallId, {
|
|
943
|
+
toolCallId: chunk.toolCallId,
|
|
944
|
+
toolName: chunk.toolName,
|
|
945
|
+
input: chunk.input
|
|
946
|
+
});
|
|
947
|
+
}
|
|
948
|
+
if (chunk.type === "error") {
|
|
949
|
+
hasInBandError = true;
|
|
950
|
+
inBandError = chunk.error;
|
|
951
|
+
}
|
|
952
|
+
if (chunk.type === "finish") {
|
|
953
|
+
providerMetadata = chunk.providerMetadata;
|
|
954
|
+
const chunkUsage = chunk.usage || {};
|
|
955
|
+
const additionalTokenValues = extractAdditionalTokenValues(providerMetadata, chunkUsage);
|
|
956
|
+
usage = {
|
|
957
|
+
inputTokens: extractTokenCount(chunk.usage?.inputTokens),
|
|
958
|
+
outputTokens: extractTokenCount(chunk.usage?.outputTokens),
|
|
959
|
+
reasoningTokens: extractReasoningTokens(chunkUsage),
|
|
960
|
+
cacheReadInputTokens: extractCacheReadTokens(chunkUsage),
|
|
961
|
+
...additionalTokenValues
|
|
962
|
+
};
|
|
963
|
+
const rawFinishReason = chunk.finishReason;
|
|
964
|
+
if (typeof rawFinishReason === "string") stopReason = rawFinishReason;
|
|
965
|
+
else if (rawFinishReason && typeof rawFinishReason === "object" && "unified" in rawFinishReason) stopReason = String(rawFinishReason.unified);
|
|
966
|
+
}
|
|
967
|
+
};
|
|
968
|
+
const finalize = (terminalError, isError = false) => {
|
|
969
|
+
if (finalizationPromise) return finalizationPromise;
|
|
970
|
+
finalizationPromise = (async () => {
|
|
971
|
+
const latency = (Date.now() - startTime) / 1e3;
|
|
972
|
+
const timeToFirstToken = firstTokenTime !== void 0 ? (firstTokenTime - startTime) / 1e3 : void 0;
|
|
973
|
+
const content = [];
|
|
974
|
+
if (reasoningText) content.push({
|
|
975
|
+
type: "reasoning",
|
|
976
|
+
text: truncate(reasoningText, phClient)
|
|
977
|
+
});
|
|
978
|
+
if (generatedText) content.push({
|
|
979
|
+
type: "text",
|
|
980
|
+
text: truncate(generatedText, phClient)
|
|
981
|
+
});
|
|
982
|
+
for (const toolCall of toolCallsInProgress.values()) if (toolCall.toolName) content.push({
|
|
983
|
+
type: "tool-call",
|
|
984
|
+
id: toolCall.toolCallId,
|
|
985
|
+
function: {
|
|
986
|
+
name: toolCall.toolName,
|
|
987
|
+
arguments: toolCall.input
|
|
988
|
+
}
|
|
989
|
+
});
|
|
990
|
+
const output = content.length > 0 ? [{
|
|
991
|
+
role: "assistant",
|
|
992
|
+
content: content.length === 1 && content[0].type === "text" ? content[0].text : content
|
|
993
|
+
}] : [];
|
|
994
|
+
const webSearchCount = extractWebSearchCount(providerMetadata, usage);
|
|
995
|
+
const finalUsage = {
|
|
996
|
+
...usage,
|
|
997
|
+
webSearchCount,
|
|
998
|
+
rawUsage: {
|
|
999
|
+
usage,
|
|
1000
|
+
providerMetadata
|
|
1001
|
+
}
|
|
1002
|
+
};
|
|
1003
|
+
adjustAnthropicV3CacheTokens(model, modelId, provider, finalUsage);
|
|
1004
|
+
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;
|
|
1005
|
+
await captureStreamGeneration({
|
|
1006
|
+
...baseOptions,
|
|
1007
|
+
model: modelId,
|
|
1008
|
+
provider,
|
|
1009
|
+
input: mergedOptions.posthogPrivacyMode ? "" : mapVercelPrompt(params.prompt, phClient),
|
|
1010
|
+
output,
|
|
1011
|
+
latency,
|
|
1012
|
+
timeToFirstToken,
|
|
1013
|
+
baseURL,
|
|
1014
|
+
modelParameters: getModelParams(mergedParams),
|
|
1015
|
+
httpStatus: error ? void 0 : 200,
|
|
1016
|
+
usage: finalUsage,
|
|
1017
|
+
stopReason,
|
|
1018
|
+
error,
|
|
1019
|
+
tools: availableTools
|
|
1020
|
+
});
|
|
1021
|
+
})().catch((error) => {
|
|
1022
|
+
console.warn("[PostHog AI] Failed to capture Vercel stream telemetry:", error);
|
|
1023
|
+
});
|
|
1024
|
+
return finalizationPromise;
|
|
1025
|
+
};
|
|
1026
|
+
return {
|
|
1027
|
+
stream: new ReadableStream({
|
|
1028
|
+
async pull(controller) {
|
|
1029
|
+
let result;
|
|
1030
|
+
try {
|
|
1031
|
+
result = await reader.read();
|
|
1032
|
+
} catch (error) {
|
|
1033
|
+
finalize(error, true);
|
|
1034
|
+
controller.error(error);
|
|
1035
|
+
return;
|
|
1036
|
+
}
|
|
1037
|
+
if (result.done) {
|
|
1038
|
+
controller.close();
|
|
1039
|
+
finalize();
|
|
1040
|
+
return;
|
|
1041
|
+
}
|
|
1042
|
+
try {
|
|
1043
|
+
observeChunk(result.value);
|
|
1044
|
+
} catch {}
|
|
1045
|
+
controller.enqueue(result.value);
|
|
1046
|
+
},
|
|
1047
|
+
cancel(reason) {
|
|
1048
|
+
finalize(reason ?? /* @__PURE__ */ new Error("Vercel AI SDK stream was cancelled"), true);
|
|
1049
|
+
return reader.cancel(reason);
|
|
1050
|
+
}
|
|
1051
|
+
}, { highWaterMark: 0 }),
|
|
1052
|
+
...rest
|
|
1053
|
+
};
|
|
1054
|
+
} catch (error) {
|
|
1055
|
+
await captureStreamGeneration({
|
|
1056
|
+
...baseOptions,
|
|
1057
|
+
model: modelId,
|
|
1058
|
+
provider,
|
|
1059
|
+
input: mergedOptions.posthogPrivacyMode ? "" : mapVercelPrompt(params.prompt, phClient),
|
|
1060
|
+
output: [],
|
|
1061
|
+
latency: (Date.now() - startTime) / 1e3,
|
|
1062
|
+
baseURL,
|
|
1063
|
+
modelParameters: getModelParams(mergedParams),
|
|
1064
|
+
usage: {},
|
|
1065
|
+
error,
|
|
1066
|
+
tools: availableTools
|
|
1067
|
+
});
|
|
1068
|
+
throw error;
|
|
1069
|
+
}
|
|
1070
|
+
},
|
|
1071
|
+
writable: true,
|
|
1072
|
+
configurable: true,
|
|
1073
|
+
enumerable: false
|
|
1074
|
+
}
|
|
1075
|
+
});
|
|
1427
1076
|
};
|
|
1428
|
-
|
|
1077
|
+
//#endregion
|
|
1429
1078
|
export { wrapVercelLanguageModel as withTracing };
|
|
1430
|
-
|
|
1079
|
+
|
|
1080
|
+
//# sourceMappingURL=index.mjs.map
|