@posthog/ai 8.9.3 → 8.10.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/dist/adk/index.cjs +977 -0
  2. package/dist/adk/index.cjs.map +1 -0
  3. package/dist/adk/index.d.ts +149 -0
  4. package/dist/adk/index.mjs +976 -0
  5. package/dist/adk/index.mjs.map +1 -0
  6. package/dist/anthropic/index.cjs +927 -1104
  7. package/dist/anthropic/index.cjs.map +1 -1
  8. package/dist/anthropic/index.d.ts +34 -33
  9. package/dist/anthropic/index.mjs +899 -1095
  10. package/dist/anthropic/index.mjs.map +1 -1
  11. package/dist/gemini/index.cjs +867 -1112
  12. package/dist/gemini/index.cjs.map +1 -1
  13. package/dist/gemini/index.d.ts +38 -35
  14. package/dist/gemini/index.mjs +862 -1107
  15. package/dist/gemini/index.mjs.map +1 -1
  16. package/dist/index.cjs +1218 -1539
  17. package/dist/index.cjs.map +1 -1
  18. package/dist/index.d.ts +170 -157
  19. package/dist/index.mjs +1216 -1537
  20. package/dist/index.mjs.map +1 -1
  21. package/dist/langchain/index.cjs +851 -1029
  22. package/dist/langchain/index.cjs.map +1 -1
  23. package/dist/langchain/index.d.ts +75 -75
  24. package/dist/langchain/index.mjs +850 -1027
  25. package/dist/langchain/index.mjs.map +1 -1
  26. package/dist/langchain/middleware/index.cjs +1016 -1225
  27. package/dist/langchain/middleware/index.cjs.map +1 -1
  28. package/dist/langchain/middleware/index.d.ts +29 -25
  29. package/dist/langchain/middleware/index.mjs +1015 -1223
  30. package/dist/langchain/middleware/index.mjs.map +1 -1
  31. package/dist/openai/index.cjs +1990 -2516
  32. package/dist/openai/index.cjs.map +1 -1
  33. package/dist/openai/index.d.ts +106 -104
  34. package/dist/openai/index.mjs +1985 -2511
  35. package/dist/openai/index.mjs.map +1 -1
  36. package/dist/openai-agents/index.cjs +745 -827
  37. package/dist/openai-agents/index.cjs.map +1 -1
  38. package/dist/openai-agents/index.d.ts +48 -47
  39. package/dist/openai-agents/index.mjs +744 -825
  40. package/dist/openai-agents/index.mjs.map +1 -1
  41. package/dist/otel/index.cjs +427 -486
  42. package/dist/otel/index.cjs.map +1 -1
  43. package/dist/otel/index.d.ts +36 -35
  44. package/dist/otel/index.mjs +426 -484
  45. package/dist/otel/index.mjs.map +1 -1
  46. package/dist/vercel/index.cjs +992 -1336
  47. package/dist/vercel/index.cjs.map +1 -1
  48. package/dist/vercel/index.d.ts +21 -16
  49. package/dist/vercel/index.mjs +991 -1334
  50. package/dist/vercel/index.mjs.map +1 -1
  51. package/package.json +23 -12
