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