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