@posthog/ai 3.3.1 → 4.0.0

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 (39) hide show
  1. package/CHANGELOG.md +8 -0
  2. package/lib/anthropic/index.cjs.js +293 -0
  3. package/lib/anthropic/index.cjs.js.map +1 -0
  4. package/lib/anthropic/index.d.ts +45 -0
  5. package/lib/anthropic/index.esm.js +282 -0
  6. package/lib/anthropic/index.esm.js.map +1 -0
  7. package/lib/index.cjs.js +36 -8
  8. package/lib/index.cjs.js.map +1 -1
  9. package/lib/index.d.ts +2 -2
  10. package/lib/index.esm.js +36 -8
  11. package/lib/index.esm.js.map +1 -1
  12. package/lib/langchain/index.cjs.js +1003 -0
  13. package/lib/langchain/index.cjs.js.map +1 -0
  14. package/lib/langchain/index.d.ts +68 -0
  15. package/lib/langchain/index.esm.js +979 -0
  16. package/lib/langchain/index.esm.js.map +1 -0
  17. package/lib/openai/index.cjs.js +286 -0
  18. package/lib/openai/index.cjs.js.map +1 -0
  19. package/lib/openai/index.d.ts +49 -0
  20. package/lib/openai/index.esm.js +274 -0
  21. package/lib/openai/index.esm.js.map +1 -0
  22. package/lib/posthog-ai/src/anthropic/index.d.ts +1 -0
  23. package/lib/posthog-ai/src/langchain/index.d.ts +1 -0
  24. package/lib/posthog-ai/src/openai/index.d.ts +3 -2
  25. package/lib/posthog-ai/src/vercel/index.d.ts +1 -0
  26. package/lib/vercel/index.cjs.js +408 -0
  27. package/lib/vercel/index.cjs.js.map +1 -0
  28. package/lib/vercel/index.d.ts +21 -0
  29. package/lib/vercel/index.esm.js +404 -0
  30. package/lib/vercel/index.esm.js.map +1 -0
  31. package/package.json +28 -1
  32. package/src/anthropic/index.ts +2 -0
  33. package/src/langchain/callbacks.ts +39 -7
  34. package/src/langchain/index.ts +1 -0
  35. package/src/openai/index.ts +4 -2
  36. package/src/utils.ts +1 -1
  37. package/src/vercel/index.ts +1 -0
  38. package/src/vercel/middleware.ts +4 -4
  39. package/tsconfig.json +1 -0
