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