@@ -1,1064 +1,887 @@
1
- import 'uuid';
2
- import { BaseCallbackHandler } from '@langchain/core/callbacks/base';
3
-
4
- // Type guards for safer type checking
5
-
6
- const isObject = value => {
7
- return value !== null && typeof value === 'object' && !Array.isArray(value);
1
+ import "uuid";
2
+ import { BaseCallbackHandler } from "@langchain/core/callbacks/base";
3
+ //#region src/typeGuards.ts
4
+ const isObject = (value) => {
5
+ return value !== null && typeof value === "object" && !Array.isArray(value);
8
6
  };
9
-
10
- /** @internal */
11
-
12
- /** @internal */
13
-
7
+ //#endregion
8
+ //#region src/captureAiEvent.ts
14
9
  /** @internal */
15
10
  function isFullAiCaptureEnabled(client) {
16
- return client?.enableFullAiCapture === true;
11
+ return client?.enableFullAiCapture === true;
17
12
  }
18
-
19
13
  /** @internal */
20
14
  function captureAiEvent(client, event) {
21
- if (isFullAiCaptureEnabled(client) && typeof client.captureAi === 'function') {
22
- client.captureAi(event);
23
- return;
24
- }
25
- client.capture(event);
15
+ if (isFullAiCaptureEnabled(client) && typeof client.captureAi === "function") {
16
+ client.captureAi(event);
17
+ return;
18
+ }
19
+ client.capture(event);
26
20
  }
27
-
21
+ //#endregion
22
+ //#region src/sanitization/base64_recognizer.ts
28
23
  const DATA_URL_PREFIX_RE = /^data:([^;,\s]+)(?:;[^;,\s]+)*;base64,/i;
29
24
  const BASE64_ALPHABET_RE = /^[A-Za-z0-9+/_=-]+$/;
30
- class Base64Recognizer {
31
- recognize(value, minLength) {
32
- const dataUrl = DATA_URL_PREFIX_RE.exec(value);
33
- if (dataUrl) return {
34
- kind: 'data-url',
35
- mediaType: dataUrl[1]
36
- };
37
- if (value.length < minLength) return {
38
- kind: 'none'
39
- };
40
- const confidencePrefix = value.slice(0, minLength);
41
- if (BASE64_ALPHABET_RE.test(confidencePrefix)) {
42
- return {
43
- kind: 'raw'
44
- };
45
- } else {
46
- return {
47
- kind: 'none'
48
- };
49
- }
50
- }
51
- }
52
-
53
- const MIME_HINT_KEYS = ['mediaType', 'media_type', 'mimeType', 'mime_type'];
54
- const STRONG_CONTEXT_KEYS = new Set(['data', 'file_data', 'fileData', 'image_url', 'imageUrl', 'video_url', 'videoUrl', 'audio', 'audio_data', 'audioData', 'inline_data', 'inlineData', 'source', 'result']);
55
- const STRONG_CONTEXT_TYPES = new Set(['image', 'image_url', 'input_image', 'audio', 'input_audio', 'video', 'video_url', 'file', 'input_file', 'document', 'media', 'file-data']);
56
- const FILE_FAMILY_TYPES = new Set(['file', 'input_file', 'document', 'media', 'file-data']);
57
- const KNOWN_AUDIO_FORMATS = new Set(['wav', 'mp3', 'ogg', 'flac', 'm4a', 'aac', 'webm']);
58
- class MediaTypeContext {
59
- static EMPTY = new MediaTypeContext(undefined, undefined);
60
- constructor(parent, key, explicitMediaType) {
61
- this.parent = parent;
62
- this.key = key;
63
- this.explicitMediaType = explicitMediaType;
64
- }
65
- inferMediaType() {
66
- return this.inferFromSiblingMime() ?? this.inferFromSiblingFormat() ?? this.inferFromParentType() ?? this.inferFromKey();
67
- }
68
- inferFromSiblingMime() {
69
- if (this.explicitMediaType) return this.explicitMediaType;
70
- if (!this.parent) return undefined;
71
- for (const hint of MIME_HINT_KEYS) {
72
- const v = this.parent[hint];
73
- if (typeof v === 'string') return v;
74
- }
75
- return undefined;
76
- }
77
- inferFromSiblingFormat() {
78
- if (!this.parent) return undefined;
79
- const fmt = this.parent.format;
80
- if (typeof fmt === 'string' && KNOWN_AUDIO_FORMATS.has(fmt.toLowerCase())) {
81
- return `audio/${fmt.toLowerCase()}`;
82
- }
83
- return undefined;
84
- }
85
- inferFromParentType() {
86
- if (!this.parent) return undefined;
87
- const t = this.parent.type;
88
- if (typeof t !== 'string') return undefined;
89
- if (t === 'image' || t === 'image_url' || t === 'input_image') return 'image';
90
- if (t === 'audio' || t === 'input_audio') return 'audio';
91
- if (t === 'video' || t === 'video_url') return 'video';
92
- if (FILE_FAMILY_TYPES.has(t)) return 'application/octet-stream';
93
- return undefined;
94
- }
95
- inferFromKey() {
96
- if (!this.key) return undefined;
97
- const key = this.key.toLowerCase();
98
- if (key.includes('audio')) return 'audio';
99
- if (key.includes('video')) return 'video';
100
- if (key.includes('image')) return 'image';
101
- if (key.includes('file') || key.includes('document')) return 'application/octet-stream';
102
- return undefined;
103
- }
104
- hasExplicitBinaryMediaType() {
105
- if (!this.explicitMediaType && (!this.parent || !this.key || !STRONG_CONTEXT_KEYS.has(this.key))) return false;
106
- const mediaType = this.inferFromSiblingMime();
107
- return mediaType !== undefined && !mediaType.toLowerCase().startsWith('text/');
108
- }
109
- signalsBinary() {
110
- if (this.explicitMediaType) return true;
111
- if (this.parent) {
112
- for (const hint of MIME_HINT_KEYS) {
113
- if (typeof this.parent[hint] === 'string') return true;
114
- }
115
- const fmt = this.parent.format;
116
- if (typeof fmt === 'string' && KNOWN_AUDIO_FORMATS.has(fmt.toLowerCase())) return true;
117
- const t = this.parent.type;
118
- if (typeof t === 'string' && STRONG_CONTEXT_TYPES.has(t)) return true;
119
- }
120
- if (this.key && STRONG_CONTEXT_KEYS.has(this.key)) return true;
121
- return false;
122
- }
123
- }
124
-
25
+ var Base64Recognizer = class {
26
+ recognize(value, minLength) {
27
+ const dataUrl = DATA_URL_PREFIX_RE.exec(value);
28
+ if (dataUrl) return {
29
+ kind: "data-url",
30
+ mediaType: dataUrl[1]
31
+ };
32
+ if (value.length < minLength) return { kind: "none" };
33
+ const confidencePrefix = value.slice(0, minLength);
34
+ if (BASE64_ALPHABET_RE.test(confidencePrefix)) return { kind: "raw" };
35
+ else return { kind: "none" };
36
+ }
37
+ };
38
+ //#endregion
39
+ //#region src/sanitization/media_type_context.ts
40
+ const MIME_HINT_KEYS = [
41
+ "mediaType",
42
+ "media_type",
43
+ "mimeType",
44
+ "mime_type"
45
+ ];
46
+ const STRONG_CONTEXT_KEYS = /* @__PURE__ */ new Set([
47
+ "data",
48
+ "file_data",
49
+ "fileData",
50
+ "image_url",
51
+ "imageUrl",
52
+ "video_url",
53
+ "videoUrl",
54
+ "audio",
55
+ "audio_data",
56
+ "audioData",
57
+ "inline_data",
58
+ "inlineData",
59
+ "source",
60
+ "result"
61
+ ]);
62
+ const STRONG_CONTEXT_TYPES = /* @__PURE__ */ new Set([
63
+ "image",
64
+ "image_url",
65
+ "input_image",
66
+ "audio",
67
+ "input_audio",
68
+ "video",
69
+ "video_url",
70
+ "file",
71
+ "input_file",
72
+ "document",
73
+ "media",
74
+ "file-data"
75
+ ]);
76
+ const FILE_FAMILY_TYPES = /* @__PURE__ */ new Set([
77
+ "file",
78
+ "input_file",
79
+ "document",
80
+ "media",
81
+ "file-data"
82
+ ]);
83
+ const KNOWN_AUDIO_FORMATS = /* @__PURE__ */ new Set([
84
+ "wav",
85
+ "mp3",
86
+ "ogg",
87
+ "flac",
88
+ "m4a",
89
+ "aac",
90
+ "webm"
91
+ ]);
92
+ var MediaTypeContext = class MediaTypeContext {
93
+ static {
94
+ this.EMPTY = new MediaTypeContext(void 0, void 0);
95
+ }
96
+ constructor(parent, key, explicitMediaType) {
97
+ this.parent = parent;
98
+ this.key = key;
99
+ this.explicitMediaType = explicitMediaType;
100
+ }
101
+ inferMediaType() {
102
+ return this.inferFromSiblingMime() ?? this.inferFromSiblingFormat() ?? this.inferFromParentType() ?? this.inferFromKey();
103
+ }
104
+ inferFromSiblingMime() {
105
+ if (this.explicitMediaType) return this.explicitMediaType;
106
+ if (!this.parent) return void 0;
107
+ for (const hint of MIME_HINT_KEYS) {
108
+ const v = this.parent[hint];
109
+ if (typeof v === "string") return v;
110
+ }
111
+ }
112
+ inferFromSiblingFormat() {
113
+ if (!this.parent) return void 0;
114
+ const fmt = this.parent.format;
115
+ if (typeof fmt === "string" && KNOWN_AUDIO_FORMATS.has(fmt.toLowerCase())) return `audio/${fmt.toLowerCase()}`;
116
+ }
117
+ inferFromParentType() {
118
+ if (!this.parent) return void 0;
119
+ const t = this.parent.type;
120
+ if (typeof t !== "string") return void 0;
121
+ if (t === "image" || t === "image_url" || t === "input_image") return "image";
122
+ if (t === "audio" || t === "input_audio") return "audio";
123
+ if (t === "video" || t === "video_url") return "video";
124
+ if (FILE_FAMILY_TYPES.has(t)) return "application/octet-stream";
125
+ }
126
+ inferFromKey() {
127
+ if (!this.key) return void 0;
128
+ const key = this.key.toLowerCase();
129
+ if (key.includes("audio")) return "audio";
130
+ if (key.includes("video")) return "video";
131
+ if (key.includes("image")) return "image";
132
+ if (key.includes("file") || key.includes("document")) return "application/octet-stream";
133
+ }
134
+ hasExplicitBinaryMediaType() {
135
+ if (!this.explicitMediaType && (!this.parent || !this.key || !STRONG_CONTEXT_KEYS.has(this.key))) return false;
136
+ const mediaType = this.inferFromSiblingMime();
137
+ return mediaType !== void 0 && !mediaType.toLowerCase().startsWith("text/");
138
+ }
139
+ signalsBinary() {
140
+ if (this.explicitMediaType) return true;
141
+ if (this.parent) {
142
+ for (const hint of MIME_HINT_KEYS) if (typeof this.parent[hint] === "string") return true;
143
+ const fmt = this.parent.format;
144
+ if (typeof fmt === "string" && KNOWN_AUDIO_FORMATS.has(fmt.toLowerCase())) return true;
145
+ const t = this.parent.type;
146
+ if (typeof t === "string" && STRONG_CONTEXT_TYPES.has(t)) return true;
147
+ }
148
+ if (this.key && STRONG_CONTEXT_KEYS.has(this.key)) return true;
149
+ return false;
150
+ }
151
+ };
152
+ //#endregion
153
+ //#region src/sanitization/binary_content_redactor.ts
125
154
  const STRONG_CONTEXT_MIN_LENGTH = 64;
126
155
  const WEAK_CONTEXT_MIN_LENGTH = 1024;
127
- class BinaryContentRedactor {
128
- visited = new WeakSet();
129
- constructor(recognizer = new Base64Recognizer()) {
130
- this.recognizer = recognizer;
131
- }
132
- redact(value, mediaType) {
133
- this.visited = new WeakSet();
134
- return this.walk(value, mediaType ? new MediaTypeContext(undefined, undefined, mediaType) : MediaTypeContext.EMPTY);
135
- }
136
- walk(value, ctx) {
137
- if (value === null || value === undefined) return value;
138
- if (typeof value === 'string') return this.redactString(value, ctx);
139
- if (typeof value !== 'object') return value;
140
-
141
- // Buffer extends Uint8Array, so this branch catches both.
142
- if (typeof Uint8Array !== 'undefined' && value instanceof Uint8Array) {
143
- return this.placeholderFor(ctx.inferMediaType());
144
- }
145
- if (this.visited.has(value)) return null;
146
- this.visited.add(value);
147
- if (Array.isArray(value)) {
148
- return value.map(item => this.walk(item, ctx));
149
- }
150
- const obj = value;
151
- const out = {};
152
- for (const k of Object.keys(obj)) {
153
- out[k] = this.walk(obj[k], new MediaTypeContext(obj, k));
154
- }
155
- return out;
156
- }
157
- redactString(value, ctx) {
158
- const hasExplicitBinaryMediaType = ctx.hasExplicitBinaryMediaType();
159
- const recognitionValue = hasExplicitBinaryMediaType ? value.replace(/[\r\n]/g, '') : value;
160
- const minLength = hasExplicitBinaryMediaType ? Math.min(recognitionValue.length, STRONG_CONTEXT_MIN_LENGTH) : ctx.signalsBinary() ? STRONG_CONTEXT_MIN_LENGTH : WEAK_CONTEXT_MIN_LENGTH;
161
- const recognition = this.recognizer.recognize(recognitionValue, minLength);
162
- switch (recognition.kind) {
163
- case 'data-url':
164
- return this.placeholderFor(recognition.mediaType);
165
- case 'raw':
166
- return this.placeholderFor(ctx.inferMediaType());
167
- case 'none':
168
- return value;
169
- }
170
- }
171
- placeholderFor(mediaType) {
172
- if (!mediaType) return '[base64 redacted]';
173
- if (mediaType === 'application/octet-stream') return '[base64 file redacted]';
174
- return `[base64 ${mediaType} redacted]`;
175
- }
176
- }
177
-
156
+ var BinaryContentRedactor = class {
157
+ constructor(recognizer = new Base64Recognizer()) {
158
+ this.recognizer = recognizer;
159
+ this.visited = /* @__PURE__ */ new WeakSet();
160
+ }
161
+ redact(value, mediaType) {
162
+ this.visited = /* @__PURE__ */ new WeakSet();
163
+ return this.walk(value, mediaType ? new MediaTypeContext(void 0, void 0, mediaType) : MediaTypeContext.EMPTY);
164
+ }
165
+ walk(value, ctx) {
166
+ if (value === null || value === void 0) return value;
167
+ if (typeof value === "string") return this.redactString(value, ctx);
168
+ if (typeof value !== "object") return value;
169
+ if (typeof Uint8Array !== "undefined" && value instanceof Uint8Array) return this.placeholderFor(ctx.inferMediaType());
170
+ if (this.visited.has(value)) return null;
171
+ this.visited.add(value);
172
+ if (Array.isArray(value)) return value.map((item) => this.walk(item, ctx));
173
+ const obj = value;
174
+ const out = {};
175
+ for (const k of Object.keys(obj)) out[k] = this.walk(obj[k], new MediaTypeContext(obj, k));
176
+ return out;
177
+ }
178
+ redactString(value, ctx) {
179
+ const hasExplicitBinaryMediaType = ctx.hasExplicitBinaryMediaType();
180
+ const recognitionValue = hasExplicitBinaryMediaType ? value.replace(/[\r\n]/g, "") : value;
181
+ const minLength = hasExplicitBinaryMediaType ? Math.min(recognitionValue.length, STRONG_CONTEXT_MIN_LENGTH) : ctx.signalsBinary() ? STRONG_CONTEXT_MIN_LENGTH : WEAK_CONTEXT_MIN_LENGTH;
182
+ const recognition = this.recognizer.recognize(recognitionValue, minLength);
183
+ switch (recognition.kind) {
184
+ case "data-url": return this.placeholderFor(recognition.mediaType);
185
+ case "raw": return this.placeholderFor(ctx.inferMediaType());
186
+ case "none": return value;
187
+ }
188
+ }
189
+ placeholderFor(mediaType) {
190
+ if (!mediaType) return "[base64 redacted]";
191
+ if (mediaType === "application/octet-stream") return "[base64 file redacted]";
192
+ return `[base64 ${mediaType} redacted]`;
193
+ }
194
+ };
195
+ //#endregion
196
+ //#region src/sanitization.ts
178
197
  const redactor = new BinaryContentRedactor();
179
198
  const sanitize = (data, client) => isFullAiCaptureEnabled(client) ? data : redactor.redact(data);
180
199
  const sanitizeLangChain = (data, client) => sanitize(data, client);
181
-
182
- const STRING_FORMAT = 'utf8';
183
-
184
- // Reused across calls to avoid per-invocation allocation; truncate() runs
185
- // hundreds of times for prompts with many parts.
200
+ //#endregion
201
+ //#region src/utils.ts
202
+ const STRING_FORMAT = "utf8";
186
203
  new TextEncoder();
187
- new TextDecoder(STRING_FORMAT, {
188
- fatal: false
189
- });
190
-
204
+ new TextDecoder(STRING_FORMAT, { fatal: false });
191
205
  /**
192
- * Safely converts content to a string, preserving structure for objects/arrays.
193
- * - If content is already a string, returns it as-is
194
- * - If content is an object or array, stringifies it with JSON.stringify to preserve structure
195
- * - Otherwise, converts to string with String()
196
- *
197
- * This prevents the "[object Object]" bug when objects are naively converted to strings.
198
- *
199
- * @param content - The content to convert to a string
200
- * @returns A string representation that preserves structure for complex types
201
- */
206
+ * Safely converts content to a string, preserving structure for objects/arrays.
207
+ * - If content is already a string, returns it as-is
208
+ * - If content is an object or array, stringifies it with JSON.stringify to preserve structure
209
+ * - Otherwise, converts to string with String()
210
+ *
211
+ * This prevents the "[object Object]" bug when objects are naively converted to strings.
212
+ *
213
+ * @param content - The content to convert to a string
214
+ * @returns A string representation that preserves structure for complex types
215
+ */
202
216
  function toContentString(content) {
203
- if (typeof content === 'string') {
204
- return content;
205
- }
206
- if (content !== undefined && content !== null && typeof content === 'object') {
207
- try {
208
- return JSON.stringify(content);
209
- } catch {
210
- // Fallback for circular refs, BigInt, or objects with throwing toJSON
211
- return String(content);
212
- }
213
- }
214
- return String(content);
217
+ if (typeof content === "string") return content;
218
+ if (content !== void 0 && content !== null && typeof content === "object") try {
219
+ return JSON.stringify(content);
220
+ } catch {
221
+ return String(content);
222
+ }
223
+ return String(content);
215
224
  }
216
225
  const getModelParams = (params, responseServiceTier) => {
217
- if (!params) {
218
- return {};
219
- }
220
- const modelParams = {};
221
- const paramKeys = ['temperature', 'max_tokens', 'max_completion_tokens', 'top_p', 'frequency_penalty', 'presence_penalty', 'n', 'stop', 'stream', 'streaming', 'language', 'response_format', 'timestamp_granularities', 'service_tier'];
222
- for (const key of paramKeys) {
223
- if (key in params && params[key] !== undefined) {
224
- modelParams[key] = params[key];
225
- }
226
- }
227
- return modelParams;
226
+ if (!params) return {};
227
+ const modelParams = {};
228
+ for (const key of [
229
+ "temperature",
230
+ "max_tokens",
231
+ "max_completion_tokens",
232
+ "top_p",
233
+ "frequency_penalty",
234
+ "presence_penalty",
235
+ "n",
236
+ "stop",
237
+ "stream",
238
+ "streaming",
239
+ "language",
240
+ "response_format",
241
+ "timestamp_granularities",
242
+ "service_tier"
243
+ ]) if (key in params && params[key] !== void 0) modelParams[key] = params[key];
244
+ if (responseServiceTier != null) modelParams.service_tier = responseServiceTier;
245
+ return modelParams;
228
246
  };
229
247
  const withPrivacyMode = (client, privacyMode, input) => {
230
- return client.privacy_mode || privacyMode ? null : input;
248
+ return client.privacy_mode || privacyMode ? null : input;
231
249
  };
232
250
  function sanitizeValues(obj) {
233
- if (obj === undefined || obj === null) {
234
- return obj;
235
- }
236
- const jsonSafe = JSON.parse(JSON.stringify(obj));
237
- if (typeof jsonSafe === 'string') {
238
- // Sanitize lone surrogates by round-tripping through UTF-8
239
- return new TextDecoder().decode(new TextEncoder().encode(jsonSafe));
240
- } else if (Array.isArray(jsonSafe)) {
241
- return jsonSafe.map(sanitizeValues);
242
- } else if (jsonSafe && typeof jsonSafe === 'object') {
243
- return Object.fromEntries(Object.entries(jsonSafe).map(([k, v]) => [k, sanitizeValues(v)]));
244
- }
245
- return jsonSafe;
251
+ if (obj === void 0 || obj === null) return obj;
252
+ const jsonSafe = JSON.parse(JSON.stringify(obj));
253
+ if (typeof jsonSafe === "string") return new TextDecoder().decode(new TextEncoder().encode(jsonSafe));
254
+ else if (Array.isArray(jsonSafe)) return jsonSafe.map(sanitizeValues);
255
+ else if (jsonSafe && typeof jsonSafe === "object") return Object.fromEntries(Object.entries(jsonSafe).map(([k, v]) => [k, sanitizeValues(v)]));
256
+ return jsonSafe;
246
257
  }
247
-
248
- var version = "8.9.3";
249
-
258
+ //#endregion
259
+ //#region package.json
260
+ var version = "8.10.1";
261
+ //#endregion
262
+ //#region src/serializeError.ts
250
263
  const DEFAULT_MAX_DEPTH = 3;
251
264
  const MAX_STACK_LINES = 20;
252
265
  function serializeError(value, depth = DEFAULT_MAX_DEPTH) {
253
- if (depth < 0 || value === null || typeof value !== 'object') {
254
- return value;
255
- }
256
- if (value instanceof Error) {
257
- const out = {
258
- name: value.name,
259
- message: value.message,
260
- stack: truncateStack(value.stack)
261
- };
262
- for (const key of Object.keys(value)) {
263
- out[key] = serializeError(value[key], depth - 1);
264
- }
265
- if (value.cause !== undefined) {
266
- out.cause = serializeError(value.cause, depth - 1);
267
- }
268
- return out;
269
- }
270
- if (Array.isArray(value)) {
271
- return value.map(item => serializeError(item, depth - 1));
272
- }
273
- return value;
266
+ if (depth < 0 || value === null || typeof value !== "object") return value;
267
+ if (value instanceof Error) {
268
+ const out = {
269
+ name: value.name,
270
+ message: value.message,
271
+ stack: truncateStack(value.stack)
272
+ };
273
+ for (const key of Object.keys(value)) out[key] = serializeError(value[key], depth - 1);
274
+ if (value.cause !== void 0) out.cause = serializeError(value.cause, depth - 1);
275
+ return out;
276
+ }
277
+ if (Array.isArray(value)) return value.map((item) => serializeError(item, depth - 1));
278
+ return value;
274
279
  }
275
280
  function stringifyError(error) {
276
- try {
277
- return JSON.stringify(sanitizeValues(serializeError(error)));
278
- } catch {
279
- if (error instanceof Error) {
280
- return JSON.stringify({
281
- name: error.name,
282
- message: error.message
283
- });
284
- }
285
- return JSON.stringify({
286
- message: String(error)
287
- });
288
- }
281
+ try {
282
+ return JSON.stringify(sanitizeValues(serializeError(error)));
283
+ } catch {
284
+ if (error instanceof Error) return JSON.stringify({
285
+ name: error.name,
286
+ message: error.message
287
+ });
288
+ return JSON.stringify({ message: String(error) });
289
+ }
289
290
  }
290
291
  function truncateStack(stack) {
291
- if (!stack) {
292
- return stack;
293
- }
294
- const lines = stack.split('\n');
295
- if (lines.length <= MAX_STACK_LINES) {
296
- return stack;
297
- }
298
- return [...lines.slice(0, MAX_STACK_LINES), '... (truncated)'].join('\n');
292
+ if (!stack) return stack;
293
+ const lines = stack.split("\n");
294
+ if (lines.length <= MAX_STACK_LINES) return stack;
295
+ return [...lines.slice(0, MAX_STACK_LINES), "... (truncated)"].join("\n");
299
296
  }
300
-
301
- // Warn when a wrapper's base_url points at the PostHog AI Gateway: the gateway
302
- // emits its own $ai_generation, so each call would be captured (and, for billable
303
- // products, billed) twice. We only warn — the wrapper's event carries data the
304
- // gateway never sees (groups, custom properties, trace hierarchy).
305
-
306
- // Keep in sync with the gateway's deployed hosts (see services/llm-gateway in the
307
- // main repo). gateway.us.posthog.com is live today; the rest are listed ahead of
308
- // any traffic moving to them.
309
- const POSTHOG_AI_GATEWAY_HOSTS = ['gateway.posthog.com', 'gateway.us.posthog.com', 'gateway.eu.posthog.com', 'ai-gateway.us.posthog.com', 'ai-gateway.eu.posthog.com'];
310
-
311
- // Swap for the dedicated AI Gateway page once it ships.
312
- const GATEWAY_DOCS_URL = 'https://posthog.com/docs/ai-observability';
313
- const extractHost = baseURL => {
314
- try {
315
- // Tolerate bare hosts that omit a scheme, e.g. "gateway.us.posthog.com/v1".
316
- const hasScheme = /^[a-z][a-z0-9+.-]*:\/\//i.test(baseURL);
317
- return new URL(hasScheme ? baseURL : `https://${baseURL}`).hostname.toLowerCase();
318
- } catch {
319
- return undefined;
320
- }
297
+ //#endregion
298
+ //#region src/gatewayWarning.ts
299
+ const POSTHOG_AI_GATEWAY_HOSTS = [
300
+ "gateway.posthog.com",
301
+ "gateway.us.posthog.com",
302
+ "gateway.eu.posthog.com",
303
+ "ai-gateway.us.posthog.com",
304
+ "ai-gateway.eu.posthog.com"
305
+ ];
306
+ const GATEWAY_DOCS_URL = "https://posthog.com/docs/ai-observability";
307
+ const extractHost = (baseURL) => {
308
+ try {
309
+ const hasScheme = /^[a-z][a-z0-9+.-]*:\/\//i.test(baseURL);
310
+ return new URL(hasScheme ? baseURL : `https://${baseURL}`).hostname.toLowerCase();
311
+ } catch {
312
+ return;
313
+ }
321
314
  };
322
- const isPostHogAiGatewayUrl = baseURL => {
323
- if (!baseURL) {
324
- return false;
325
- }
326
- const host = extractHost(baseURL);
327
- return host !== undefined && POSTHOG_AI_GATEWAY_HOSTS.includes(host);
315
+ const isPostHogAiGatewayUrl = (baseURL) => {
316
+ if (!baseURL) return false;
317
+ const host = extractHost(baseURL);
318
+ return host !== void 0 && POSTHOG_AI_GATEWAY_HOSTS.includes(host);
328
319
  };
329
-
330
- // Warns on every gateway call by design: the misconfiguration is impossible to
331
- // miss that way, and a doubled bill is worse than noisy logs.
332
- const warnIfPostHogAiGateway = baseURL => {
333
- if (!isPostHogAiGatewayUrl(baseURL)) {
334
- return;
335
- }
336
- 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}.`);
320
+ const warnIfPostHogAiGateway = (baseURL) => {
321
+ if (!isPostHogAiGatewayUrl(baseURL)) return;
322
+ 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}.`);
337
323
  };
338
-
339
- // Mirror LangGraph's isGraphBubbleUp guard without adding LangGraph as a dependency. Every
340
- // LangGraph control-flow exception (GraphInterrupt, NodeInterrupt, ParentCommand, GraphDrained,
341
- // and future subclasses) exposes a prototype getter `is_bubble_up` that returns true, which the
342
- // LangGraph runtime itself uses to distinguish control flow from real failures. The getter reads
343
- // as undefined on ordinary Errors and works across duplicated LangGraph package copies.
344
- const isLangGraphControlFlow = error => error.is_bubble_up === true;
345
-
346
- /** A run may either be a Span or a Generation */
347
-
348
- /** Storage for run metadata */
349
-
350
- class LangChainCallbackHandler extends BaseCallbackHandler {
351
- name = 'PosthogCallbackHandler';
352
- runs = {};
353
- parentTree = {};
354
- constructor(options) {
355
- if (!options.client) {
356
- throw new Error('PostHog client is required');
357
- }
358
- super();
359
- this.client = options.client;
360
- this.distinctId = options.distinctId;
361
- this.traceId = options.traceId;
362
- this.properties = options.properties || {};
363
- this.privacyMode = options.privacyMode || false;
364
- this.groups = options.groups || {};
365
- this.debug = options.debug || false;
366
- }
367
-
368
- // ===== CALLBACK METHODS =====
369
-
370
- handleChainStart(chain, inputs, runId, parentRunId, tags, metadata, _runType, runName, extra) {
371
- this._logDebugEvent('on_chain_start', runId, parentRunId, {
372
- inputs,
373
- tags
374
- });
375
- this._setParentOfRun(runId, parentRunId);
376
- this._setTraceOrSpanMetadata(chain, inputs, runId, parentRunId, metadata, tags, runName);
377
- if (typeof extra?.posthogStartTime === 'number' && Number.isFinite(extra.posthogStartTime)) {
378
- this.runs[runId].startTime = extra.posthogStartTime;
379
- }
380
- }
381
- handleChainEnd(outputs, runId, parentRunId, tags, _kwargs) {
382
- this._logAndPopTraceOrSpan('on_chain_end', runId, parentRunId, {
383
- outputs,
384
- tags
385
- }, outputs);
386
- }
387
- handleChainError(error, runId, parentRunId, tags, _kwargs) {
388
- this._logAndPopTraceOrSpan('on_chain_error', runId, parentRunId, {
389
- error,
390
- tags
391
- }, error);
392
- }
393
- handleChatModelStart(serialized, messages, runId, parentRunId, extraParams, tags, metadata, runName) {
394
- this._logDebugEvent('on_chat_model_start', runId, parentRunId, {
395
- messages,
396
- tags
397
- });
398
- this._setParentOfRun(runId, parentRunId);
399
- // Flatten the two-dimensional messages and convert each message to a plain object
400
- const input = messages.flat().map(m => this._convertMessageToDict(m));
401
- this._setLLMMetadata(serialized, runId, input, metadata, extraParams, runName);
402
- }
403
- handleLLMStart(serialized, prompts, runId, parentRunId, extraParams, tags, metadata, runName) {
404
- this._logDebugEvent('on_llm_start', runId, parentRunId, {
405
- prompts,
406
- tags
407
- });
408
- this._setParentOfRun(runId, parentRunId);
409
- this._setLLMMetadata(serialized, runId, prompts, metadata, extraParams, runName);
410
- }
411
- handleLLMEnd(output, runId, parentRunId, tags, _extraParams) {
412
- this._logAndPopGeneration('on_llm_end', runId, parentRunId, {
413
- output,
414
- tags
415
- }, output);
416
- }
417
- handleLLMError(err, runId, parentRunId, tags, _extraParams) {
418
- this._logAndPopGeneration('on_llm_error', runId, parentRunId, {
419
- err,
420
- tags
421
- }, err);
422
- }
423
- handleToolStart(tool, input, runId, parentRunId, tags, metadata, runName) {
424
- this._logAndSetTraceOrSpan('on_tool_start', tool, input, runId, parentRunId, {
425
- input,
426
- tags
427
- }, tags, metadata, runName);
428
- }
429
- handleToolEnd(output, runId, parentRunId, tags) {
430
- this._logAndPopTraceOrSpan('on_tool_end', runId, parentRunId, {
431
- output,
432
- tags
433
- }, output);
434
- }
435
- handleToolError(err, runId, parentRunId, tags) {
436
- this._logAndPopTraceOrSpan('on_tool_error', runId, parentRunId, {
437
- err,
438
- tags
439
- }, err);
440
- }
441
- handleRetrieverStart(retriever, query, runId, parentRunId, tags, metadata, name) {
442
- this._logAndSetTraceOrSpan('on_retriever_start', retriever, query, runId, parentRunId, {
443
- query,
444
- tags
445
- }, tags, metadata, name);
446
- }
447
- handleRetrieverEnd(documents, runId, parentRunId, tags) {
448
- this._logAndPopTraceOrSpan('on_retriever_end', runId, parentRunId, {
449
- documents,
450
- tags
451
- }, documents);
452
- }
453
- handleRetrieverError(err, runId, parentRunId, tags) {
454
- this._logAndPopTraceOrSpan('on_retriever_error', runId, parentRunId, {
455
- err,
456
- tags
457
- }, err);
458
- }
459
- handleAgentAction(action, runId, parentRunId, tags) {
460
- this._logDebugEvent('on_agent_action', runId, parentRunId, {
461
- action,
462
- tags
463
- });
464
- this._setParentOfRun(runId, parentRunId);
465
- this._setTraceOrSpanMetadata(null, action, runId, parentRunId);
466
- }
467
- handleAgentEnd(action, runId, parentRunId, tags) {
468
- this._logDebugEvent('on_agent_finish', runId, parentRunId, {
469
- action,
470
- tags
471
- });
472
- this._popRunAndCaptureTraceOrSpan(runId, parentRunId, action);
473
- }
474
-
475
- // ===== PRIVATE HELPERS =====
476
-
477
- _logAndSetTraceOrSpan(eventName, serialized, input, runId, parentRunId, debugPayload, tags, metadata, runName) {
478
- this._logDebugEvent(eventName, runId, parentRunId, debugPayload);
479
- this._setParentOfRun(runId, parentRunId);
480
- this._setTraceOrSpanMetadata(serialized, input, runId, parentRunId, metadata, tags, runName);
481
- }
482
- _logAndPopTraceOrSpan(eventName, runId, parentRunId, debugPayload, result) {
483
- this._logDebugEvent(eventName, runId, parentRunId, debugPayload);
484
- this._popRunAndCaptureTraceOrSpan(runId, parentRunId, result);
485
- }
486
- _logAndPopGeneration(eventName, runId, parentRunId, debugPayload, result) {
487
- this._logDebugEvent(eventName, runId, parentRunId, debugPayload);
488
- this._popRunAndCaptureGeneration(runId, parentRunId, result);
489
- }
490
- _setParentOfRun(runId, parentRunId) {
491
- if (parentRunId) {
492
- this.parentTree[runId] = parentRunId;
493
- }
494
- }
495
- _popParentOfRun(runId) {
496
- delete this.parentTree[runId];
497
- }
498
- _findRootRun(runId) {
499
- let id = runId;
500
- while (this.parentTree[id]) {
501
- id = this.parentTree[id];
502
- }
503
- return id;
504
- }
505
- _setTraceOrSpanMetadata(serialized, input, runId, parentRunId, ...args) {
506
- // Use default names if not provided: if this is a top-level run, we mark it as a trace, otherwise as a span.
507
- const defaultName = parentRunId ? 'span' : 'trace';
508
- const runName = this._getLangchainRunName(serialized, ...args) || defaultName;
509
- this.runs[runId] = {
510
- name: runName,
511
- input,
512
- startTime: Date.now()
513
- };
514
- }
515
- _setLLMMetadata(serialized, runId, messages, metadata, extraParams, runName) {
516
- const runNameFound = this._getLangchainRunName(serialized, {
517
- extraParams,
518
- runName
519
- }) || 'generation';
520
- const generation = {
521
- name: runNameFound,
522
- input: sanitizeLangChain(messages, this.client),
523
- startTime: Date.now()
524
- };
525
- if (extraParams) {
526
- generation.modelParams = getModelParams(extraParams.invocation_params);
527
- if (extraParams.invocation_params && extraParams.invocation_params.tools) {
528
- generation.tools = extraParams.invocation_params.tools;
529
- }
530
- }
531
- if (metadata) {
532
- if (metadata.ls_model_name) {
533
- generation.model = metadata.ls_model_name;
534
- }
535
- if (metadata.ls_provider) {
536
- generation.provider = metadata.ls_provider;
537
- }
538
- }
539
- if (serialized && 'kwargs' in serialized && serialized.kwargs.openai_api_base) {
540
- generation.baseUrl = serialized.kwargs.openai_api_base;
541
- }
542
- this.runs[runId] = generation;
543
- }
544
- _popRunMetadata(runId) {
545
- const endTime = Date.now();
546
- const run = this.runs[runId];
547
- if (!run) {
548
- console.warn(`No run metadata found for run ${runId}`);
549
- return undefined;
550
- }
551
- run.endTime = endTime;
552
- delete this.runs[runId];
553
- return run;
554
- }
555
- _getTraceId(runId) {
556
- return this.traceId ? String(this.traceId) : this._findRootRun(runId);
557
- }
558
- _getParentRunId(traceId, _runId, parentRunId) {
559
- // Replace the parent-run if not found in our stored parent tree.
560
- if (parentRunId && !this.parentTree[parentRunId]) {
561
- return traceId;
562
- }
563
- return parentRunId;
564
- }
565
- _safeCapture(message) {
566
- try {
567
- captureAiEvent(this.client, message);
568
- } catch {
569
- // Telemetry delivery must never affect the LangChain callback lifecycle.
570
- }
571
- }
572
- _popRunAndCaptureTraceOrSpan(runId, parentRunId, outputs) {
573
- const traceId = this._getTraceId(runId);
574
- const isSpan = Boolean(parentRunId || this.parentTree[runId]);
575
- this._popParentOfRun(runId);
576
- const run = this._popRunMetadata(runId);
577
- if (!run) {
578
- return;
579
- }
580
- if ('modelParams' in run) {
581
- console.warn(`Run ${runId} is a generation, but attempted to be captured as a trace/span.`);
582
- return;
583
- }
584
- const actualParentRunId = this._getParentRunId(traceId, runId, parentRunId);
585
- this._captureTraceOrSpan(traceId, runId, run, outputs, isSpan, actualParentRunId);
586
- }
587
- _captureTraceOrSpan(traceId, runId, run, outputs, isSpan, parentRunId) {
588
- const eventName = isSpan ? '$ai_span' : '$ai_trace';
589
- const latency = run.endTime ? (run.endTime - run.startTime) / 1000 : 0;
590
- const eventProperties = {
591
- $ai_lib: 'posthog-ai',
592
- $ai_lib_version: version,
593
- $ai_trace_id: traceId,
594
- $ai_input_state: withPrivacyMode(this.client, this.privacyMode, sanitizeLangChain(run.input, this.client)),
595
- $ai_latency: latency,
596
- $ai_span_name: run.name,
597
- $ai_span_id: runId,
598
- $ai_framework: 'langchain'
599
- };
600
- if (parentRunId) {
601
- eventProperties['$ai_parent_id'] = parentRunId;
602
- }
603
- Object.assign(eventProperties, this.properties);
604
- if (!this.distinctId) {
605
- eventProperties['$process_person_profile'] = false;
606
- }
607
- if (outputs instanceof Error) {
608
- if (isLangGraphControlFlow(outputs)) {
609
- // GraphInterrupt carries the pending interrupts (e.g. the question posed to a human).
610
- // Surface them under the same `__interrupt__` key LangGraph hands back to the caller,
611
- // so an interrupted span stays distinguishable from a node that returned nothing.
612
- const interrupts = outputs.interrupts;
613
- if (interrupts !== undefined) {
614
- eventProperties['$ai_output_state'] = withPrivacyMode(this.client, this.privacyMode, sanitizeLangChain({
615
- __interrupt__: interrupts
616
- }, this.client));
617
- }
618
- } else {
619
- eventProperties['$ai_error'] = stringifyError(outputs);
620
- eventProperties['$ai_is_error'] = true;
621
- }
622
- } else if (outputs !== undefined) {
623
- eventProperties['$ai_output_state'] = withPrivacyMode(this.client, this.privacyMode, sanitizeLangChain(outputs, this.client));
624
- }
625
- this._safeCapture({
626
- distinctId: this.distinctId ? this.distinctId.toString() : runId,
627
- event: eventName,
628
- properties: eventProperties,
629
- groups: this.groups
630
- });
631
- }
632
- _popRunAndCaptureGeneration(runId, parentRunId, response) {
633
- const traceId = this._getTraceId(runId);
634
- this._popParentOfRun(runId);
635
- const run = this._popRunMetadata(runId);
636
- if (!run || typeof run !== 'object' || !('modelParams' in run)) {
637
- console.warn(`Run ${runId} is not a generation, but attempted to be captured as such.`);
638
- return;
639
- }
640
- const actualParentRunId = this._getParentRunId(traceId, runId, parentRunId);
641
- this._captureGeneration(traceId, runId, run, response, actualParentRunId);
642
- }
643
- _captureGeneration(traceId, runId, run, output, parentRunId) {
644
- const latency = run.endTime ? (run.endTime - run.startTime) / 1000 : 0;
645
- warnIfPostHogAiGateway(run.baseUrl);
646
- const eventProperties = {
647
- $ai_lib: 'posthog-ai',
648
- $ai_lib_version: version,
649
- $ai_trace_id: traceId,
650
- $ai_span_id: runId,
651
- $ai_span_name: run.name,
652
- $ai_provider: run.provider,
653
- $ai_model: run.model,
654
- $ai_model_parameters: run.modelParams,
655
- $ai_input: withPrivacyMode(this.client, this.privacyMode, run.input),
656
- $ai_http_status: 200,
657
- $ai_latency: latency,
658
- $ai_base_url: run.baseUrl,
659
- $ai_framework: 'langchain'
660
- };
661
- if (parentRunId) {
662
- eventProperties['$ai_parent_id'] = parentRunId;
663
- }
664
- if (run.tools) {
665
- eventProperties['$ai_tools'] = run.tools;
666
- }
667
- if (output instanceof Error) {
668
- eventProperties['$ai_http_status'] = output.status || 500;
669
- eventProperties['$ai_error'] = stringifyError(output);
670
- eventProperties['$ai_is_error'] = true;
671
- } else {
672
- // Handle token usage
673
- const [inputTokens, outputTokens, additionalTokenData] = this.parseUsage(output, run.provider, run.model);
674
- eventProperties['$ai_input_tokens'] = inputTokens;
675
- eventProperties['$ai_output_tokens'] = outputTokens;
676
-
677
- // Add additional token data to properties
678
- if (additionalTokenData.cacheReadInputTokens) {
679
- eventProperties['$ai_cache_read_input_tokens'] = additionalTokenData.cacheReadInputTokens;
680
- }
681
- if (additionalTokenData.cacheWriteInputTokens) {
682
- eventProperties['$ai_cache_creation_input_tokens'] = additionalTokenData.cacheWriteInputTokens;
683
- }
684
- if (additionalTokenData.cacheWrite5mInputTokens !== undefined && additionalTokenData.cacheWrite1hInputTokens !== undefined) {
685
- eventProperties['$ai_cache_creation_5m_input_tokens'] = additionalTokenData.cacheWrite5mInputTokens;
686
- eventProperties['$ai_cache_creation_1h_input_tokens'] = additionalTokenData.cacheWrite1hInputTokens;
687
- }
688
- if (additionalTokenData.reasoningTokens) {
689
- eventProperties['$ai_reasoning_tokens'] = additionalTokenData.reasoningTokens;
690
- }
691
- if (additionalTokenData.webSearchCount !== undefined) {
692
- eventProperties['$ai_web_search_count'] = additionalTokenData.webSearchCount;
693
- }
694
-
695
- // Extract stop reason from generation info
696
- const stopReason = this._extractStopReason(output);
697
- if (stopReason) {
698
- eventProperties['$ai_stop_reason'] = stopReason;
699
- }
700
-
701
- // Handle generations/completions
702
- let completions;
703
- if (output.generations && Array.isArray(output.generations)) {
704
- const lastGeneration = output.generations[output.generations.length - 1];
705
- if (Array.isArray(lastGeneration) && lastGeneration.length > 0) {
706
- // Check if this is a ChatGeneration by looking at the first item
707
- const isChatGeneration = 'message' in lastGeneration[0] && lastGeneration[0].message;
708
- if (isChatGeneration) {
709
- // For ChatGeneration, convert messages to dict format
710
- completions = lastGeneration.map(gen => {
711
- return this._convertMessageToDict(gen.message);
712
- });
713
- } else {
714
- // For non-ChatGeneration, extract raw response
715
- completions = lastGeneration.map(gen => {
716
- return this._extractRawResponse(gen);
717
- });
718
- }
719
- }
720
- }
721
- if (completions) {
722
- eventProperties['$ai_output_choices'] = withPrivacyMode(this.client, this.privacyMode, completions);
723
- }
724
- }
725
- Object.assign(eventProperties, this.properties);
726
- if (!this.distinctId) {
727
- eventProperties['$process_person_profile'] = false;
728
- }
729
- this._safeCapture({
730
- distinctId: this.distinctId ? this.distinctId.toString() : traceId,
731
- event: '$ai_generation',
732
- properties: eventProperties,
733
- groups: this.groups
734
- });
735
- }
736
- _logDebugEvent(eventName, runId, parentRunId, extra) {
737
- if (this.debug) {
738
- console.log(`Event: ${eventName}, runId: ${runId}, parentRunId: ${parentRunId}, extra:`, extra);
739
- }
740
- }
741
- _getLangchainRunName(serialized, ...args) {
742
- if (args && args.length > 0) {
743
- for (const arg of args) {
744
- // LangChain hands runName through as a bare string, not wrapped in an object
745
- if (typeof arg === 'string' && arg) {
746
- return arg;
747
- }
748
- if (arg && typeof arg === 'object') {
749
- if (arg.name) {
750
- return arg.name;
751
- }
752
- if (arg.runName) {
753
- return arg.runName;
754
- }
755
- }
756
- }
757
- }
758
- if (serialized && serialized.name) {
759
- return serialized.name;
760
- }
761
- if (serialized && serialized.id) {
762
- return Array.isArray(serialized.id) ? serialized.id[serialized.id.length - 1] : serialized.id;
763
- }
764
- return undefined;
765
- }
766
- _convertLcToolCallsToOai(toolCalls) {
767
- return toolCalls.map(toolCall => ({
768
- type: 'function',
769
- id: toolCall.id,
770
- function: {
771
- name: toolCall.name,
772
- arguments: JSON.stringify(toolCall.args)
773
- }
774
- }));
775
- }
776
- _extractRawResponse(generation) {
777
- // Extract the response from the last response of the LLM call
778
- // We return the text of the response if not empty
779
- if (generation.text != null && generation.text.trim() !== '') {
780
- return generation.text.trim();
781
- } else if (generation.message) {
782
- // Additional kwargs contains the response in case of tool usage
783
- return generation.message.additional_kwargs || generation.message.additionalKwargs || {};
784
- } else {
785
- // Not tool usage, some LLM responses can be simply empty
786
- return '';
787
- }
788
- }
789
- _convertMessageToDict(message) {
790
- let messageDict = {};
791
- const messageType = message.getType();
792
- switch (messageType) {
793
- case 'human':
794
- messageDict = {
795
- role: 'user',
796
- content: message.content
797
- };
798
- break;
799
- case 'ai':
800
- messageDict = {
801
- role: 'assistant',
802
- content: message.content
803
- };
804
- if (message.tool_calls) {
805
- messageDict.tool_calls = this._convertLcToolCallsToOai(message.tool_calls);
806
- }
807
- break;
808
- case 'system':
809
- messageDict = {
810
- role: 'system',
811
- content: message.content
812
- };
813
- break;
814
- case 'tool':
815
- messageDict = {
816
- role: 'tool',
817
- content: message.content
818
- };
819
- break;
820
- case 'function':
821
- messageDict = {
822
- role: 'function',
823
- content: message.content
824
- };
825
- break;
826
- default:
827
- messageDict = {
828
- role: messageType,
829
- content: toContentString(message.content)
830
- };
831
- break;
832
- }
833
- if (message.additional_kwargs) {
834
- messageDict = {
835
- ...messageDict,
836
- ...message.additional_kwargs
837
- };
838
- }
839
-
840
- // Sanitize the message content to redact base64 images
841
- return sanitizeLangChain(messageDict, this.client);
842
- }
843
- _extractStopReason(output) {
844
- if (!output.generations || !Array.isArray(output.generations)) {
845
- return undefined;
846
- }
847
- const lastGeneration = output.generations[output.generations.length - 1];
848
- if (!Array.isArray(lastGeneration) || lastGeneration.length === 0) {
849
- return undefined;
850
- }
851
- const gen = lastGeneration[0];
852
- const messageResponseMetadata = gen.message?.response_metadata;
853
- const generationResponseMetadata = gen.generationInfo?.response_metadata;
854
- const stopReason = messageResponseMetadata?.finish_reason || messageResponseMetadata?.stop_reason || gen.generationInfo?.finish_reason || generationResponseMetadata?.stop_reason || generationResponseMetadata?.finish_reason || gen.generationInfo?.stop_reason ||
855
- // The Responses API reports no finish_reason. An early stop is named by
856
- // `incomplete_details.reason`, and `status` covers the rest, matching the
857
- // native OpenAI Responses wrapper.
858
- messageResponseMetadata?.incomplete_details?.reason || generationResponseMetadata?.incomplete_details?.reason || messageResponseMetadata?.status || generationResponseMetadata?.status;
859
- return stopReason != null ? String(stopReason) : undefined;
860
- }
861
- _extractCacheCreationTtlBreakdown(cacheCreation, aggregateValues) {
862
- if (!isObject(cacheCreation)) {
863
- return undefined;
864
- }
865
- const {
866
- ephemeral_5m_input_tokens: cache5m,
867
- ephemeral_1h_input_tokens: cache1h
868
- } = cacheCreation;
869
- const providedValues = [cache5m, cache1h].filter(value => value != null);
870
- if (providedValues.length === 0 || !providedValues.every(value => typeof value === 'number' && Number.isFinite(value) && value >= 0)) {
871
- return undefined;
872
- }
873
- const breakdown = [typeof cache5m === 'number' ? cache5m : 0, typeof cache1h === 'number' ? cache1h : 0];
874
- const total = breakdown[0] + breakdown[1];
875
- const validAggregates = aggregateValues.filter(value => typeof value === 'number' && Number.isFinite(value) && value >= 0);
876
- return total > 0 && !validAggregates.some(aggregate => aggregate !== total) ? breakdown : undefined;
877
- }
878
- _extractBedrockCacheCreationTtlBreakdown(cacheDetails, aggregateValues) {
879
- if (!Array.isArray(cacheDetails)) {
880
- return undefined;
881
- }
882
- let cache5m = 0;
883
- let cache1h = 0;
884
- for (const detail of cacheDetails) {
885
- if (!isObject(detail)) {
886
- continue;
887
- }
888
- const ttl = typeof detail.ttl === 'string' ? detail.ttl.toLowerCase() : undefined;
889
- const inputTokens = detail.inputTokens;
890
- if (ttl !== '5m' && ttl !== 't5m' && ttl !== '1h' && ttl !== 't1h' || typeof inputTokens !== 'number' || !Number.isFinite(inputTokens) || inputTokens < 0) {
891
- continue;
892
- }
893
- if (ttl === '5m' || ttl === 't5m') {
894
- cache5m += inputTokens;
895
- } else {
896
- cache1h += inputTokens;
897
- }
898
- }
899
- const total = cache5m + cache1h;
900
- const validAggregates = aggregateValues.filter(value => typeof value === 'number' && Number.isFinite(value) && value >= 0);
901
- if (total === 0 || validAggregates.some(aggregate => aggregate !== total)) {
902
- return undefined;
903
- }
904
- return [cache5m, cache1h];
905
- }
906
- _parseUsageModel(usage, provider, model, inputIncludesCacheTokens = true, rawUsage) {
907
- const conversionList = [['promptTokens', 'input'], ['completionTokens', 'output'], ['input_tokens', 'input'], ['output_tokens', 'output'], ['prompt_token_count', 'input'], ['candidates_token_count', 'output'], ['inputTokenCount', 'input'], ['outputTokenCount', 'output'], ['input_token_count', 'input'], ['generated_token_count', 'output']];
908
- const parsedUsage = conversionList.reduce((acc, [modelKey, typeKey]) => {
909
- const value = usage[modelKey];
910
- if (value != null) {
911
- const finalCount = Array.isArray(value) ? value.reduce((sum, tokenCount) => sum + tokenCount, 0) : value;
912
- acc[typeKey] = finalCount;
913
- }
914
- return acc;
915
- }, {
916
- input: 0,
917
- output: 0
918
- });
919
-
920
- // Extract additional token details like cached tokens and reasoning tokens
921
- const additionalTokenData = {};
922
-
923
- // Check for cached tokens in various formats
924
- if (usage.prompt_tokens_details?.cached_tokens != null) {
925
- additionalTokenData.cacheReadInputTokens = usage.prompt_tokens_details.cached_tokens;
926
- } else if (usage.input_token_details?.cache_read != null) {
927
- additionalTokenData.cacheReadInputTokens = usage.input_token_details.cache_read;
928
- } else if (usage.cachedPromptTokens != null) {
929
- additionalTokenData.cacheReadInputTokens = usage.cachedPromptTokens;
930
- } else if (usage.cache_read_input_tokens != null) {
931
- additionalTokenData.cacheReadInputTokens = usage.cache_read_input_tokens;
932
- }
933
-
934
- // Check for cache write/creation tokens in various formats
935
- if (usage.cache_creation_input_tokens != null) {
936
- additionalTokenData.cacheWriteInputTokens = usage.cache_creation_input_tokens;
937
- } else if (usage.input_token_details?.cache_creation != null) {
938
- additionalTokenData.cacheWriteInputTokens = usage.input_token_details.cache_creation;
939
- }
940
- const directCacheCreationAggregates = [usage.cache_creation_input_tokens, usage.input_token_details?.cache_creation, usage.cacheWriteInputTokens, rawUsage?.cache_creation_input_tokens, rawUsage?.input_token_details?.cache_creation, rawUsage?.cacheWriteInputTokens, additionalTokenData.cacheWriteInputTokens];
941
- const cacheCreationTtl = this._extractCacheCreationTtlBreakdown(usage.cache_creation, directCacheCreationAggregates) ?? this._extractCacheCreationTtlBreakdown(rawUsage?.cache_creation, directCacheCreationAggregates) ?? this._extractBedrockCacheCreationTtlBreakdown(usage.cacheDetails, [usage.cacheWriteInputTokens, additionalTokenData.cacheWriteInputTokens]) ?? this._extractBedrockCacheCreationTtlBreakdown(rawUsage?.cacheDetails, [rawUsage?.cacheWriteInputTokens, additionalTokenData.cacheWriteInputTokens]);
942
- if (cacheCreationTtl) {
943
- const [cacheWrite5mInputTokens, cacheWrite1hInputTokens] = cacheCreationTtl;
944
- additionalTokenData.cacheWrite5mInputTokens = cacheWrite5mInputTokens;
945
- additionalTokenData.cacheWrite1hInputTokens = cacheWrite1hInputTokens;
946
- additionalTokenData.cacheWriteInputTokens = cacheWrite5mInputTokens + cacheWrite1hInputTokens;
947
- }
948
-
949
- // Check for reasoning tokens in various formats
950
- if (usage.completion_tokens_details?.reasoning_tokens != null) {
951
- additionalTokenData.reasoningTokens = usage.completion_tokens_details.reasoning_tokens;
952
- } else if (usage.output_token_details?.reasoning != null) {
953
- additionalTokenData.reasoningTokens = usage.output_token_details.reasoning;
954
- } else if (usage.reasoningTokens != null) {
955
- additionalTokenData.reasoningTokens = usage.reasoningTokens;
956
- }
957
-
958
- // Extract web search counts from various provider formats
959
- let webSearchCount;
960
-
961
- // Priority 1: Exact Count
962
- // Check Anthropic format (server_tool_use.web_search_requests)
963
- if (usage.server_tool_use?.web_search_requests !== undefined) {
964
- webSearchCount = usage.server_tool_use.web_search_requests;
965
- }
966
- // Priority 2: Binary Detection (1 or 0)
967
- // Check for citations array (Perplexity)
968
- else if (usage.citations && Array.isArray(usage.citations) && usage.citations.length > 0) {
969
- webSearchCount = 1;
970
- }
971
- // Check for search_results array (Perplexity via OpenRouter)
972
- else if (usage.search_results && Array.isArray(usage.search_results) && usage.search_results.length > 0) {
973
- webSearchCount = 1;
974
- }
975
- // Check for search_context_size (Perplexity via OpenRouter)
976
- else if (usage.search_context_size) {
977
- webSearchCount = 1;
978
- }
979
- // Check for annotations with url_citation type
980
- else if (usage.annotations && Array.isArray(usage.annotations)) {
981
- const hasUrlCitation = usage.annotations.some(ann => {
982
- return ann && typeof ann === 'object' && 'type' in ann && ann.type === 'url_citation';
983
- });
984
- if (hasUrlCitation) {
985
- webSearchCount = 1;
986
- }
987
- }
988
- // Check Gemini format (grounding metadata - binary 0 or 1)
989
- else if (usage.grounding_metadata?.grounding_support !== undefined || usage.grounding_metadata?.web_search_queries !== undefined) {
990
- webSearchCount = 1;
991
- }
992
- if (webSearchCount !== undefined) {
993
- additionalTokenData.webSearchCount = webSearchCount;
994
- }
995
-
996
- // For Anthropic providers, LangChain reports input_tokens as the sum of all input tokens.
997
- // Our cost calculation expects them to be separate for Anthropic, so we subtract cache tokens.
998
- // Both cache_read and cache_write tokens should be subtracted since Anthropic's raw API
999
- // reports input_tokens as tokens NOT read from or used to create a cache.
1000
- // For other providers (OpenAI, etc.), input_tokens already excludes cache tokens as expected.
1001
- // Match logic consistent with plugin-server: exact match on provider OR substring match on model
1002
- let isAnthropic = false;
1003
- if (provider && provider.toLowerCase() === 'anthropic') {
1004
- isAnthropic = true;
1005
- } else if (model && model.toLowerCase().includes('anthropic')) {
1006
- isAnthropic = true;
1007
- }
1008
- if (isAnthropic && inputIncludesCacheTokens && parsedUsage.input) {
1009
- const cacheTokens = (additionalTokenData.cacheReadInputTokens || 0) + (additionalTokenData.cacheWriteInputTokens || 0);
1010
- if (cacheTokens > 0) {
1011
- parsedUsage.input = Math.max(parsedUsage.input - cacheTokens, 0);
1012
- }
1013
- }
1014
- return [parsedUsage.input, parsedUsage.output, additionalTokenData];
1015
- }
1016
- parseUsage(response, provider, model) {
1017
- const isNonEmptyUsage = usage => isObject(usage) && Object.keys(usage).length > 0;
1018
- const firstNonEmptyUsage = (...candidates) => candidates.find(isNonEmptyUsage);
1019
- let normalizedGenerationUsage;
1020
- let rawGenerationUsage;
1021
- let fallbackGenerationUsage;
1022
- for (const generation of response.generations ?? []) {
1023
- for (const genChunk of generation) {
1024
- const generationInfo = genChunk.generationInfo ?? {};
1025
- const message = 'message' in genChunk ? genChunk.message : undefined;
1026
- const messageUsage = message && typeof message === 'object' && 'usage_metadata' in message ? message.usage_metadata : undefined;
1027
- normalizedGenerationUsage = firstNonEmptyUsage(normalizedGenerationUsage, messageUsage, generationInfo.usage_metadata);
1028
- const messageResponseMetadata = message && typeof message === 'object' && 'response_metadata' in message && isObject(message.response_metadata) ? message.response_metadata : undefined;
1029
- const generationResponseMetadata = isObject(generationInfo.response_metadata) ? generationInfo.response_metadata : undefined;
1030
- const messageStreamMetadata = isObject(messageResponseMetadata?.metadata) ? messageResponseMetadata.metadata : undefined;
1031
- const generationStreamMetadata = isObject(generationResponseMetadata?.metadata) ? generationResponseMetadata.metadata : undefined;
1032
- rawGenerationUsage = firstNonEmptyUsage(rawGenerationUsage, messageResponseMetadata?.usage, messageStreamMetadata?.usage, generationResponseMetadata?.usage, generationStreamMetadata?.usage);
1033
- fallbackGenerationUsage = firstNonEmptyUsage(fallbackGenerationUsage, messageResponseMetadata?.['amazon-bedrock-invocationMetrics'], generationResponseMetadata?.['amazon-bedrock-invocationMetrics'], generationInfo.usage_metadata);
1034
- }
1035
- }
1036
- const isAnthropic = provider?.toLowerCase() === 'anthropic' || model?.toLowerCase().includes('anthropic') === true;
1037
- if (isAnthropic && isNonEmptyUsage(normalizedGenerationUsage)) {
1038
- return this._parseUsageModel(normalizedGenerationUsage, provider, model, true, rawGenerationUsage);
1039
- }
1040
- const llmUsageKeys = ['token_usage', 'usage', 'tokenUsage'];
1041
- if (response.llmOutput != null) {
1042
- for (const key of llmUsageKeys) {
1043
- const llmUsage = response.llmOutput[key];
1044
- if (!isNonEmptyUsage(llmUsage)) {
1045
- continue;
1046
- }
1047
- return this._parseUsageModel(llmUsage, provider, model, key !== 'usage', llmUsage);
1048
- }
1049
- }
1050
- if (isNonEmptyUsage(normalizedGenerationUsage)) {
1051
- return this._parseUsageModel(normalizedGenerationUsage, provider, model, true, rawGenerationUsage);
1052
- }
1053
- if (isNonEmptyUsage(rawGenerationUsage)) {
1054
- return this._parseUsageModel(rawGenerationUsage, provider, model, false, rawGenerationUsage);
1055
- }
1056
- if (isNonEmptyUsage(fallbackGenerationUsage)) {
1057
- return this._parseUsageModel(fallbackGenerationUsage, provider, model);
1058
- }
1059
- return [0, 0, {}];
1060
- }
324
+ //#endregion
325
+ //#region src/openai/utils.ts
326
+ const TERMINAL_RESPONSE_STATUSES = /* @__PURE__ */ new Set([
327
+ "completed",
328
+ "failed",
329
+ "cancelled",
330
+ "incomplete"
331
+ ]);
332
+ /**
333
+ * Checks whether a Responses API response has reached a status that should
334
+ * produce a final `$ai_generation` event.
335
+ */
336
+ function isTerminalResponse(response) {
337
+ return !!response?.status && TERMINAL_RESPONSE_STATUSES.has(response.status);
1061
338
  }
1062
-
339
+ /**
340
+ * Maps a Responses API outcome to a `$ai_stop_reason`. An incomplete run is
341
+ * named by what cut it short (`incomplete_details.reason`, e.g.
342
+ * `max_output_tokens`); the other terminal statuses stand for themselves.
343
+ * Non-terminal lifecycle statuses (`queued`, `in_progress`) are not stop
344
+ * reasons, so they yield undefined.
345
+ */
346
+ function responsesStopReason(response) {
347
+ if (!response || !isTerminalResponse(response)) return;
348
+ if (response.status === "incomplete" && response.incomplete_details?.reason) return response.incomplete_details.reason;
349
+ return response.status ?? void 0;
350
+ }
351
+ //#endregion
352
+ //#region src/langchain/callbacks.ts
353
+ const isLangGraphControlFlow = (error) => error.is_bubble_up === true;
354
+ var LangChainCallbackHandler = class extends BaseCallbackHandler {
355
+ constructor(options) {
356
+ if (!options.client) throw new Error("PostHog client is required");
357
+ super();
358
+ this.name = "PosthogCallbackHandler";
359
+ this.runs = {};
360
+ this.parentTree = {};
361
+ this.client = options.client;
362
+ this.distinctId = options.distinctId;
363
+ this.traceId = options.traceId;
364
+ this.properties = options.properties || {};
365
+ this.privacyMode = options.privacyMode || false;
366
+ this.groups = options.groups || {};
367
+ this.debug = options.debug || false;
368
+ }
369
+ handleChainStart(chain, inputs, runId, parentRunId, tags, metadata, _runType, runName, extra) {
370
+ this._logDebugEvent("on_chain_start", runId, parentRunId, {
371
+ inputs,
372
+ tags
373
+ });
374
+ this._setParentOfRun(runId, parentRunId);
375
+ this._setTraceOrSpanMetadata(chain, inputs, runId, parentRunId, metadata, tags, runName);
376
+ if (typeof extra?.posthogStartTime === "number" && Number.isFinite(extra.posthogStartTime)) this.runs[runId].startTime = extra.posthogStartTime;
377
+ }
378
+ handleChainEnd(outputs, runId, parentRunId, tags, _kwargs) {
379
+ this._logAndPopTraceOrSpan("on_chain_end", runId, parentRunId, {
380
+ outputs,
381
+ tags
382
+ }, outputs);
383
+ }
384
+ handleChainError(error, runId, parentRunId, tags, _kwargs) {
385
+ this._logAndPopTraceOrSpan("on_chain_error", runId, parentRunId, {
386
+ error,
387
+ tags
388
+ }, error);
389
+ }
390
+ handleChatModelStart(serialized, messages, runId, parentRunId, extraParams, tags, metadata, runName) {
391
+ this._logDebugEvent("on_chat_model_start", runId, parentRunId, {
392
+ messages,
393
+ tags
394
+ });
395
+ this._setParentOfRun(runId, parentRunId);
396
+ const input = messages.flat().map((m) => this._convertMessageToDict(m));
397
+ this._setLLMMetadata(serialized, runId, input, metadata, extraParams, runName);
398
+ }
399
+ handleLLMStart(serialized, prompts, runId, parentRunId, extraParams, tags, metadata, runName) {
400
+ this._logDebugEvent("on_llm_start", runId, parentRunId, {
401
+ prompts,
402
+ tags
403
+ });
404
+ this._setParentOfRun(runId, parentRunId);
405
+ this._setLLMMetadata(serialized, runId, prompts, metadata, extraParams, runName);
406
+ }
407
+ handleLLMEnd(output, runId, parentRunId, tags, _extraParams) {
408
+ this._logAndPopGeneration("on_llm_end", runId, parentRunId, {
409
+ output,
410
+ tags
411
+ }, output);
412
+ }
413
+ handleLLMError(err, runId, parentRunId, tags, _extraParams) {
414
+ this._logAndPopGeneration("on_llm_error", runId, parentRunId, {
415
+ err,
416
+ tags
417
+ }, err);
418
+ }
419
+ handleToolStart(tool, input, runId, parentRunId, tags, metadata, runName) {
420
+ this._logAndSetTraceOrSpan("on_tool_start", tool, input, runId, parentRunId, {
421
+ input,
422
+ tags
423
+ }, tags, metadata, runName);
424
+ }
425
+ handleToolEnd(output, runId, parentRunId, tags) {
426
+ this._logAndPopTraceOrSpan("on_tool_end", runId, parentRunId, {
427
+ output,
428
+ tags
429
+ }, output);
430
+ }
431
+ handleToolError(err, runId, parentRunId, tags) {
432
+ this._logAndPopTraceOrSpan("on_tool_error", runId, parentRunId, {
433
+ err,
434
+ tags
435
+ }, err);
436
+ }
437
+ handleRetrieverStart(retriever, query, runId, parentRunId, tags, metadata, name) {
438
+ this._logAndSetTraceOrSpan("on_retriever_start", retriever, query, runId, parentRunId, {
439
+ query,
440
+ tags
441
+ }, tags, metadata, name);
442
+ }
443
+ handleRetrieverEnd(documents, runId, parentRunId, tags) {
444
+ this._logAndPopTraceOrSpan("on_retriever_end", runId, parentRunId, {
445
+ documents,
446
+ tags
447
+ }, documents);
448
+ }
449
+ handleRetrieverError(err, runId, parentRunId, tags) {
450
+ this._logAndPopTraceOrSpan("on_retriever_error", runId, parentRunId, {
451
+ err,
452
+ tags
453
+ }, err);
454
+ }
455
+ handleAgentAction(action, runId, parentRunId, tags) {
456
+ this._logDebugEvent("on_agent_action", runId, parentRunId, {
457
+ action,
458
+ tags
459
+ });
460
+ this._setParentOfRun(runId, parentRunId);
461
+ this._setTraceOrSpanMetadata(null, action, runId, parentRunId);
462
+ }
463
+ handleAgentEnd(action, runId, parentRunId, tags) {
464
+ this._logDebugEvent("on_agent_finish", runId, parentRunId, {
465
+ action,
466
+ tags
467
+ });
468
+ this._popRunAndCaptureTraceOrSpan(runId, parentRunId, action);
469
+ }
470
+ _logAndSetTraceOrSpan(eventName, serialized, input, runId, parentRunId, debugPayload, tags, metadata, runName) {
471
+ this._logDebugEvent(eventName, runId, parentRunId, debugPayload);
472
+ this._setParentOfRun(runId, parentRunId);
473
+ this._setTraceOrSpanMetadata(serialized, input, runId, parentRunId, metadata, tags, runName);
474
+ }
475
+ _logAndPopTraceOrSpan(eventName, runId, parentRunId, debugPayload, result) {
476
+ this._logDebugEvent(eventName, runId, parentRunId, debugPayload);
477
+ this._popRunAndCaptureTraceOrSpan(runId, parentRunId, result);
478
+ }
479
+ _logAndPopGeneration(eventName, runId, parentRunId, debugPayload, result) {
480
+ this._logDebugEvent(eventName, runId, parentRunId, debugPayload);
481
+ this._popRunAndCaptureGeneration(runId, parentRunId, result);
482
+ }
483
+ _setParentOfRun(runId, parentRunId) {
484
+ if (parentRunId) this.parentTree[runId] = parentRunId;
485
+ }
486
+ _popParentOfRun(runId) {
487
+ delete this.parentTree[runId];
488
+ }
489
+ _findRootRun(runId) {
490
+ let id = runId;
491
+ while (this.parentTree[id]) id = this.parentTree[id];
492
+ return id;
493
+ }
494
+ _setTraceOrSpanMetadata(serialized, input, runId, parentRunId, ...args) {
495
+ const defaultName = parentRunId ? "span" : "trace";
496
+ const runName = this._getLangchainRunName(serialized, ...args) || defaultName;
497
+ this.runs[runId] = {
498
+ name: runName,
499
+ input,
500
+ startTime: Date.now()
501
+ };
502
+ }
503
+ _setLLMMetadata(serialized, runId, messages, metadata, extraParams, runName) {
504
+ const generation = {
505
+ name: this._getLangchainRunName(serialized, {
506
+ extraParams,
507
+ runName
508
+ }) || "generation",
509
+ input: sanitizeLangChain(messages, this.client),
510
+ startTime: Date.now()
511
+ };
512
+ if (extraParams) {
513
+ generation.modelParams = getModelParams(extraParams.invocation_params);
514
+ if (extraParams.invocation_params && extraParams.invocation_params.tools) generation.tools = extraParams.invocation_params.tools;
515
+ }
516
+ if (metadata) {
517
+ if (metadata.ls_model_name) generation.model = metadata.ls_model_name;
518
+ if (metadata.ls_provider) generation.provider = metadata.ls_provider;
519
+ }
520
+ if (serialized && "kwargs" in serialized && serialized.kwargs.openai_api_base) generation.baseUrl = serialized.kwargs.openai_api_base;
521
+ this.runs[runId] = generation;
522
+ }
523
+ _popRunMetadata(runId) {
524
+ const endTime = Date.now();
525
+ const run = this.runs[runId];
526
+ if (!run) {
527
+ console.warn(`No run metadata found for run ${runId}`);
528
+ return;
529
+ }
530
+ run.endTime = endTime;
531
+ delete this.runs[runId];
532
+ return run;
533
+ }
534
+ _getTraceId(runId) {
535
+ return this.traceId ? String(this.traceId) : this._findRootRun(runId);
536
+ }
537
+ _getParentRunId(traceId, _runId, parentRunId) {
538
+ if (parentRunId && !this.parentTree[parentRunId]) return traceId;
539
+ return parentRunId;
540
+ }
541
+ _safeCapture(message) {
542
+ try {
543
+ captureAiEvent(this.client, message);
544
+ } catch {}
545
+ }
546
+ _popRunAndCaptureTraceOrSpan(runId, parentRunId, outputs) {
547
+ const traceId = this._getTraceId(runId);
548
+ const isSpan = Boolean(parentRunId || this.parentTree[runId]);
549
+ this._popParentOfRun(runId);
550
+ const run = this._popRunMetadata(runId);
551
+ if (!run) return;
552
+ if ("modelParams" in run) {
553
+ console.warn(`Run ${runId} is a generation, but attempted to be captured as a trace/span.`);
554
+ return;
555
+ }
556
+ const actualParentRunId = this._getParentRunId(traceId, runId, parentRunId);
557
+ this._captureTraceOrSpan(traceId, runId, run, outputs, isSpan, actualParentRunId);
558
+ }
559
+ _captureTraceOrSpan(traceId, runId, run, outputs, isSpan, parentRunId) {
560
+ const eventName = isSpan ? "$ai_span" : "$ai_trace";
561
+ const latency = run.endTime ? (run.endTime - run.startTime) / 1e3 : 0;
562
+ const eventProperties = {
563
+ $ai_lib: "posthog-ai",
564
+ $ai_lib_version: version,
565
+ $ai_trace_id: traceId,
566
+ $ai_input_state: withPrivacyMode(this.client, this.privacyMode, sanitizeLangChain(run.input, this.client)),
567
+ $ai_latency: latency,
568
+ $ai_span_name: run.name,
569
+ $ai_span_id: runId,
570
+ $ai_framework: "langchain"
571
+ };
572
+ if (parentRunId) eventProperties["$ai_parent_id"] = parentRunId;
573
+ Object.assign(eventProperties, this.properties);
574
+ if (!this.distinctId) eventProperties["$process_person_profile"] = false;
575
+ if (outputs instanceof Error) {
576
+ if (isLangGraphControlFlow(outputs)) {
577
+ const interrupts = outputs.interrupts;
578
+ if (interrupts !== void 0) eventProperties["$ai_output_state"] = withPrivacyMode(this.client, this.privacyMode, sanitizeLangChain({ __interrupt__: interrupts }, this.client));
579
+ } else {
580
+ eventProperties["$ai_error"] = stringifyError(outputs);
581
+ eventProperties["$ai_is_error"] = true;
582
+ }
583
+ } else if (outputs !== void 0) eventProperties["$ai_output_state"] = withPrivacyMode(this.client, this.privacyMode, sanitizeLangChain(outputs, this.client));
584
+ this._safeCapture({
585
+ distinctId: this.distinctId ? this.distinctId.toString() : runId,
586
+ event: eventName,
587
+ properties: eventProperties,
588
+ groups: this.groups
589
+ });
590
+ }
591
+ _popRunAndCaptureGeneration(runId, parentRunId, response) {
592
+ const traceId = this._getTraceId(runId);
593
+ this._popParentOfRun(runId);
594
+ const run = this._popRunMetadata(runId);
595
+ if (!run || typeof run !== "object" || !("modelParams" in run)) {
596
+ console.warn(`Run ${runId} is not a generation, but attempted to be captured as such.`);
597
+ return;
598
+ }
599
+ const actualParentRunId = this._getParentRunId(traceId, runId, parentRunId);
600
+ this._captureGeneration(traceId, runId, run, response, actualParentRunId);
601
+ }
602
+ _captureGeneration(traceId, runId, run, output, parentRunId) {
603
+ const latency = run.endTime ? (run.endTime - run.startTime) / 1e3 : 0;
604
+ warnIfPostHogAiGateway(run.baseUrl);
605
+ const eventProperties = {
606
+ $ai_lib: "posthog-ai",
607
+ $ai_lib_version: version,
608
+ $ai_trace_id: traceId,
609
+ $ai_span_id: runId,
610
+ $ai_span_name: run.name,
611
+ $ai_provider: run.provider,
612
+ $ai_model: run.model,
613
+ $ai_model_parameters: run.modelParams,
614
+ $ai_input: withPrivacyMode(this.client, this.privacyMode, run.input),
615
+ $ai_http_status: 200,
616
+ $ai_latency: latency,
617
+ $ai_base_url: run.baseUrl,
618
+ $ai_framework: "langchain"
619
+ };
620
+ if (parentRunId) eventProperties["$ai_parent_id"] = parentRunId;
621
+ if (run.tools) eventProperties["$ai_tools"] = run.tools;
622
+ if (output instanceof Error) {
623
+ eventProperties["$ai_http_status"] = output.status || 500;
624
+ eventProperties["$ai_error"] = stringifyError(output);
625
+ eventProperties["$ai_is_error"] = true;
626
+ } else {
627
+ const [inputTokens, outputTokens, additionalTokenData] = this.parseUsage(output, run.provider, run.model);
628
+ eventProperties["$ai_input_tokens"] = inputTokens;
629
+ eventProperties["$ai_output_tokens"] = outputTokens;
630
+ if (additionalTokenData.cacheReadInputTokens) eventProperties["$ai_cache_read_input_tokens"] = additionalTokenData.cacheReadInputTokens;
631
+ if (additionalTokenData.cacheWriteInputTokens) eventProperties["$ai_cache_creation_input_tokens"] = additionalTokenData.cacheWriteInputTokens;
632
+ if (additionalTokenData.cacheWrite5mInputTokens !== void 0 && additionalTokenData.cacheWrite1hInputTokens !== void 0) {
633
+ eventProperties["$ai_cache_creation_5m_input_tokens"] = additionalTokenData.cacheWrite5mInputTokens;
634
+ eventProperties["$ai_cache_creation_1h_input_tokens"] = additionalTokenData.cacheWrite1hInputTokens;
635
+ }
636
+ if (additionalTokenData.reasoningTokens) eventProperties["$ai_reasoning_tokens"] = additionalTokenData.reasoningTokens;
637
+ if (additionalTokenData.webSearchCount !== void 0) eventProperties["$ai_web_search_count"] = additionalTokenData.webSearchCount;
638
+ const stopReason = this._extractStopReason(output);
639
+ if (stopReason) eventProperties["$ai_stop_reason"] = stopReason;
640
+ let completions;
641
+ if (output.generations && Array.isArray(output.generations)) {
642
+ const lastGeneration = output.generations[output.generations.length - 1];
643
+ if (Array.isArray(lastGeneration) && lastGeneration.length > 0) {
644
+ if ("message" in lastGeneration[0] && lastGeneration[0].message) completions = lastGeneration.map((gen) => {
645
+ return this._convertMessageToDict(gen.message);
646
+ });
647
+ else completions = lastGeneration.map((gen) => {
648
+ return this._extractRawResponse(gen);
649
+ });
650
+ }
651
+ }
652
+ if (completions) eventProperties["$ai_output_choices"] = withPrivacyMode(this.client, this.privacyMode, completions);
653
+ }
654
+ Object.assign(eventProperties, this.properties);
655
+ if (!this.distinctId) eventProperties["$process_person_profile"] = false;
656
+ this._safeCapture({
657
+ distinctId: this.distinctId ? this.distinctId.toString() : traceId,
658
+ event: "$ai_generation",
659
+ properties: eventProperties,
660
+ groups: this.groups
661
+ });
662
+ }
663
+ _logDebugEvent(eventName, runId, parentRunId, extra) {
664
+ if (this.debug) console.log(`Event: ${eventName}, runId: ${runId}, parentRunId: ${parentRunId}, extra:`, extra);
665
+ }
666
+ _getLangchainRunName(serialized, ...args) {
667
+ if (args && args.length > 0) for (const arg of args) {
668
+ if (typeof arg === "string" && arg) return arg;
669
+ if (arg && typeof arg === "object") {
670
+ if (arg.name) return arg.name;
671
+ if (arg.runName) return arg.runName;
672
+ }
673
+ }
674
+ if (serialized && serialized.name) return serialized.name;
675
+ if (serialized && serialized.id) return Array.isArray(serialized.id) ? serialized.id[serialized.id.length - 1] : serialized.id;
676
+ }
677
+ _convertLcToolCallsToOai(toolCalls) {
678
+ return toolCalls.map((toolCall) => ({
679
+ type: "function",
680
+ id: toolCall.id,
681
+ function: {
682
+ name: toolCall.name,
683
+ arguments: JSON.stringify(toolCall.args)
684
+ }
685
+ }));
686
+ }
687
+ _extractRawResponse(generation) {
688
+ if (generation.text != null && generation.text.trim() !== "") return generation.text.trim();
689
+ else if (generation.message) return generation.message.additional_kwargs || generation.message.additionalKwargs || {};
690
+ else return "";
691
+ }
692
+ _convertMessageToDict(message) {
693
+ let messageDict = {};
694
+ const messageType = message.getType();
695
+ switch (messageType) {
696
+ case "human":
697
+ messageDict = {
698
+ role: "user",
699
+ content: message.content
700
+ };
701
+ break;
702
+ case "ai":
703
+ messageDict = {
704
+ role: "assistant",
705
+ content: message.content
706
+ };
707
+ if (message.tool_calls) messageDict.tool_calls = this._convertLcToolCallsToOai(message.tool_calls);
708
+ break;
709
+ case "system":
710
+ messageDict = {
711
+ role: "system",
712
+ content: message.content
713
+ };
714
+ break;
715
+ case "tool":
716
+ messageDict = {
717
+ role: "tool",
718
+ content: message.content
719
+ };
720
+ break;
721
+ case "function":
722
+ messageDict = {
723
+ role: "function",
724
+ content: message.content
725
+ };
726
+ break;
727
+ default: messageDict = {
728
+ role: messageType,
729
+ content: toContentString(message.content)
730
+ };
731
+ }
732
+ if (message.additional_kwargs) messageDict = {
733
+ ...messageDict,
734
+ ...message.additional_kwargs
735
+ };
736
+ return sanitizeLangChain(messageDict, this.client);
737
+ }
738
+ _extractStopReason(output) {
739
+ if (!output.generations || !Array.isArray(output.generations)) return;
740
+ const lastGeneration = output.generations[output.generations.length - 1];
741
+ if (!Array.isArray(lastGeneration) || lastGeneration.length === 0) return;
742
+ const gen = lastGeneration[0];
743
+ const messageResponseMetadata = gen.message?.response_metadata;
744
+ const generationResponseMetadata = gen.generationInfo?.response_metadata;
745
+ const stopReason = messageResponseMetadata?.finish_reason || messageResponseMetadata?.stop_reason || gen.generationInfo?.finish_reason || generationResponseMetadata?.stop_reason || generationResponseMetadata?.finish_reason || gen.generationInfo?.stop_reason || responsesStopReason(messageResponseMetadata) || responsesStopReason(generationResponseMetadata);
746
+ return stopReason != null ? String(stopReason) : void 0;
747
+ }
748
+ _extractCacheCreationTtlBreakdown(cacheCreation, aggregateValues) {
749
+ if (!isObject(cacheCreation)) return;
750
+ const { ephemeral_5m_input_tokens: cache5m, ephemeral_1h_input_tokens: cache1h } = cacheCreation;
751
+ const providedValues = [cache5m, cache1h].filter((value) => value != null);
752
+ if (providedValues.length === 0 || !providedValues.every((value) => typeof value === "number" && Number.isFinite(value) && value >= 0)) return;
753
+ const breakdown = [typeof cache5m === "number" ? cache5m : 0, typeof cache1h === "number" ? cache1h : 0];
754
+ const total = breakdown[0] + breakdown[1];
755
+ const validAggregates = aggregateValues.filter((value) => typeof value === "number" && Number.isFinite(value) && value >= 0);
756
+ return total > 0 && !validAggregates.some((aggregate) => aggregate !== total) ? breakdown : void 0;
757
+ }
758
+ _extractBedrockCacheCreationTtlBreakdown(cacheDetails, aggregateValues) {
759
+ if (!Array.isArray(cacheDetails)) return;
760
+ let cache5m = 0;
761
+ let cache1h = 0;
762
+ for (const detail of cacheDetails) {
763
+ if (!isObject(detail)) continue;
764
+ const ttl = typeof detail.ttl === "string" ? detail.ttl.toLowerCase() : void 0;
765
+ const inputTokens = detail.inputTokens;
766
+ if (ttl !== "5m" && ttl !== "t5m" && ttl !== "1h" && ttl !== "t1h" || typeof inputTokens !== "number" || !Number.isFinite(inputTokens) || inputTokens < 0) continue;
767
+ if (ttl === "5m" || ttl === "t5m") cache5m += inputTokens;
768
+ else cache1h += inputTokens;
769
+ }
770
+ const total = cache5m + cache1h;
771
+ const validAggregates = aggregateValues.filter((value) => typeof value === "number" && Number.isFinite(value) && value >= 0);
772
+ if (total === 0 || validAggregates.some((aggregate) => aggregate !== total)) return;
773
+ return [cache5m, cache1h];
774
+ }
775
+ _parseUsageModel(usage, provider, model, inputIncludesCacheTokens = true, rawUsage) {
776
+ const parsedUsage = [
777
+ ["promptTokens", "input"],
778
+ ["completionTokens", "output"],
779
+ ["input_tokens", "input"],
780
+ ["output_tokens", "output"],
781
+ ["prompt_token_count", "input"],
782
+ ["candidates_token_count", "output"],
783
+ ["inputTokenCount", "input"],
784
+ ["outputTokenCount", "output"],
785
+ ["input_token_count", "input"],
786
+ ["generated_token_count", "output"]
787
+ ].reduce((acc, [modelKey, typeKey]) => {
788
+ const value = usage[modelKey];
789
+ if (value != null) acc[typeKey] = Array.isArray(value) ? value.reduce((sum, tokenCount) => sum + tokenCount, 0) : value;
790
+ return acc;
791
+ }, {
792
+ input: 0,
793
+ output: 0
794
+ });
795
+ const additionalTokenData = {};
796
+ if (usage.prompt_tokens_details?.cached_tokens != null) additionalTokenData.cacheReadInputTokens = usage.prompt_tokens_details.cached_tokens;
797
+ else if (usage.input_token_details?.cache_read != null) additionalTokenData.cacheReadInputTokens = usage.input_token_details.cache_read;
798
+ else if (usage.cachedPromptTokens != null) additionalTokenData.cacheReadInputTokens = usage.cachedPromptTokens;
799
+ else if (usage.cache_read_input_tokens != null) additionalTokenData.cacheReadInputTokens = usage.cache_read_input_tokens;
800
+ if (usage.cache_creation_input_tokens != null) additionalTokenData.cacheWriteInputTokens = usage.cache_creation_input_tokens;
801
+ else if (usage.input_token_details?.cache_creation != null) additionalTokenData.cacheWriteInputTokens = usage.input_token_details.cache_creation;
802
+ const directCacheCreationAggregates = [
803
+ usage.cache_creation_input_tokens,
804
+ usage.input_token_details?.cache_creation,
805
+ usage.cacheWriteInputTokens,
806
+ rawUsage?.cache_creation_input_tokens,
807
+ rawUsage?.input_token_details?.cache_creation,
808
+ rawUsage?.cacheWriteInputTokens,
809
+ additionalTokenData.cacheWriteInputTokens
810
+ ];
811
+ const cacheCreationTtl = this._extractCacheCreationTtlBreakdown(usage.cache_creation, directCacheCreationAggregates) ?? this._extractCacheCreationTtlBreakdown(rawUsage?.cache_creation, directCacheCreationAggregates) ?? this._extractBedrockCacheCreationTtlBreakdown(usage.cacheDetails, [usage.cacheWriteInputTokens, additionalTokenData.cacheWriteInputTokens]) ?? this._extractBedrockCacheCreationTtlBreakdown(rawUsage?.cacheDetails, [rawUsage?.cacheWriteInputTokens, additionalTokenData.cacheWriteInputTokens]);
812
+ if (cacheCreationTtl) {
813
+ const [cacheWrite5mInputTokens, cacheWrite1hInputTokens] = cacheCreationTtl;
814
+ additionalTokenData.cacheWrite5mInputTokens = cacheWrite5mInputTokens;
815
+ additionalTokenData.cacheWrite1hInputTokens = cacheWrite1hInputTokens;
816
+ additionalTokenData.cacheWriteInputTokens = cacheWrite5mInputTokens + cacheWrite1hInputTokens;
817
+ }
818
+ if (usage.completion_tokens_details?.reasoning_tokens != null) additionalTokenData.reasoningTokens = usage.completion_tokens_details.reasoning_tokens;
819
+ else if (usage.output_token_details?.reasoning != null) additionalTokenData.reasoningTokens = usage.output_token_details.reasoning;
820
+ else if (usage.reasoningTokens != null) additionalTokenData.reasoningTokens = usage.reasoningTokens;
821
+ let webSearchCount;
822
+ if (usage.server_tool_use?.web_search_requests !== void 0) webSearchCount = usage.server_tool_use.web_search_requests;
823
+ else if (usage.citations && Array.isArray(usage.citations) && usage.citations.length > 0) webSearchCount = 1;
824
+ else if (usage.search_results && Array.isArray(usage.search_results) && usage.search_results.length > 0) webSearchCount = 1;
825
+ else if (usage.search_context_size) webSearchCount = 1;
826
+ else if (usage.annotations && Array.isArray(usage.annotations)) {
827
+ if (usage.annotations.some((ann) => {
828
+ return ann && typeof ann === "object" && "type" in ann && ann.type === "url_citation";
829
+ })) webSearchCount = 1;
830
+ } else if (usage.grounding_metadata?.grounding_support !== void 0 || usage.grounding_metadata?.web_search_queries !== void 0) webSearchCount = 1;
831
+ if (webSearchCount !== void 0) additionalTokenData.webSearchCount = webSearchCount;
832
+ let isAnthropic = false;
833
+ if (provider && provider.toLowerCase() === "anthropic") isAnthropic = true;
834
+ else if (model && model.toLowerCase().includes("anthropic")) isAnthropic = true;
835
+ if (isAnthropic && inputIncludesCacheTokens && parsedUsage.input) {
836
+ const cacheTokens = (additionalTokenData.cacheReadInputTokens || 0) + (additionalTokenData.cacheWriteInputTokens || 0);
837
+ if (cacheTokens > 0) parsedUsage.input = Math.max(parsedUsage.input - cacheTokens, 0);
838
+ }
839
+ return [
840
+ parsedUsage.input,
841
+ parsedUsage.output,
842
+ additionalTokenData
843
+ ];
844
+ }
845
+ parseUsage(response, provider, model) {
846
+ const isNonEmptyUsage = (usage) => isObject(usage) && Object.keys(usage).length > 0;
847
+ const firstNonEmptyUsage = (...candidates) => candidates.find(isNonEmptyUsage);
848
+ let normalizedGenerationUsage;
849
+ let rawGenerationUsage;
850
+ let fallbackGenerationUsage;
851
+ for (const generation of response.generations ?? []) for (const genChunk of generation) {
852
+ const generationInfo = genChunk.generationInfo ?? {};
853
+ const message = "message" in genChunk ? genChunk.message : void 0;
854
+ const messageUsage = message && typeof message === "object" && "usage_metadata" in message ? message.usage_metadata : void 0;
855
+ normalizedGenerationUsage = firstNonEmptyUsage(normalizedGenerationUsage, messageUsage, generationInfo.usage_metadata);
856
+ const messageResponseMetadata = message && typeof message === "object" && "response_metadata" in message && isObject(message.response_metadata) ? message.response_metadata : void 0;
857
+ const generationResponseMetadata = isObject(generationInfo.response_metadata) ? generationInfo.response_metadata : void 0;
858
+ const messageStreamMetadata = isObject(messageResponseMetadata?.metadata) ? messageResponseMetadata.metadata : void 0;
859
+ const generationStreamMetadata = isObject(generationResponseMetadata?.metadata) ? generationResponseMetadata.metadata : void 0;
860
+ rawGenerationUsage = firstNonEmptyUsage(rawGenerationUsage, messageResponseMetadata?.usage, messageStreamMetadata?.usage, generationResponseMetadata?.usage, generationStreamMetadata?.usage);
861
+ fallbackGenerationUsage = firstNonEmptyUsage(fallbackGenerationUsage, messageResponseMetadata?.["amazon-bedrock-invocationMetrics"], generationResponseMetadata?.["amazon-bedrock-invocationMetrics"], generationInfo.usage_metadata);
862
+ }
863
+ if ((provider?.toLowerCase() === "anthropic" || model?.toLowerCase().includes("anthropic") === true) && isNonEmptyUsage(normalizedGenerationUsage)) return this._parseUsageModel(normalizedGenerationUsage, provider, model, true, rawGenerationUsage);
864
+ const llmUsageKeys = [
865
+ "token_usage",
866
+ "usage",
867
+ "tokenUsage"
868
+ ];
869
+ if (response.llmOutput != null) for (const key of llmUsageKeys) {
870
+ const llmUsage = response.llmOutput[key];
871
+ if (!isNonEmptyUsage(llmUsage)) continue;
872
+ return this._parseUsageModel(llmUsage, provider, model, key !== "usage", llmUsage);
873
+ }
874
+ if (isNonEmptyUsage(normalizedGenerationUsage)) return this._parseUsageModel(normalizedGenerationUsage, provider, model, true, rawGenerationUsage);
875
+ if (isNonEmptyUsage(rawGenerationUsage)) return this._parseUsageModel(rawGenerationUsage, provider, model, false, rawGenerationUsage);
876
+ if (isNonEmptyUsage(fallbackGenerationUsage)) return this._parseUsageModel(fallbackGenerationUsage, provider, model);
877
+ return [
878
+ 0,
879
+ 0,
880
+ {}
881
+ ];
882
+ }
883
+ };
884
+ //#endregion
1063
885
  export { LangChainCallbackHandler };
1064
- //# sourceMappingURL=index.mjs.map
886
+
887
+ //# sourceMappingURL=index.mjs.map