@@ -0,0 +1,979 @@
1
+ import * as uuid from 'uuid';
2
+
3
+ const getModelParams = params => {
4
+ if (!params) {
5
+ return {};
6
+ }
7
+ const modelParams = {};
8
+ const paramKeys = ['temperature', 'max_tokens', 'max_completion_tokens', 'top_p', 'frequency_penalty', 'presence_penalty', 'n', 'stop', 'stream', 'streaming'];
9
+ for (const key of paramKeys) {
10
+ if (key in params && params[key] !== undefined) {
11
+ modelParams[key] = params[key];
12
+ }
13
+ }
14
+ return modelParams;
15
+ };
16
+ const withPrivacyMode = (client, privacyMode, input) => {
17
+ return client.privacy_mode || privacyMode ? null : input;
18
+ };
19
+
20
+ var decamelize = function (str, sep) {
21
+ if (typeof str !== 'string') {
22
+ throw new TypeError('Expected a string');
23
+ }
24
+
25
+ sep = typeof sep === 'undefined' ? '_' : sep;
26
+
27
+ return str
28
+ .replace(/([a-z\d])([A-Z])/g, '$1' + sep + '$2')
29
+ .replace(/([A-Z]+)([A-Z][a-z\d]+)/g, '$1' + sep + '$2')
30
+ .toLowerCase();
31
+ };
32
+
33
+ var camelcase = {exports: {}};
34
+
35
+ const UPPERCASE = /[\p{Lu}]/u;
36
+ const LOWERCASE = /[\p{Ll}]/u;
37
+ const LEADING_CAPITAL = /^[\p{Lu}](?![\p{Lu}])/gu;
38
+ const IDENTIFIER = /([\p{Alpha}\p{N}_]|$)/u;
39
+ const SEPARATORS = /[_.\- ]+/;
40
+
41
+ const LEADING_SEPARATORS = new RegExp('^' + SEPARATORS.source);
42
+ const SEPARATORS_AND_IDENTIFIER = new RegExp(SEPARATORS.source + IDENTIFIER.source, 'gu');
43
+ const NUMBERS_AND_IDENTIFIER = new RegExp('\\d+' + IDENTIFIER.source, 'gu');
44
+
45
+ const preserveCamelCase = (string, toLowerCase, toUpperCase) => {
46
+ let isLastCharLower = false;
47
+ let isLastCharUpper = false;
48
+ let isLastLastCharUpper = false;
49
+
50
+ for (let i = 0; i < string.length; i++) {
51
+ const character = string[i];
52
+
53
+ if (isLastCharLower && UPPERCASE.test(character)) {
54
+ string = string.slice(0, i) + '-' + string.slice(i);
55
+ isLastCharLower = false;
56
+ isLastLastCharUpper = isLastCharUpper;
57
+ isLastCharUpper = true;
58
+ i++;
59
+ } else if (isLastCharUpper && isLastLastCharUpper && LOWERCASE.test(character)) {
60
+ string = string.slice(0, i - 1) + '-' + string.slice(i - 1);
61
+ isLastLastCharUpper = isLastCharUpper;
62
+ isLastCharUpper = false;
63
+ isLastCharLower = true;
64
+ } else {
65
+ isLastCharLower = toLowerCase(character) === character && toUpperCase(character) !== character;
66
+ isLastLastCharUpper = isLastCharUpper;
67
+ isLastCharUpper = toUpperCase(character) === character && toLowerCase(character) !== character;
68
+ }
69
+ }
70
+
71
+ return string;
72
+ };
73
+
74
+ const preserveConsecutiveUppercase = (input, toLowerCase) => {
75
+ LEADING_CAPITAL.lastIndex = 0;
76
+
77
+ return input.replace(LEADING_CAPITAL, m1 => toLowerCase(m1));
78
+ };
79
+
80
+ const postProcess = (input, toUpperCase) => {
81
+ SEPARATORS_AND_IDENTIFIER.lastIndex = 0;
82
+ NUMBERS_AND_IDENTIFIER.lastIndex = 0;
83
+
84
+ return input.replace(SEPARATORS_AND_IDENTIFIER, (_, identifier) => toUpperCase(identifier))
85
+ .replace(NUMBERS_AND_IDENTIFIER, m => toUpperCase(m));
86
+ };
87
+
88
+ const camelCase = (input, options) => {
89
+ if (!(typeof input === 'string' || Array.isArray(input))) {
90
+ throw new TypeError('Expected the input to be `string | string[]`');
91
+ }
92
+
93
+ options = {
94
+ pascalCase: false,
95
+ preserveConsecutiveUppercase: false,
96
+ ...options
97
+ };
98
+
99
+ if (Array.isArray(input)) {
100
+ input = input.map(x => x.trim())
101
+ .filter(x => x.length)
102
+ .join('-');
103
+ } else {
104
+ input = input.trim();
105
+ }
106
+
107
+ if (input.length === 0) {
108
+ return '';
109
+ }
110
+
111
+ const toLowerCase = options.locale === false ?
112
+ string => string.toLowerCase() :
113
+ string => string.toLocaleLowerCase(options.locale);
114
+ const toUpperCase = options.locale === false ?
115
+ string => string.toUpperCase() :
116
+ string => string.toLocaleUpperCase(options.locale);
117
+
118
+ if (input.length === 1) {
119
+ return options.pascalCase ? toUpperCase(input) : toLowerCase(input);
120
+ }
121
+
122
+ const hasUpperCase = input !== toLowerCase(input);
123
+
124
+ if (hasUpperCase) {
125
+ input = preserveCamelCase(input, toLowerCase, toUpperCase);
126
+ }
127
+
128
+ input = input.replace(LEADING_SEPARATORS, '');
129
+
130
+ if (options.preserveConsecutiveUppercase) {
131
+ input = preserveConsecutiveUppercase(input, toLowerCase);
132
+ } else {
133
+ input = toLowerCase(input);
134
+ }
135
+
136
+ if (options.pascalCase) {
137
+ input = toUpperCase(input.charAt(0)) + input.slice(1);
138
+ }
139
+
140
+ return postProcess(input, toUpperCase);
141
+ };
142
+
143
+ camelcase.exports = camelCase;
144
+ // TODO: Remove this for the next major release
145
+ camelcase.exports.default = camelCase;
146
+
147
+ function keyToJson(key, map) {
148
+ return map?.[key] || decamelize(key);
149
+ }
150
+ function mapKeys(fields, mapper, map) {
151
+ const mapped = {};
152
+ for (const key in fields) {
153
+ if (Object.hasOwn(fields, key)) {
154
+ mapped[mapper(key, map)] = fields[key];
155
+ }
156
+ }
157
+ return mapped;
158
+ }
159
+
160
+ function shallowCopy(obj) {
161
+ return Array.isArray(obj) ? [...obj] : { ...obj };
162
+ }
163
+ function replaceSecrets(root, secretsMap) {
164
+ const result = shallowCopy(root);
165
+ for (const [path, secretId] of Object.entries(secretsMap)) {
166
+ const [last, ...partsReverse] = path.split(".").reverse();
167
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
168
+ let current = result;
169
+ for (const part of partsReverse.reverse()) {
170
+ if (current[part] === undefined) {
171
+ break;
172
+ }
173
+ current[part] = shallowCopy(current[part]);
174
+ current = current[part];
175
+ }
176
+ if (current[last] !== undefined) {
177
+ current[last] = {
178
+ lc: 1,
179
+ type: "secret",
180
+ id: [secretId],
181
+ };
182
+ }
183
+ }
184
+ return result;
185
+ }
186
+ /**
187
+ * Get a unique name for the module, rather than parent class implementations.
188
+ * Should not be subclassed, subclass lc_name above instead.
189
+ */
190
+ function get_lc_unique_name(
191
+ // eslint-disable-next-line @typescript-eslint/no-use-before-define
192
+ serializableClass) {
193
+ // "super" here would refer to the parent class of Serializable,
194
+ // when we want the parent class of the module actually calling this method.
195
+ const parentClass = Object.getPrototypeOf(serializableClass);
196
+ const lcNameIsSubclassed = typeof serializableClass.lc_name === "function" &&
197
+ (typeof parentClass.lc_name !== "function" ||
198
+ serializableClass.lc_name() !== parentClass.lc_name());
199
+ if (lcNameIsSubclassed) {
200
+ return serializableClass.lc_name();
201
+ }
202
+ else {
203
+ return serializableClass.name;
204
+ }
205
+ }
206
+ class Serializable {
207
+ /**
208
+ * The name of the serializable. Override to provide an alias or
209
+ * to preserve the serialized module name in minified environments.
210
+ *
211
+ * Implemented as a static method to support loading logic.
212
+ */
213
+ static lc_name() {
214
+ return this.name;
215
+ }
216
+ /**
217
+ * The final serialized identifier for the module.
218
+ */
219
+ get lc_id() {
220
+ return [
221
+ ...this.lc_namespace,
222
+ get_lc_unique_name(this.constructor),
223
+ ];
224
+ }
225
+ /**
226
+ * A map of secrets, which will be omitted from serialization.
227
+ * Keys are paths to the secret in constructor args, e.g. "foo.bar.baz".
228
+ * Values are the secret ids, which will be used when deserializing.
229
+ */
230
+ get lc_secrets() {
231
+ return undefined;
232
+ }
233
+ /**
234
+ * A map of additional attributes to merge with constructor args.
235
+ * Keys are the attribute names, e.g. "foo".
236
+ * Values are the attribute values, which will be serialized.
237
+ * These attributes need to be accepted by the constructor as arguments.
238
+ */
239
+ get lc_attributes() {
240
+ return undefined;
241
+ }
242
+ /**
243
+ * A map of aliases for constructor args.
244
+ * Keys are the attribute names, e.g. "foo".
245
+ * Values are the alias that will replace the key in serialization.
246
+ * This is used to eg. make argument names match Python.
247
+ */
248
+ get lc_aliases() {
249
+ return undefined;
250
+ }
251
+ constructor(kwargs, ..._args) {
252
+ Object.defineProperty(this, "lc_serializable", {
253
+ enumerable: true,
254
+ configurable: true,
255
+ writable: true,
256
+ value: false
257
+ });
258
+ Object.defineProperty(this, "lc_kwargs", {
259
+ enumerable: true,
260
+ configurable: true,
261
+ writable: true,
262
+ value: void 0
263
+ });
264
+ this.lc_kwargs = kwargs || {};
265
+ }
266
+ toJSON() {
267
+ if (!this.lc_serializable) {
268
+ return this.toJSONNotImplemented();
269
+ }
270
+ if (
271
+ // eslint-disable-next-line no-instanceof/no-instanceof
272
+ this.lc_kwargs instanceof Serializable ||
273
+ typeof this.lc_kwargs !== "object" ||
274
+ Array.isArray(this.lc_kwargs)) {
275
+ // We do not support serialization of classes with arg not a POJO
276
+ // I'm aware the check above isn't as strict as it could be
277
+ return this.toJSONNotImplemented();
278
+ }
279
+ const aliases = {};
280
+ const secrets = {};
281
+ const kwargs = Object.keys(this.lc_kwargs).reduce((acc, key) => {
282
+ acc[key] = key in this ? this[key] : this.lc_kwargs[key];
283
+ return acc;
284
+ }, {});
285
+ // get secrets, attributes and aliases from all superclasses
286
+ for (
287
+ // eslint-disable-next-line @typescript-eslint/no-this-alias
288
+ let current = Object.getPrototypeOf(this); current; current = Object.getPrototypeOf(current)) {
289
+ Object.assign(aliases, Reflect.get(current, "lc_aliases", this));
290
+ Object.assign(secrets, Reflect.get(current, "lc_secrets", this));
291
+ Object.assign(kwargs, Reflect.get(current, "lc_attributes", this));
292
+ }
293
+ // include all secrets used, even if not in kwargs,
294
+ // will be replaced with sentinel value in replaceSecrets
295
+ Object.keys(secrets).forEach((keyPath) => {
296
+ // eslint-disable-next-line @typescript-eslint/no-this-alias, @typescript-eslint/no-explicit-any
297
+ let read = this;
298
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
299
+ let write = kwargs;
300
+ const [last, ...partsReverse] = keyPath.split(".").reverse();
301
+ for (const key of partsReverse.reverse()) {
302
+ if (!(key in read) || read[key] === undefined)
303
+ return;
304
+ if (!(key in write) || write[key] === undefined) {
305
+ if (typeof read[key] === "object" && read[key] != null) {
306
+ write[key] = {};
307
+ }
308
+ else if (Array.isArray(read[key])) {
309
+ write[key] = [];
310
+ }
311
+ }
312
+ read = read[key];
313
+ write = write[key];
314
+ }
315
+ if (last in read && read[last] !== undefined) {
316
+ write[last] = write[last] || read[last];
317
+ }
318
+ });
319
+ return {
320
+ lc: 1,
321
+ type: "constructor",
322
+ id: this.lc_id,
323
+ kwargs: mapKeys(Object.keys(secrets).length ? replaceSecrets(kwargs, secrets) : kwargs, keyToJson, aliases),
324
+ };
325
+ }
326
+ toJSONNotImplemented() {
327
+ return {
328
+ lc: 1,
329
+ type: "not_implemented",
330
+ id: this.lc_id,
331
+ };
332
+ }
333
+ }
334
+
335
+ // Supabase Edge Function provides a `Deno` global object
336
+ // without `version` property
337
+ const isDeno = () => typeof Deno !== "undefined";
338
+ function getEnvironmentVariable(name) {
339
+ // Certain Deno setups will throw an error if you try to access environment variables
340
+ // https://github.com/langchain-ai/langchainjs/issues/1412
341
+ try {
342
+ if (typeof process !== "undefined") {
343
+ // eslint-disable-next-line no-process-env
344
+ return process.env?.[name];
345
+ }
346
+ else if (isDeno()) {
347
+ return Deno?.env.get(name);
348
+ }
349
+ else {
350
+ return undefined;
351
+ }
352
+ }
353
+ catch (e) {
354
+ return undefined;
355
+ }
356
+ }
357
+
358
+ /**
359
+ * Abstract class that provides a set of optional methods that can be
360
+ * overridden in derived classes to handle various events during the
361
+ * execution of a LangChain application.
362
+ */
363
+ class BaseCallbackHandlerMethodsClass {
364
+ }
365
+ /**
366
+ * Abstract base class for creating callback handlers in the LangChain
367
+ * framework. It provides a set of optional methods that can be overridden
368
+ * in derived classes to handle various events during the execution of a
369
+ * LangChain application.
370
+ */
371
+ class BaseCallbackHandler extends BaseCallbackHandlerMethodsClass {
372
+ get lc_namespace() {
373
+ return ["langchain_core", "callbacks", this.name];
374
+ }
375
+ get lc_secrets() {
376
+ return undefined;
377
+ }
378
+ get lc_attributes() {
379
+ return undefined;
380
+ }
381
+ get lc_aliases() {
382
+ return undefined;
383
+ }
384
+ /**
385
+ * The name of the serializable. Override to provide an alias or
386
+ * to preserve the serialized module name in minified environments.
387
+ *
388
+ * Implemented as a static method to support loading logic.
389
+ */
390
+ static lc_name() {
391
+ return this.name;
392
+ }
393
+ /**
394
+ * The final serialized identifier for the module.
395
+ */
396
+ get lc_id() {
397
+ return [
398
+ ...this.lc_namespace,
399
+ get_lc_unique_name(this.constructor),
400
+ ];
401
+ }
402
+ constructor(input) {
403
+ super();
404
+ Object.defineProperty(this, "lc_serializable", {
405
+ enumerable: true,
406
+ configurable: true,
407
+ writable: true,
408
+ value: false
409
+ });
410
+ Object.defineProperty(this, "lc_kwargs", {
411
+ enumerable: true,
412
+ configurable: true,
413
+ writable: true,
414
+ value: void 0
415
+ });
416
+ Object.defineProperty(this, "ignoreLLM", {
417
+ enumerable: true,
418
+ configurable: true,
419
+ writable: true,
420
+ value: false
421
+ });
422
+ Object.defineProperty(this, "ignoreChain", {
423
+ enumerable: true,
424
+ configurable: true,
425
+ writable: true,
426
+ value: false
427
+ });
428
+ Object.defineProperty(this, "ignoreAgent", {
429
+ enumerable: true,
430
+ configurable: true,
431
+ writable: true,
432
+ value: false
433
+ });
434
+ Object.defineProperty(this, "ignoreRetriever", {
435
+ enumerable: true,
436
+ configurable: true,
437
+ writable: true,
438
+ value: false
439
+ });
440
+ Object.defineProperty(this, "ignoreCustomEvent", {
441
+ enumerable: true,
442
+ configurable: true,
443
+ writable: true,
444
+ value: false
445
+ });
446
+ Object.defineProperty(this, "raiseError", {
447
+ enumerable: true,
448
+ configurable: true,
449
+ writable: true,
450
+ value: false
451
+ });
452
+ Object.defineProperty(this, "awaitHandlers", {
453
+ enumerable: true,
454
+ configurable: true,
455
+ writable: true,
456
+ value: getEnvironmentVariable("LANGCHAIN_CALLBACKS_BACKGROUND") === "false"
457
+ });
458
+ this.lc_kwargs = input || {};
459
+ if (input) {
460
+ this.ignoreLLM = input.ignoreLLM ?? this.ignoreLLM;
461
+ this.ignoreChain = input.ignoreChain ?? this.ignoreChain;
462
+ this.ignoreAgent = input.ignoreAgent ?? this.ignoreAgent;
463
+ this.ignoreRetriever = input.ignoreRetriever ?? this.ignoreRetriever;
464
+ this.ignoreCustomEvent =
465
+ input.ignoreCustomEvent ?? this.ignoreCustomEvent;
466
+ this.raiseError = input.raiseError ?? this.raiseError;
467
+ this.awaitHandlers =
468
+ this.raiseError || (input._awaitHandler ?? this.awaitHandlers);
469
+ }
470
+ }
471
+ copy() {
472
+ return new this.constructor(this);
473
+ }
474
+ toJSON() {
475
+ return Serializable.prototype.toJSON.call(this);
476
+ }
477
+ toJSONNotImplemented() {
478
+ return Serializable.prototype.toJSONNotImplemented.call(this);
479
+ }
480
+ static fromMethods(methods) {
481
+ class Handler extends BaseCallbackHandler {
482
+ constructor() {
483
+ super();
484
+ Object.defineProperty(this, "name", {
485
+ enumerable: true,
486
+ configurable: true,
487
+ writable: true,
488
+ value: uuid.v4()
489
+ });
490
+ Object.assign(this, methods);
491
+ }
492
+ }
493
+ return new Handler();
494
+ }
495
+ }
496
+
497
+ /** A run may either be a Span or a Generation */
498
+
499
+ /** Storage for run metadata */
500
+
501
+ class LangChainCallbackHandler extends BaseCallbackHandler {
502
+ name = 'PosthogCallbackHandler';
503
+ runs = {};
504
+ parentTree = {};
505
+ constructor(options) {
506
+ if (!options.client) {
507
+ throw new Error('PostHog client is required');
508
+ }
509
+ super();
510
+ this.client = options.client;
511
+ this.distinctId = options.distinctId;
512
+ this.traceId = options.traceId;
513
+ this.properties = options.properties || {};
514
+ this.privacyMode = options.privacyMode || false;
515
+ this.groups = options.groups || {};
516
+ this.debug = options.debug || false;
517
+ }
518
+
519
+ // ===== CALLBACK METHODS =====
520
+
521
+ handleChainStart(chain, inputs, runId, parentRunId, tags, metadata, runType, runName) {
522
+ this._logDebugEvent('on_chain_start', runId, parentRunId, {
523
+ inputs,
524
+ tags
525
+ });
526
+ this._setParentOfRun(runId, parentRunId);
527
+ this._setTraceOrSpanMetadata(chain, inputs, runId, parentRunId, metadata, tags, runName);
528
+ }
529
+ handleChainEnd(outputs, runId, parentRunId, tags,
530
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
531
+ kwargs) {
532
+ this._logDebugEvent('on_chain_end', runId, parentRunId, {
533
+ outputs,
534
+ tags
535
+ });
536
+ this._popRunAndCaptureTraceOrSpan(runId, parentRunId, outputs);
537
+ }
538
+ handleChainError(error, runId, parentRunId, tags,
539
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
540
+ kwargs) {
541
+ this._logDebugEvent('on_chain_error', runId, parentRunId, {
542
+ error,
543
+ tags
544
+ });
545
+ this._popRunAndCaptureTraceOrSpan(runId, parentRunId, error);
546
+ }
547
+ handleChatModelStart(serialized, messages, runId, parentRunId, extraParams, tags, metadata, runName) {
548
+ this._logDebugEvent('on_chat_model_start', runId, parentRunId, {
549
+ messages,
550
+ tags
551
+ });
552
+ this._setParentOfRun(runId, parentRunId);
553
+ // Flatten the two-dimensional messages and convert each message to a plain object
554
+ const input = messages.flat().map(m => this._convertMessageToDict(m));
555
+ this._setLLMMetadata(serialized, runId, input, metadata, extraParams, runName);
556
+ }
557
+ handleLLMStart(serialized, prompts, runId, parentRunId, extraParams, tags, metadata, runName) {
558
+ this._logDebugEvent('on_llm_start', runId, parentRunId, {
559
+ prompts,
560
+ tags
561
+ });
562
+ this._setParentOfRun(runId, parentRunId);
563
+ this._setLLMMetadata(serialized, runId, prompts, metadata, extraParams, runName);
564
+ }
565
+ handleLLMEnd(output, runId, parentRunId, tags,
566
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
567
+ extraParams) {
568
+ this._logDebugEvent('on_llm_end', runId, parentRunId, {
569
+ output,
570
+ tags
571
+ });
572
+ this._popRunAndCaptureGeneration(runId, parentRunId, output);
573
+ }
574
+ handleLLMError(err, runId, parentRunId, tags,
575
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
576
+ extraParams) {
577
+ this._logDebugEvent('on_llm_error', runId, parentRunId, {
578
+ err,
579
+ tags
580
+ });
581
+ this._popRunAndCaptureGeneration(runId, parentRunId, err);
582
+ }
583
+ handleToolStart(tool, input, runId, parentRunId, tags, metadata, runName) {
584
+ this._logDebugEvent('on_tool_start', runId, parentRunId, {
585
+ input,
586
+ tags
587
+ });
588
+ this._setParentOfRun(runId, parentRunId);
589
+ this._setTraceOrSpanMetadata(tool, input, runId, parentRunId, metadata, tags, runName);
590
+ }
591
+ handleToolEnd(output, runId, parentRunId, tags) {
592
+ this._logDebugEvent('on_tool_end', runId, parentRunId, {
593
+ output,
594
+ tags
595
+ });
596
+ this._popRunAndCaptureTraceOrSpan(runId, parentRunId, output);
597
+ }
598
+ handleToolError(err, runId, parentRunId, tags) {
599
+ this._logDebugEvent('on_tool_error', runId, parentRunId, {
600
+ err,
601
+ tags
602
+ });
603
+ this._popRunAndCaptureTraceOrSpan(runId, parentRunId, err);
604
+ }
605
+ handleRetrieverStart(retriever, query, runId, parentRunId, tags, metadata, name) {
606
+ this._logDebugEvent('on_retriever_start', runId, parentRunId, {
607
+ query,
608
+ tags
609
+ });
610
+ this._setParentOfRun(runId, parentRunId);
611
+ this._setTraceOrSpanMetadata(retriever, query, runId, parentRunId, metadata, tags, name);
612
+ }
613
+ handleRetrieverEnd(documents, runId, parentRunId, tags) {
614
+ this._logDebugEvent('on_retriever_end', runId, parentRunId, {
615
+ documents,
616
+ tags
617
+ });
618
+ this._popRunAndCaptureTraceOrSpan(runId, parentRunId, documents);
619
+ }
620
+ handleRetrieverError(err, runId, parentRunId, tags) {
621
+ this._logDebugEvent('on_retriever_error', runId, parentRunId, {
622
+ err,
623
+ tags
624
+ });
625
+ this._popRunAndCaptureTraceOrSpan(runId, parentRunId, err);
626
+ }
627
+ handleAgentAction(action, runId, parentRunId, tags) {
628
+ this._logDebugEvent('on_agent_action', runId, parentRunId, {
629
+ action,
630
+ tags
631
+ });
632
+ this._setParentOfRun(runId, parentRunId);
633
+ this._setTraceOrSpanMetadata(null, action, runId, parentRunId);
634
+ }
635
+ handleAgentEnd(action, runId, parentRunId, tags) {
636
+ this._logDebugEvent('on_agent_finish', runId, parentRunId, {
637
+ action,
638
+ tags
639
+ });
640
+ this._popRunAndCaptureTraceOrSpan(runId, parentRunId, action);
641
+ }
642
+
643
+ // ===== PRIVATE HELPERS =====
644
+
645
+ _setParentOfRun(runId, parentRunId) {
646
+ if (parentRunId) {
647
+ this.parentTree[runId] = parentRunId;
648
+ }
649
+ }
650
+ _popParentOfRun(runId) {
651
+ delete this.parentTree[runId];
652
+ }
653
+ _findRootRun(runId) {
654
+ let id = runId;
655
+ while (this.parentTree[id]) {
656
+ id = this.parentTree[id];
657
+ }
658
+ return id;
659
+ }
660
+ _setTraceOrSpanMetadata(serialized, input, runId, parentRunId, ...args) {
661
+ // Use default names if not provided: if this is a top-level run, we mark it as a trace, otherwise as a span.
662
+ const defaultName = parentRunId ? 'span' : 'trace';
663
+ const runName = this._getLangchainRunName(serialized, ...args) || defaultName;
664
+ this.runs[runId] = {
665
+ name: runName,
666
+ input,
667
+ startTime: Date.now()
668
+ };
669
+ }
670
+ _setLLMMetadata(serialized, runId, messages, metadata, extraParams, runName) {
671
+ const runNameFound = this._getLangchainRunName(serialized, {
672
+ extraParams,
673
+ runName
674
+ }) || 'generation';
675
+ const generation = {
676
+ name: runNameFound,
677
+ input: messages,
678
+ startTime: Date.now()
679
+ };
680
+ if (extraParams) {
681
+ generation.modelParams = getModelParams(extraParams.invocation_params);
682
+ }
683
+ if (metadata) {
684
+ if (metadata.ls_model_name) {
685
+ generation.model = metadata.ls_model_name;
686
+ }
687
+ if (metadata.ls_provider) {
688
+ generation.provider = metadata.ls_provider;
689
+ }
690
+ }
691
+ if (serialized && 'kwargs' in serialized && serialized.kwargs.openai_api_base) {
692
+ generation.baseUrl = serialized.kwargs.openai_api_base;
693
+ }
694
+ this.runs[runId] = generation;
695
+ }
696
+ _popRunMetadata(runId) {
697
+ const endTime = Date.now();
698
+ const run = this.runs[runId];
699
+ if (!run) {
700
+ console.warn(`No run metadata found for run ${runId}`);
701
+ return undefined;
702
+ }
703
+ run.endTime = endTime;
704
+ delete this.runs[runId];
705
+ return run;
706
+ }
707
+ _getTraceId(runId) {
708
+ return this.traceId ? String(this.traceId) : this._findRootRun(runId);
709
+ }
710
+ _getParentRunId(traceId, runId, parentRunId) {
711
+ // Replace the parent-run if not found in our stored parent tree.
712
+ if (parentRunId && !this.parentTree[parentRunId]) {
713
+ return traceId;
714
+ }
715
+ return parentRunId;
716
+ }
717
+ _popRunAndCaptureTraceOrSpan(runId, parentRunId, outputs) {
718
+ const traceId = this._getTraceId(runId);
719
+ this._popParentOfRun(runId);
720
+ const run = this._popRunMetadata(runId);
721
+ if (!run) {
722
+ return;
723
+ }
724
+ if ('modelParams' in run) {
725
+ console.warn(`Run ${runId} is a generation, but attempted to be captured as a trace/span.`);
726
+ return;
727
+ }
728
+ const actualParentRunId = this._getParentRunId(traceId, runId, parentRunId);
729
+ this._captureTraceOrSpan(traceId, runId, run, outputs, actualParentRunId);
730
+ }
731
+ _captureTraceOrSpan(traceId, runId, run, outputs, parentRunId) {
732
+ const eventName = parentRunId ? '$ai_span' : '$ai_trace';
733
+ const latency = run.endTime ? (run.endTime - run.startTime) / 1000 : 0;
734
+ const eventProperties = {
735
+ $ai_trace_id: traceId,
736
+ $ai_input_state: withPrivacyMode(this.client, this.privacyMode, run.input),
737
+ $ai_latency: latency,
738
+ $ai_span_name: run.name,
739
+ $ai_span_id: runId
740
+ };
741
+ if (parentRunId) {
742
+ eventProperties['$ai_parent_id'] = parentRunId;
743
+ }
744
+ Object.assign(eventProperties, this.properties);
745
+ if (!this.distinctId) {
746
+ eventProperties['$process_person_profile'] = false;
747
+ }
748
+ if (outputs instanceof Error) {
749
+ eventProperties['$ai_error'] = outputs.toString();
750
+ eventProperties['$ai_is_error'] = true;
751
+ } else if (outputs !== undefined) {
752
+ eventProperties['$ai_output_state'] = withPrivacyMode(this.client, this.privacyMode, outputs);
753
+ }
754
+ this.client.capture({
755
+ distinctId: this.distinctId ? this.distinctId.toString() : runId,
756
+ event: eventName,
757
+ properties: eventProperties,
758
+ groups: this.groups
759
+ });
760
+ }
761
+ _popRunAndCaptureGeneration(runId, parentRunId, response) {
762
+ const traceId = this._getTraceId(runId);
763
+ this._popParentOfRun(runId);
764
+ const run = this._popRunMetadata(runId);
765
+ if (!run || typeof run !== 'object' || !('modelParams' in run)) {
766
+ console.warn(`Run ${runId} is not a generation, but attempted to be captured as such.`);
767
+ return;
768
+ }
769
+ const actualParentRunId = this._getParentRunId(traceId, runId, parentRunId);
770
+ this._captureGeneration(traceId, runId, run, response, actualParentRunId);
771
+ }
772
+ _captureGeneration(traceId, runId, run, output, parentRunId) {
773
+ const latency = run.endTime ? (run.endTime - run.startTime) / 1000 : 0;
774
+ const eventProperties = {
775
+ $ai_trace_id: traceId,
776
+ $ai_span_id: runId,
777
+ $ai_span_name: run.name,
778
+ $ai_parent_id: parentRunId,
779
+ $ai_provider: run.provider,
780
+ $ai_model: run.model,
781
+ $ai_model_parameters: run.modelParams,
782
+ $ai_input: withPrivacyMode(this.client, this.privacyMode, run.input),
783
+ $ai_http_status: 200,
784
+ $ai_latency: latency,
785
+ $ai_base_url: run.baseUrl
786
+ };
787
+ if (run.tools) {
788
+ eventProperties['$ai_tools'] = withPrivacyMode(this.client, this.privacyMode, run.tools);
789
+ }
790
+ if (output instanceof Error) {
791
+ eventProperties['$ai_http_status'] = output.status || 500;
792
+ eventProperties['$ai_error'] = output.toString();
793
+ eventProperties['$ai_is_error'] = true;
794
+ } else {
795
+ // Handle token usage
796
+ const [inputTokens, outputTokens, additionalTokenData] = this.parseUsage(output);
797
+ eventProperties['$ai_input_tokens'] = inputTokens;
798
+ eventProperties['$ai_output_tokens'] = outputTokens;
799
+
800
+ // Add additional token data to properties
801
+ if (additionalTokenData.cacheReadInputTokens) {
802
+ eventProperties['$ai_cache_read_tokens'] = additionalTokenData.cacheReadInputTokens;
803
+ }
804
+ if (additionalTokenData.reasoningTokens) {
805
+ eventProperties['$ai_reasoning_tokens'] = additionalTokenData.reasoningTokens;
806
+ }
807
+
808
+ // Handle generations/completions
809
+ let completions;
810
+ if (output.generations && Array.isArray(output.generations)) {
811
+ const lastGeneration = output.generations[output.generations.length - 1];
812
+ if (Array.isArray(lastGeneration)) {
813
+ completions = lastGeneration.map(gen => {
814
+ return {
815
+ role: 'assistant',
816
+ content: gen.text
817
+ };
818
+ });
819
+ }
820
+ }
821
+ if (completions) {
822
+ eventProperties['$ai_output_choices'] = withPrivacyMode(this.client, this.privacyMode, completions);
823
+ }
824
+ }
825
+ Object.assign(eventProperties, this.properties);
826
+ if (!this.distinctId) {
827
+ eventProperties['$process_person_profile'] = false;
828
+ }
829
+ this.client.capture({
830
+ distinctId: this.distinctId ? this.distinctId.toString() : traceId,
831
+ event: '$ai_generation',
832
+ properties: eventProperties,
833
+ groups: this.groups
834
+ });
835
+ }
836
+ _logDebugEvent(eventName, runId, parentRunId, extra) {
837
+ if (this.debug) {
838
+ console.log(`Event: ${eventName}, runId: ${runId}, parentRunId: ${parentRunId}, extra:`, extra);
839
+ }
840
+ }
841
+ _getLangchainRunName(serialized, ...args) {
842
+ if (args && args.length > 0) {
843
+ for (const arg of args) {
844
+ if (arg && typeof arg === 'object' && 'name' in arg) {
845
+ return arg.name;
846
+ } else if (arg && typeof arg === 'object' && 'runName' in arg) {
847
+ return arg.runName;
848
+ }
849
+ }
850
+ }
851
+ if (serialized && serialized.name) {
852
+ return serialized.name;
853
+ }
854
+ if (serialized && serialized.id) {
855
+ return Array.isArray(serialized.id) ? serialized.id[serialized.id.length - 1] : serialized.id;
856
+ }
857
+ return undefined;
858
+ }
859
+ _convertMessageToDict(message) {
860
+ let messageDict = {};
861
+
862
+ // Check the _getType() method or type property instead of instanceof
863
+ const messageType = message._getType?.() || message.type;
864
+ switch (messageType) {
865
+ case 'human':
866
+ messageDict = {
867
+ role: 'user',
868
+ content: message.content
869
+ };
870
+ break;
871
+ case 'ai':
872
+ messageDict = {
873
+ role: 'assistant',
874
+ content: message.content
875
+ };
876
+ break;
877
+ case 'system':
878
+ messageDict = {
879
+ role: 'system',
880
+ content: message.content
881
+ };
882
+ break;
883
+ case 'tool':
884
+ messageDict = {
885
+ role: 'tool',
886
+ content: message.content
887
+ };
888
+ break;
889
+ case 'function':
890
+ messageDict = {
891
+ role: 'function',
892
+ content: message.content
893
+ };
894
+ break;
895
+ default:
896
+ messageDict = {
897
+ role: messageType || 'unknown',
898
+ content: String(message.content)
899
+ };
900
+ }
901
+ if (message.additional_kwargs) {
902
+ messageDict = {
903
+ ...messageDict,
904
+ ...message.additional_kwargs
905
+ };
906
+ }
907
+ return messageDict;
908
+ }
909
+ _parseUsageModel(usage) {
910
+ 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']];
911
+ const parsedUsage = conversionList.reduce((acc, [modelKey, typeKey]) => {
912
+ const value = usage[modelKey];
913
+ if (value != null) {
914
+ const finalCount = Array.isArray(value) ? value.reduce((sum, tokenCount) => sum + tokenCount, 0) : value;
915
+ acc[typeKey] = finalCount;
916
+ }
917
+ return acc;
918
+ }, {
919
+ input: 0,
920
+ output: 0
921
+ });
922
+
923
+ // Extract additional token details like cached tokens and reasoning tokens
924
+ const additionalTokenData = {};
925
+
926
+ // Check for cached tokens in various formats
927
+ if (usage.prompt_tokens_details?.cached_tokens != null) {
928
+ additionalTokenData.cacheReadInputTokens = usage.prompt_tokens_details.cached_tokens;
929
+ } else if (usage.input_token_details?.cache_read != null) {
930
+ additionalTokenData.cacheReadInputTokens = usage.input_token_details.cache_read;
931
+ } else if (usage.cachedPromptTokens != null) {
932
+ additionalTokenData.cacheReadInputTokens = usage.cachedPromptTokens;
933
+ }
934
+
935
+ // Check for reasoning tokens in various formats
936
+ if (usage.completion_tokens_details?.reasoning_tokens != null) {
937
+ additionalTokenData.reasoningTokens = usage.completion_tokens_details.reasoning_tokens;
938
+ } else if (usage.output_token_details?.reasoning != null) {
939
+ additionalTokenData.reasoningTokens = usage.output_token_details.reasoning;
940
+ } else if (usage.reasoningTokens != null) {
941
+ additionalTokenData.reasoningTokens = usage.reasoningTokens;
942
+ }
943
+ return [parsedUsage.input, parsedUsage.output, additionalTokenData];
944
+ }
945
+ parseUsage(response) {
946
+ let llmUsage = [0, 0, {}];
947
+ const llmUsageKeys = ['token_usage', 'usage', 'tokenUsage'];
948
+ if (response.llmOutput != null) {
949
+ const key = llmUsageKeys.find(k => response.llmOutput?.[k] != null);
950
+ if (key) {
951
+ llmUsage = this._parseUsageModel(response.llmOutput[key]);
952
+ }
953
+ }
954
+
955
+ // If top-level usage info was not found, try checking the generations.
956
+ if (llmUsage[0] === 0 && llmUsage[1] === 0 && response.generations) {
957
+ for (const generation of response.generations) {
958
+ for (const genChunk of generation) {
959
+ // Check other paths for usage information
960
+ if (genChunk.generationInfo?.usage_metadata) {
961
+ llmUsage = this._parseUsageModel(genChunk.generationInfo.usage_metadata);
962
+ return llmUsage;
963
+ }
964
+ const messageChunk = genChunk.generationInfo ?? {};
965
+ const responseMetadata = messageChunk.response_metadata ?? {};
966
+ const chunkUsage = responseMetadata['usage'] ?? responseMetadata['amazon-bedrock-invocationMetrics'] ?? messageChunk.usage_metadata;
967
+ if (chunkUsage) {
968
+ llmUsage = this._parseUsageModel(chunkUsage);
969
+ return llmUsage;
970
+ }
971
+ }
972
+ }
973
+ }
974
+ return llmUsage;
975
+ }
976
+ }
977
+
978
+ export { LangChainCallbackHandler };
979
+ //# sourceMappingURL=index.esm.js.map