@midscene/core 0.9.1 → 0.9.2-beta-20250114083542.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.
@@ -0,0 +1,4086 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
2
+
3
+
4
+ var _chunkG7A32JAGjs = require('./chunk-G7A32JAG.js');
5
+
6
+ // ../../node_modules/.pnpm/retry@0.13.1/node_modules/retry/lib/retry_operation.js
7
+ var require_retry_operation = _chunkG7A32JAGjs.__commonJS.call(void 0, {
8
+ "../../node_modules/.pnpm/retry@0.13.1/node_modules/retry/lib/retry_operation.js"(exports, module) {
9
+ "use strict";
10
+ function RetryOperation(timeouts, options) {
11
+ if (typeof options === "boolean") {
12
+ options = { forever: options };
13
+ }
14
+ this._originalTimeouts = JSON.parse(JSON.stringify(timeouts));
15
+ this._timeouts = timeouts;
16
+ this._options = options || {};
17
+ this._maxRetryTime = options && options.maxRetryTime || Infinity;
18
+ this._fn = null;
19
+ this._errors = [];
20
+ this._attempts = 1;
21
+ this._operationTimeout = null;
22
+ this._operationTimeoutCb = null;
23
+ this._timeout = null;
24
+ this._operationStart = null;
25
+ this._timer = null;
26
+ if (this._options.forever) {
27
+ this._cachedTimeouts = this._timeouts.slice(0);
28
+ }
29
+ }
30
+ module.exports = RetryOperation;
31
+ RetryOperation.prototype.reset = function() {
32
+ this._attempts = 1;
33
+ this._timeouts = this._originalTimeouts.slice(0);
34
+ };
35
+ RetryOperation.prototype.stop = function() {
36
+ if (this._timeout) {
37
+ clearTimeout(this._timeout);
38
+ }
39
+ if (this._timer) {
40
+ clearTimeout(this._timer);
41
+ }
42
+ this._timeouts = [];
43
+ this._cachedTimeouts = null;
44
+ };
45
+ RetryOperation.prototype.retry = function(err) {
46
+ if (this._timeout) {
47
+ clearTimeout(this._timeout);
48
+ }
49
+ if (!err) {
50
+ return false;
51
+ }
52
+ var currentTime = (/* @__PURE__ */ new Date()).getTime();
53
+ if (err && currentTime - this._operationStart >= this._maxRetryTime) {
54
+ this._errors.push(err);
55
+ this._errors.unshift(new Error("RetryOperation timeout occurred"));
56
+ return false;
57
+ }
58
+ this._errors.push(err);
59
+ var timeout = this._timeouts.shift();
60
+ if (timeout === void 0) {
61
+ if (this._cachedTimeouts) {
62
+ this._errors.splice(0, this._errors.length - 1);
63
+ timeout = this._cachedTimeouts.slice(-1);
64
+ } else {
65
+ return false;
66
+ }
67
+ }
68
+ var self = this;
69
+ this._timer = setTimeout(function() {
70
+ self._attempts++;
71
+ if (self._operationTimeoutCb) {
72
+ self._timeout = setTimeout(function() {
73
+ self._operationTimeoutCb(self._attempts);
74
+ }, self._operationTimeout);
75
+ if (self._options.unref) {
76
+ self._timeout.unref();
77
+ }
78
+ }
79
+ self._fn(self._attempts);
80
+ }, timeout);
81
+ if (this._options.unref) {
82
+ this._timer.unref();
83
+ }
84
+ return true;
85
+ };
86
+ RetryOperation.prototype.attempt = function(fn, timeoutOps) {
87
+ this._fn = fn;
88
+ if (timeoutOps) {
89
+ if (timeoutOps.timeout) {
90
+ this._operationTimeout = timeoutOps.timeout;
91
+ }
92
+ if (timeoutOps.cb) {
93
+ this._operationTimeoutCb = timeoutOps.cb;
94
+ }
95
+ }
96
+ var self = this;
97
+ if (this._operationTimeoutCb) {
98
+ this._timeout = setTimeout(function() {
99
+ self._operationTimeoutCb();
100
+ }, self._operationTimeout);
101
+ }
102
+ this._operationStart = (/* @__PURE__ */ new Date()).getTime();
103
+ this._fn(this._attempts);
104
+ };
105
+ RetryOperation.prototype.try = function(fn) {
106
+ console.log("Using RetryOperation.try() is deprecated");
107
+ this.attempt(fn);
108
+ };
109
+ RetryOperation.prototype.start = function(fn) {
110
+ console.log("Using RetryOperation.start() is deprecated");
111
+ this.attempt(fn);
112
+ };
113
+ RetryOperation.prototype.start = RetryOperation.prototype.try;
114
+ RetryOperation.prototype.errors = function() {
115
+ return this._errors;
116
+ };
117
+ RetryOperation.prototype.attempts = function() {
118
+ return this._attempts;
119
+ };
120
+ RetryOperation.prototype.mainError = function() {
121
+ if (this._errors.length === 0) {
122
+ return null;
123
+ }
124
+ var counts = {};
125
+ var mainError = null;
126
+ var mainErrorCount = 0;
127
+ for (var i = 0; i < this._errors.length; i++) {
128
+ var error = this._errors[i];
129
+ var message = error.message;
130
+ var count = (counts[message] || 0) + 1;
131
+ counts[message] = count;
132
+ if (count >= mainErrorCount) {
133
+ mainError = error;
134
+ mainErrorCount = count;
135
+ }
136
+ }
137
+ return mainError;
138
+ };
139
+ }
140
+ });
141
+
142
+ // ../../node_modules/.pnpm/retry@0.13.1/node_modules/retry/lib/retry.js
143
+ var require_retry = _chunkG7A32JAGjs.__commonJS.call(void 0, {
144
+ "../../node_modules/.pnpm/retry@0.13.1/node_modules/retry/lib/retry.js"(exports) {
145
+ "use strict";
146
+ var RetryOperation = require_retry_operation();
147
+ exports.operation = function(options) {
148
+ var timeouts = exports.timeouts(options);
149
+ return new RetryOperation(timeouts, {
150
+ forever: options && (options.forever || options.retries === Infinity),
151
+ unref: options && options.unref,
152
+ maxRetryTime: options && options.maxRetryTime
153
+ });
154
+ };
155
+ exports.timeouts = function(options) {
156
+ if (options instanceof Array) {
157
+ return [].concat(options);
158
+ }
159
+ var opts = {
160
+ retries: 10,
161
+ factor: 2,
162
+ minTimeout: 1 * 1e3,
163
+ maxTimeout: Infinity,
164
+ randomize: false
165
+ };
166
+ for (var key in options) {
167
+ opts[key] = options[key];
168
+ }
169
+ if (opts.minTimeout > opts.maxTimeout) {
170
+ throw new Error("minTimeout is greater than maxTimeout");
171
+ }
172
+ var timeouts = [];
173
+ for (var i = 0; i < opts.retries; i++) {
174
+ timeouts.push(this.createTimeout(i, opts));
175
+ }
176
+ if (options && options.forever && !timeouts.length) {
177
+ timeouts.push(this.createTimeout(i, opts));
178
+ }
179
+ timeouts.sort(function(a, b) {
180
+ return a - b;
181
+ });
182
+ return timeouts;
183
+ };
184
+ exports.createTimeout = function(attempt, opts) {
185
+ var random = opts.randomize ? Math.random() + 1 : 1;
186
+ var timeout = Math.round(random * Math.max(opts.minTimeout, 1) * Math.pow(opts.factor, attempt));
187
+ timeout = Math.min(timeout, opts.maxTimeout);
188
+ return timeout;
189
+ };
190
+ exports.wrap = function(obj, options, methods) {
191
+ if (options instanceof Array) {
192
+ methods = options;
193
+ options = null;
194
+ }
195
+ if (!methods) {
196
+ methods = [];
197
+ for (var key in obj) {
198
+ if (typeof obj[key] === "function") {
199
+ methods.push(key);
200
+ }
201
+ }
202
+ }
203
+ for (var i = 0; i < methods.length; i++) {
204
+ var method = methods[i];
205
+ var original = obj[method];
206
+ obj[method] = function retryWrapper(original2) {
207
+ var op = exports.operation(options);
208
+ var args = Array.prototype.slice.call(arguments, 1);
209
+ var callback = args.pop();
210
+ args.push(function(err) {
211
+ if (op.retry(err)) {
212
+ return;
213
+ }
214
+ if (err) {
215
+ arguments[0] = op.mainError();
216
+ }
217
+ callback.apply(this, arguments);
218
+ });
219
+ op.attempt(function() {
220
+ original2.apply(obj, args);
221
+ });
222
+ }.bind(obj, original);
223
+ obj[method].options = options;
224
+ }
225
+ };
226
+ }
227
+ });
228
+
229
+ // ../../node_modules/.pnpm/retry@0.13.1/node_modules/retry/index.js
230
+ var require_retry2 = _chunkG7A32JAGjs.__commonJS.call(void 0, {
231
+ "../../node_modules/.pnpm/retry@0.13.1/node_modules/retry/index.js"(exports, module) {
232
+ "use strict";
233
+ module.exports = require_retry();
234
+ }
235
+ });
236
+
237
+ // ../../node_modules/.pnpm/p-retry@4.6.2/node_modules/p-retry/index.js
238
+ var require_p_retry = _chunkG7A32JAGjs.__commonJS.call(void 0, {
239
+ "../../node_modules/.pnpm/p-retry@4.6.2/node_modules/p-retry/index.js"(exports, module) {
240
+ "use strict";
241
+ var retry = require_retry2();
242
+ var networkErrorMsgs = [
243
+ "Failed to fetch",
244
+ // Chrome
245
+ "NetworkError when attempting to fetch resource.",
246
+ // Firefox
247
+ "The Internet connection appears to be offline.",
248
+ // Safari
249
+ "Network request failed"
250
+ // `cross-fetch`
251
+ ];
252
+ var AbortError = class extends Error {
253
+ constructor(message) {
254
+ super();
255
+ if (message instanceof Error) {
256
+ this.originalError = message;
257
+ ({ message } = message);
258
+ } else {
259
+ this.originalError = new Error(message);
260
+ this.originalError.stack = this.stack;
261
+ }
262
+ this.name = "AbortError";
263
+ this.message = message;
264
+ }
265
+ };
266
+ var decorateErrorWithCounts = (error, attemptNumber, options) => {
267
+ const retriesLeft = options.retries - (attemptNumber - 1);
268
+ error.attemptNumber = attemptNumber;
269
+ error.retriesLeft = retriesLeft;
270
+ return error;
271
+ };
272
+ var isNetworkError = (errorMessage) => networkErrorMsgs.includes(errorMessage);
273
+ var pRetry2 = (input, options) => new Promise((resolve, reject) => {
274
+ options = {
275
+ onFailedAttempt: () => {
276
+ },
277
+ retries: 10,
278
+ ...options
279
+ };
280
+ const operation = retry.operation(options);
281
+ operation.attempt(async (attemptNumber) => {
282
+ try {
283
+ resolve(await input(attemptNumber));
284
+ } catch (error) {
285
+ if (!(error instanceof Error)) {
286
+ reject(new TypeError(`Non-error was thrown: "${error}". You should only throw errors.`));
287
+ return;
288
+ }
289
+ if (error instanceof AbortError) {
290
+ operation.stop();
291
+ reject(error.originalError);
292
+ } else if (error instanceof TypeError && !isNetworkError(error.message)) {
293
+ operation.stop();
294
+ reject(error);
295
+ } else {
296
+ decorateErrorWithCounts(error, attemptNumber, options);
297
+ try {
298
+ await options.onFailedAttempt(error);
299
+ } catch (error2) {
300
+ reject(error2);
301
+ return;
302
+ }
303
+ if (!operation.retry(error)) {
304
+ reject(operation.mainError());
305
+ }
306
+ }
307
+ }
308
+ });
309
+ });
310
+ module.exports = pRetry2;
311
+ module.exports.default = pRetry2;
312
+ module.exports.AbortError = AbortError;
313
+ }
314
+ });
315
+
316
+ // ../../node_modules/.pnpm/eventemitter3@4.0.7/node_modules/eventemitter3/index.js
317
+ var require_eventemitter3 = _chunkG7A32JAGjs.__commonJS.call(void 0, {
318
+ "../../node_modules/.pnpm/eventemitter3@4.0.7/node_modules/eventemitter3/index.js"(exports, module) {
319
+ "use strict";
320
+ var has = Object.prototype.hasOwnProperty;
321
+ var prefix = "~";
322
+ function Events() {
323
+ }
324
+ if (Object.create) {
325
+ Events.prototype = /* @__PURE__ */ Object.create(null);
326
+ if (!new Events().__proto__)
327
+ prefix = false;
328
+ }
329
+ function EE(fn, context, once) {
330
+ this.fn = fn;
331
+ this.context = context;
332
+ this.once = once || false;
333
+ }
334
+ function addListener(emitter, event, fn, context, once) {
335
+ if (typeof fn !== "function") {
336
+ throw new TypeError("The listener must be a function");
337
+ }
338
+ var listener = new EE(fn, context || emitter, once), evt = prefix ? prefix + event : event;
339
+ if (!emitter._events[evt])
340
+ emitter._events[evt] = listener, emitter._eventsCount++;
341
+ else if (!emitter._events[evt].fn)
342
+ emitter._events[evt].push(listener);
343
+ else
344
+ emitter._events[evt] = [emitter._events[evt], listener];
345
+ return emitter;
346
+ }
347
+ function clearEvent(emitter, evt) {
348
+ if (--emitter._eventsCount === 0)
349
+ emitter._events = new Events();
350
+ else
351
+ delete emitter._events[evt];
352
+ }
353
+ function EventEmitter() {
354
+ this._events = new Events();
355
+ this._eventsCount = 0;
356
+ }
357
+ EventEmitter.prototype.eventNames = function eventNames() {
358
+ var names = [], events, name;
359
+ if (this._eventsCount === 0)
360
+ return names;
361
+ for (name in events = this._events) {
362
+ if (has.call(events, name))
363
+ names.push(prefix ? name.slice(1) : name);
364
+ }
365
+ if (Object.getOwnPropertySymbols) {
366
+ return names.concat(Object.getOwnPropertySymbols(events));
367
+ }
368
+ return names;
369
+ };
370
+ EventEmitter.prototype.listeners = function listeners(event) {
371
+ var evt = prefix ? prefix + event : event, handlers = this._events[evt];
372
+ if (!handlers)
373
+ return [];
374
+ if (handlers.fn)
375
+ return [handlers.fn];
376
+ for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) {
377
+ ee[i] = handlers[i].fn;
378
+ }
379
+ return ee;
380
+ };
381
+ EventEmitter.prototype.listenerCount = function listenerCount(event) {
382
+ var evt = prefix ? prefix + event : event, listeners = this._events[evt];
383
+ if (!listeners)
384
+ return 0;
385
+ if (listeners.fn)
386
+ return 1;
387
+ return listeners.length;
388
+ };
389
+ EventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) {
390
+ var evt = prefix ? prefix + event : event;
391
+ if (!this._events[evt])
392
+ return false;
393
+ var listeners = this._events[evt], len = arguments.length, args, i;
394
+ if (listeners.fn) {
395
+ if (listeners.once)
396
+ this.removeListener(event, listeners.fn, void 0, true);
397
+ switch (len) {
398
+ case 1:
399
+ return listeners.fn.call(listeners.context), true;
400
+ case 2:
401
+ return listeners.fn.call(listeners.context, a1), true;
402
+ case 3:
403
+ return listeners.fn.call(listeners.context, a1, a2), true;
404
+ case 4:
405
+ return listeners.fn.call(listeners.context, a1, a2, a3), true;
406
+ case 5:
407
+ return listeners.fn.call(listeners.context, a1, a2, a3, a4), true;
408
+ case 6:
409
+ return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true;
410
+ }
411
+ for (i = 1, args = new Array(len - 1); i < len; i++) {
412
+ args[i - 1] = arguments[i];
413
+ }
414
+ listeners.fn.apply(listeners.context, args);
415
+ } else {
416
+ var length = listeners.length, j;
417
+ for (i = 0; i < length; i++) {
418
+ if (listeners[i].once)
419
+ this.removeListener(event, listeners[i].fn, void 0, true);
420
+ switch (len) {
421
+ case 1:
422
+ listeners[i].fn.call(listeners[i].context);
423
+ break;
424
+ case 2:
425
+ listeners[i].fn.call(listeners[i].context, a1);
426
+ break;
427
+ case 3:
428
+ listeners[i].fn.call(listeners[i].context, a1, a2);
429
+ break;
430
+ case 4:
431
+ listeners[i].fn.call(listeners[i].context, a1, a2, a3);
432
+ break;
433
+ default:
434
+ if (!args)
435
+ for (j = 1, args = new Array(len - 1); j < len; j++) {
436
+ args[j - 1] = arguments[j];
437
+ }
438
+ listeners[i].fn.apply(listeners[i].context, args);
439
+ }
440
+ }
441
+ }
442
+ return true;
443
+ };
444
+ EventEmitter.prototype.on = function on(event, fn, context) {
445
+ return addListener(this, event, fn, context, false);
446
+ };
447
+ EventEmitter.prototype.once = function once(event, fn, context) {
448
+ return addListener(this, event, fn, context, true);
449
+ };
450
+ EventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) {
451
+ var evt = prefix ? prefix + event : event;
452
+ if (!this._events[evt])
453
+ return this;
454
+ if (!fn) {
455
+ clearEvent(this, evt);
456
+ return this;
457
+ }
458
+ var listeners = this._events[evt];
459
+ if (listeners.fn) {
460
+ if (listeners.fn === fn && (!once || listeners.once) && (!context || listeners.context === context)) {
461
+ clearEvent(this, evt);
462
+ }
463
+ } else {
464
+ for (var i = 0, events = [], length = listeners.length; i < length; i++) {
465
+ if (listeners[i].fn !== fn || once && !listeners[i].once || context && listeners[i].context !== context) {
466
+ events.push(listeners[i]);
467
+ }
468
+ }
469
+ if (events.length)
470
+ this._events[evt] = events.length === 1 ? events[0] : events;
471
+ else
472
+ clearEvent(this, evt);
473
+ }
474
+ return this;
475
+ };
476
+ EventEmitter.prototype.removeAllListeners = function removeAllListeners(event) {
477
+ var evt;
478
+ if (event) {
479
+ evt = prefix ? prefix + event : event;
480
+ if (this._events[evt])
481
+ clearEvent(this, evt);
482
+ } else {
483
+ this._events = new Events();
484
+ this._eventsCount = 0;
485
+ }
486
+ return this;
487
+ };
488
+ EventEmitter.prototype.off = EventEmitter.prototype.removeListener;
489
+ EventEmitter.prototype.addListener = EventEmitter.prototype.on;
490
+ EventEmitter.prefixed = prefix;
491
+ EventEmitter.EventEmitter = EventEmitter;
492
+ if ("undefined" !== typeof module) {
493
+ module.exports = EventEmitter;
494
+ }
495
+ }
496
+ });
497
+
498
+ // ../../node_modules/.pnpm/p-finally@1.0.0/node_modules/p-finally/index.js
499
+ var require_p_finally = _chunkG7A32JAGjs.__commonJS.call(void 0, {
500
+ "../../node_modules/.pnpm/p-finally@1.0.0/node_modules/p-finally/index.js"(exports, module) {
501
+ "use strict";
502
+ module.exports = (promise, onFinally) => {
503
+ onFinally = onFinally || (() => {
504
+ });
505
+ return promise.then(
506
+ (val) => new Promise((resolve) => {
507
+ resolve(onFinally());
508
+ }).then(() => val),
509
+ (err) => new Promise((resolve) => {
510
+ resolve(onFinally());
511
+ }).then(() => {
512
+ throw err;
513
+ })
514
+ );
515
+ };
516
+ }
517
+ });
518
+
519
+ // ../../node_modules/.pnpm/p-timeout@3.2.0/node_modules/p-timeout/index.js
520
+ var require_p_timeout = _chunkG7A32JAGjs.__commonJS.call(void 0, {
521
+ "../../node_modules/.pnpm/p-timeout@3.2.0/node_modules/p-timeout/index.js"(exports, module) {
522
+ "use strict";
523
+ var pFinally = require_p_finally();
524
+ var TimeoutError = class extends Error {
525
+ constructor(message) {
526
+ super(message);
527
+ this.name = "TimeoutError";
528
+ }
529
+ };
530
+ var pTimeout = (promise, milliseconds, fallback) => new Promise((resolve, reject) => {
531
+ if (typeof milliseconds !== "number" || milliseconds < 0) {
532
+ throw new TypeError("Expected `milliseconds` to be a positive number");
533
+ }
534
+ if (milliseconds === Infinity) {
535
+ resolve(promise);
536
+ return;
537
+ }
538
+ const timer = setTimeout(() => {
539
+ if (typeof fallback === "function") {
540
+ try {
541
+ resolve(fallback());
542
+ } catch (error) {
543
+ reject(error);
544
+ }
545
+ return;
546
+ }
547
+ const message = typeof fallback === "string" ? fallback : `Promise timed out after ${milliseconds} milliseconds`;
548
+ const timeoutError = fallback instanceof Error ? fallback : new TimeoutError(message);
549
+ if (typeof promise.cancel === "function") {
550
+ promise.cancel();
551
+ }
552
+ reject(timeoutError);
553
+ }, milliseconds);
554
+ pFinally(
555
+ // eslint-disable-next-line promise/prefer-await-to-then
556
+ promise.then(resolve, reject),
557
+ () => {
558
+ clearTimeout(timer);
559
+ }
560
+ );
561
+ });
562
+ module.exports = pTimeout;
563
+ module.exports.default = pTimeout;
564
+ module.exports.TimeoutError = TimeoutError;
565
+ }
566
+ });
567
+
568
+ // ../../node_modules/.pnpm/p-queue@6.6.2/node_modules/p-queue/dist/lower-bound.js
569
+ var require_lower_bound = _chunkG7A32JAGjs.__commonJS.call(void 0, {
570
+ "../../node_modules/.pnpm/p-queue@6.6.2/node_modules/p-queue/dist/lower-bound.js"(exports) {
571
+ "use strict";
572
+ Object.defineProperty(exports, "__esModule", { value: true });
573
+ function lowerBound(array, value, comparator) {
574
+ let first = 0;
575
+ let count = array.length;
576
+ while (count > 0) {
577
+ const step = count / 2 | 0;
578
+ let it = first + step;
579
+ if (comparator(array[it], value) <= 0) {
580
+ first = ++it;
581
+ count -= step + 1;
582
+ } else {
583
+ count = step;
584
+ }
585
+ }
586
+ return first;
587
+ }
588
+ exports.default = lowerBound;
589
+ }
590
+ });
591
+
592
+ // ../../node_modules/.pnpm/p-queue@6.6.2/node_modules/p-queue/dist/priority-queue.js
593
+ var require_priority_queue = _chunkG7A32JAGjs.__commonJS.call(void 0, {
594
+ "../../node_modules/.pnpm/p-queue@6.6.2/node_modules/p-queue/dist/priority-queue.js"(exports) {
595
+ "use strict";
596
+ Object.defineProperty(exports, "__esModule", { value: true });
597
+ var lower_bound_1 = require_lower_bound();
598
+ var PriorityQueue = class {
599
+ constructor() {
600
+ this._queue = [];
601
+ }
602
+ enqueue(run, options) {
603
+ options = Object.assign({ priority: 0 }, options);
604
+ const element = {
605
+ priority: options.priority,
606
+ run
607
+ };
608
+ if (this.size && this._queue[this.size - 1].priority >= options.priority) {
609
+ this._queue.push(element);
610
+ return;
611
+ }
612
+ const index = lower_bound_1.default(this._queue, element, (a, b) => b.priority - a.priority);
613
+ this._queue.splice(index, 0, element);
614
+ }
615
+ dequeue() {
616
+ const item = this._queue.shift();
617
+ return item === null || item === void 0 ? void 0 : item.run;
618
+ }
619
+ filter(options) {
620
+ return this._queue.filter((element) => element.priority === options.priority).map((element) => element.run);
621
+ }
622
+ get size() {
623
+ return this._queue.length;
624
+ }
625
+ };
626
+ exports.default = PriorityQueue;
627
+ }
628
+ });
629
+
630
+ // ../../node_modules/.pnpm/p-queue@6.6.2/node_modules/p-queue/dist/index.js
631
+ var require_dist = _chunkG7A32JAGjs.__commonJS.call(void 0, {
632
+ "../../node_modules/.pnpm/p-queue@6.6.2/node_modules/p-queue/dist/index.js"(exports) {
633
+ "use strict";
634
+ Object.defineProperty(exports, "__esModule", { value: true });
635
+ var EventEmitter = require_eventemitter3();
636
+ var p_timeout_1 = require_p_timeout();
637
+ var priority_queue_1 = require_priority_queue();
638
+ var empty = () => {
639
+ };
640
+ var timeoutError = new p_timeout_1.TimeoutError();
641
+ var PQueue = class extends EventEmitter {
642
+ constructor(options) {
643
+ var _a, _b, _c, _d;
644
+ super();
645
+ this._intervalCount = 0;
646
+ this._intervalEnd = 0;
647
+ this._pendingCount = 0;
648
+ this._resolveEmpty = empty;
649
+ this._resolveIdle = empty;
650
+ options = Object.assign({ carryoverConcurrencyCount: false, intervalCap: Infinity, interval: 0, concurrency: Infinity, autoStart: true, queueClass: priority_queue_1.default }, options);
651
+ if (!(typeof options.intervalCap === "number" && options.intervalCap >= 1)) {
652
+ throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${(_b = (_a = options.intervalCap) === null || _a === void 0 ? void 0 : _a.toString()) !== null && _b !== void 0 ? _b : ""}\` (${typeof options.intervalCap})`);
653
+ }
654
+ if (options.interval === void 0 || !(Number.isFinite(options.interval) && options.interval >= 0)) {
655
+ throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${(_d = (_c = options.interval) === null || _c === void 0 ? void 0 : _c.toString()) !== null && _d !== void 0 ? _d : ""}\` (${typeof options.interval})`);
656
+ }
657
+ this._carryoverConcurrencyCount = options.carryoverConcurrencyCount;
658
+ this._isIntervalIgnored = options.intervalCap === Infinity || options.interval === 0;
659
+ this._intervalCap = options.intervalCap;
660
+ this._interval = options.interval;
661
+ this._queue = new options.queueClass();
662
+ this._queueClass = options.queueClass;
663
+ this.concurrency = options.concurrency;
664
+ this._timeout = options.timeout;
665
+ this._throwOnTimeout = options.throwOnTimeout === true;
666
+ this._isPaused = options.autoStart === false;
667
+ }
668
+ get _doesIntervalAllowAnother() {
669
+ return this._isIntervalIgnored || this._intervalCount < this._intervalCap;
670
+ }
671
+ get _doesConcurrentAllowAnother() {
672
+ return this._pendingCount < this._concurrency;
673
+ }
674
+ _next() {
675
+ this._pendingCount--;
676
+ this._tryToStartAnother();
677
+ this.emit("next");
678
+ }
679
+ _resolvePromises() {
680
+ this._resolveEmpty();
681
+ this._resolveEmpty = empty;
682
+ if (this._pendingCount === 0) {
683
+ this._resolveIdle();
684
+ this._resolveIdle = empty;
685
+ this.emit("idle");
686
+ }
687
+ }
688
+ _onResumeInterval() {
689
+ this._onInterval();
690
+ this._initializeIntervalIfNeeded();
691
+ this._timeoutId = void 0;
692
+ }
693
+ _isIntervalPaused() {
694
+ const now = Date.now();
695
+ if (this._intervalId === void 0) {
696
+ const delay = this._intervalEnd - now;
697
+ if (delay < 0) {
698
+ this._intervalCount = this._carryoverConcurrencyCount ? this._pendingCount : 0;
699
+ } else {
700
+ if (this._timeoutId === void 0) {
701
+ this._timeoutId = setTimeout(() => {
702
+ this._onResumeInterval();
703
+ }, delay);
704
+ }
705
+ return true;
706
+ }
707
+ }
708
+ return false;
709
+ }
710
+ _tryToStartAnother() {
711
+ if (this._queue.size === 0) {
712
+ if (this._intervalId) {
713
+ clearInterval(this._intervalId);
714
+ }
715
+ this._intervalId = void 0;
716
+ this._resolvePromises();
717
+ return false;
718
+ }
719
+ if (!this._isPaused) {
720
+ const canInitializeInterval = !this._isIntervalPaused();
721
+ if (this._doesIntervalAllowAnother && this._doesConcurrentAllowAnother) {
722
+ const job = this._queue.dequeue();
723
+ if (!job) {
724
+ return false;
725
+ }
726
+ this.emit("active");
727
+ job();
728
+ if (canInitializeInterval) {
729
+ this._initializeIntervalIfNeeded();
730
+ }
731
+ return true;
732
+ }
733
+ }
734
+ return false;
735
+ }
736
+ _initializeIntervalIfNeeded() {
737
+ if (this._isIntervalIgnored || this._intervalId !== void 0) {
738
+ return;
739
+ }
740
+ this._intervalId = setInterval(() => {
741
+ this._onInterval();
742
+ }, this._interval);
743
+ this._intervalEnd = Date.now() + this._interval;
744
+ }
745
+ _onInterval() {
746
+ if (this._intervalCount === 0 && this._pendingCount === 0 && this._intervalId) {
747
+ clearInterval(this._intervalId);
748
+ this._intervalId = void 0;
749
+ }
750
+ this._intervalCount = this._carryoverConcurrencyCount ? this._pendingCount : 0;
751
+ this._processQueue();
752
+ }
753
+ /**
754
+ Executes all queued functions until it reaches the limit.
755
+ */
756
+ _processQueue() {
757
+ while (this._tryToStartAnother()) {
758
+ }
759
+ }
760
+ get concurrency() {
761
+ return this._concurrency;
762
+ }
763
+ set concurrency(newConcurrency) {
764
+ if (!(typeof newConcurrency === "number" && newConcurrency >= 1)) {
765
+ throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${newConcurrency}\` (${typeof newConcurrency})`);
766
+ }
767
+ this._concurrency = newConcurrency;
768
+ this._processQueue();
769
+ }
770
+ /**
771
+ Adds a sync or async task to the queue. Always returns a promise.
772
+ */
773
+ async add(fn, options = {}) {
774
+ return new Promise((resolve, reject) => {
775
+ const run = async () => {
776
+ this._pendingCount++;
777
+ this._intervalCount++;
778
+ try {
779
+ const operation = this._timeout === void 0 && options.timeout === void 0 ? fn() : p_timeout_1.default(Promise.resolve(fn()), options.timeout === void 0 ? this._timeout : options.timeout, () => {
780
+ if (options.throwOnTimeout === void 0 ? this._throwOnTimeout : options.throwOnTimeout) {
781
+ reject(timeoutError);
782
+ }
783
+ return void 0;
784
+ });
785
+ resolve(await operation);
786
+ } catch (error) {
787
+ reject(error);
788
+ }
789
+ this._next();
790
+ };
791
+ this._queue.enqueue(run, options);
792
+ this._tryToStartAnother();
793
+ this.emit("add");
794
+ });
795
+ }
796
+ /**
797
+ Same as `.add()`, but accepts an array of sync or async functions.
798
+
799
+ @returns A promise that resolves when all functions are resolved.
800
+ */
801
+ async addAll(functions, options) {
802
+ return Promise.all(functions.map(async (function_) => this.add(function_, options)));
803
+ }
804
+ /**
805
+ Start (or resume) executing enqueued tasks within concurrency limit. No need to call this if queue is not paused (via `options.autoStart = false` or by `.pause()` method.)
806
+ */
807
+ start() {
808
+ if (!this._isPaused) {
809
+ return this;
810
+ }
811
+ this._isPaused = false;
812
+ this._processQueue();
813
+ return this;
814
+ }
815
+ /**
816
+ Put queue execution on hold.
817
+ */
818
+ pause() {
819
+ this._isPaused = true;
820
+ }
821
+ /**
822
+ Clear the queue.
823
+ */
824
+ clear() {
825
+ this._queue = new this._queueClass();
826
+ }
827
+ /**
828
+ Can be called multiple times. Useful if you for example add additional items at a later time.
829
+
830
+ @returns A promise that settles when the queue becomes empty.
831
+ */
832
+ async onEmpty() {
833
+ if (this._queue.size === 0) {
834
+ return;
835
+ }
836
+ return new Promise((resolve) => {
837
+ const existingResolve = this._resolveEmpty;
838
+ this._resolveEmpty = () => {
839
+ existingResolve();
840
+ resolve();
841
+ };
842
+ });
843
+ }
844
+ /**
845
+ The difference with `.onEmpty` is that `.onIdle` guarantees that all work from the queue has finished. `.onEmpty` merely signals that the queue is empty, but it could mean that some promises haven't completed yet.
846
+
847
+ @returns A promise that settles when the queue becomes empty, and all promises have completed; `queue.size === 0 && queue.pending === 0`.
848
+ */
849
+ async onIdle() {
850
+ if (this._pendingCount === 0 && this._queue.size === 0) {
851
+ return;
852
+ }
853
+ return new Promise((resolve) => {
854
+ const existingResolve = this._resolveIdle;
855
+ this._resolveIdle = () => {
856
+ existingResolve();
857
+ resolve();
858
+ };
859
+ });
860
+ }
861
+ /**
862
+ Size of the queue.
863
+ */
864
+ get size() {
865
+ return this._queue.size;
866
+ }
867
+ /**
868
+ Size of the queue, filtered by the given options.
869
+
870
+ For example, this can be used to find the number of items remaining in the queue with a specific priority level.
871
+ */
872
+ sizeBy(options) {
873
+ return this._queue.filter(options).length;
874
+ }
875
+ /**
876
+ Number of pending promises.
877
+ */
878
+ get pending() {
879
+ return this._pendingCount;
880
+ }
881
+ /**
882
+ Whether the queue is currently paused.
883
+ */
884
+ get isPaused() {
885
+ return this._isPaused;
886
+ }
887
+ get timeout() {
888
+ return this._timeout;
889
+ }
890
+ /**
891
+ Set the timeout for future operations.
892
+ */
893
+ set timeout(milliseconds) {
894
+ this._timeout = milliseconds;
895
+ }
896
+ };
897
+ exports.default = PQueue;
898
+ }
899
+ });
900
+
901
+ // ../../node_modules/.pnpm/langsmith@0.1.36_@langchain+core@0.3.26_openai@4.57.1_zod@3.23.8___langchain@0.3.8_@langchain_hhfvzcdxxvt4fjst2j6ox4bwsa/node_modules/langsmith/dist/traceable.js
902
+ var _async_hooks = require('async_hooks');
903
+
904
+ // ../../node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-node/rng.js
905
+ var _crypto = require('crypto'); var _crypto2 = _interopRequireDefault(_crypto);
906
+ var rnds8Pool = new Uint8Array(256);
907
+ var poolPtr = rnds8Pool.length;
908
+ function rng() {
909
+ if (poolPtr > rnds8Pool.length - 16) {
910
+ _crypto2.default.randomFillSync(rnds8Pool);
911
+ poolPtr = 0;
912
+ }
913
+ return rnds8Pool.slice(poolPtr, poolPtr += 16);
914
+ }
915
+
916
+ // ../../node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-node/regex.js
917
+ var regex_default = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;
918
+
919
+ // ../../node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-node/validate.js
920
+ function validate(uuid) {
921
+ return typeof uuid === "string" && regex_default.test(uuid);
922
+ }
923
+ var validate_default = validate;
924
+
925
+ // ../../node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-node/stringify.js
926
+ var byteToHex = [];
927
+ for (let i = 0; i < 256; ++i) {
928
+ byteToHex.push((i + 256).toString(16).slice(1));
929
+ }
930
+ function unsafeStringify(arr, offset = 0) {
931
+ return byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + "-" + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + "-" + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + "-" + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + "-" + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]];
932
+ }
933
+
934
+ // ../../node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-node/native.js
935
+
936
+ var native_default = {
937
+ randomUUID: _crypto2.default.randomUUID
938
+ };
939
+
940
+ // ../../node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-node/v4.js
941
+ function v4(options, buf, offset) {
942
+ if (native_default.randomUUID && !buf && !options) {
943
+ return native_default.randomUUID();
944
+ }
945
+ options = options || {};
946
+ const rnds = options.random || (options.rng || rng)();
947
+ rnds[6] = rnds[6] & 15 | 64;
948
+ rnds[8] = rnds[8] & 63 | 128;
949
+ if (buf) {
950
+ offset = offset || 0;
951
+ for (let i = 0; i < 16; ++i) {
952
+ buf[offset + i] = rnds[i];
953
+ }
954
+ return buf;
955
+ }
956
+ return unsafeStringify(rnds);
957
+ }
958
+ var v4_default = v4;
959
+
960
+ // ../../node_modules/.pnpm/langsmith@0.1.36_@langchain+core@0.3.26_openai@4.57.1_zod@3.23.8___langchain@0.3.8_@langchain_hhfvzcdxxvt4fjst2j6ox4bwsa/node_modules/langsmith/dist/utils/async_caller.js
961
+ var import_p_retry = _chunkG7A32JAGjs.__toESM.call(void 0, require_p_retry());
962
+ var import_p_queue = _chunkG7A32JAGjs.__toESM.call(void 0, require_dist());
963
+ var STATUS_NO_RETRY = [
964
+ 400,
965
+ // Bad Request
966
+ 401,
967
+ // Unauthorized
968
+ 403,
969
+ // Forbidden
970
+ 404,
971
+ // Not Found
972
+ 405,
973
+ // Method Not Allowed
974
+ 406,
975
+ // Not Acceptable
976
+ 407,
977
+ // Proxy Authentication Required
978
+ 408
979
+ // Request Timeout
980
+ ];
981
+ var STATUS_IGNORE = [
982
+ 409
983
+ // Conflict
984
+ ];
985
+ var AsyncCaller = class {
986
+ constructor(params) {
987
+ var _a, _b;
988
+ Object.defineProperty(this, "maxConcurrency", {
989
+ enumerable: true,
990
+ configurable: true,
991
+ writable: true,
992
+ value: void 0
993
+ });
994
+ Object.defineProperty(this, "maxRetries", {
995
+ enumerable: true,
996
+ configurable: true,
997
+ writable: true,
998
+ value: void 0
999
+ });
1000
+ Object.defineProperty(this, "queue", {
1001
+ enumerable: true,
1002
+ configurable: true,
1003
+ writable: true,
1004
+ value: void 0
1005
+ });
1006
+ Object.defineProperty(this, "onFailedResponseHook", {
1007
+ enumerable: true,
1008
+ configurable: true,
1009
+ writable: true,
1010
+ value: void 0
1011
+ });
1012
+ this.maxConcurrency = (_a = params.maxConcurrency) != null ? _a : Infinity;
1013
+ this.maxRetries = (_b = params.maxRetries) != null ? _b : 6;
1014
+ if ("default" in import_p_queue.default) {
1015
+ this.queue = new import_p_queue.default.default({
1016
+ concurrency: this.maxConcurrency
1017
+ });
1018
+ } else {
1019
+ this.queue = new import_p_queue.default({ concurrency: this.maxConcurrency });
1020
+ }
1021
+ this.onFailedResponseHook = params == null ? void 0 : params.onFailedResponseHook;
1022
+ }
1023
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
1024
+ call(callable, ...args) {
1025
+ const onFailedResponseHook = this.onFailedResponseHook;
1026
+ return this.queue.add(() => (0, import_p_retry.default)(() => callable(...args).catch((error) => {
1027
+ if (error instanceof Error) {
1028
+ throw error;
1029
+ } else {
1030
+ throw new Error(error);
1031
+ }
1032
+ }), {
1033
+ async onFailedAttempt(error) {
1034
+ if (error.message.startsWith("Cancel") || error.message.startsWith("TimeoutError") || error.message.startsWith("AbortError")) {
1035
+ throw error;
1036
+ }
1037
+ if ((error == null ? void 0 : error.code) === "ECONNABORTED") {
1038
+ throw error;
1039
+ }
1040
+ const response = error == null ? void 0 : error.response;
1041
+ const status = response == null ? void 0 : response.status;
1042
+ if (status) {
1043
+ if (STATUS_NO_RETRY.includes(+status)) {
1044
+ throw error;
1045
+ } else if (STATUS_IGNORE.includes(+status)) {
1046
+ return;
1047
+ }
1048
+ if (onFailedResponseHook) {
1049
+ await onFailedResponseHook(response);
1050
+ }
1051
+ }
1052
+ },
1053
+ // If needed we can change some of the defaults here,
1054
+ // but they're quite sensible.
1055
+ retries: this.maxRetries,
1056
+ randomize: true
1057
+ }), { throwOnTimeout: true });
1058
+ }
1059
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
1060
+ callWithOptions(options, callable, ...args) {
1061
+ if (options.signal) {
1062
+ return Promise.race([
1063
+ this.call(callable, ...args),
1064
+ new Promise((_, reject) => {
1065
+ var _a;
1066
+ (_a = options.signal) == null ? void 0 : _a.addEventListener("abort", () => {
1067
+ reject(new Error("AbortError"));
1068
+ });
1069
+ })
1070
+ ]);
1071
+ }
1072
+ return this.call(callable, ...args);
1073
+ }
1074
+ fetch(...args) {
1075
+ return this.call(() => fetch(...args).then((res) => res.ok ? res : Promise.reject(res)));
1076
+ }
1077
+ };
1078
+
1079
+ // ../../node_modules/.pnpm/langsmith@0.1.36_@langchain+core@0.3.26_openai@4.57.1_zod@3.23.8___langchain@0.3.8_@langchain_hhfvzcdxxvt4fjst2j6ox4bwsa/node_modules/langsmith/dist/utils/messages.js
1080
+ function isLangChainMessage(message) {
1081
+ return typeof (message == null ? void 0 : message._getType) === "function";
1082
+ }
1083
+ function convertLangChainMessageToExample(message) {
1084
+ const converted = {
1085
+ type: message._getType(),
1086
+ data: { content: message.content }
1087
+ };
1088
+ if ((message == null ? void 0 : message.additional_kwargs) && Object.keys(message.additional_kwargs).length > 0) {
1089
+ converted.data.additional_kwargs = { ...message.additional_kwargs };
1090
+ }
1091
+ return converted;
1092
+ }
1093
+
1094
+ // ../../node_modules/.pnpm/langsmith@0.1.36_@langchain+core@0.3.26_openai@4.57.1_zod@3.23.8___langchain@0.3.8_@langchain_hhfvzcdxxvt4fjst2j6ox4bwsa/node_modules/langsmith/dist/utils/_uuid.js
1095
+ function assertUuid(str) {
1096
+ if (!validate_default(str)) {
1097
+ throw new Error(`Invalid UUID: ${str}`);
1098
+ }
1099
+ }
1100
+
1101
+ // ../../node_modules/.pnpm/langsmith@0.1.36_@langchain+core@0.3.26_openai@4.57.1_zod@3.23.8___langchain@0.3.8_@langchain_hhfvzcdxxvt4fjst2j6ox4bwsa/node_modules/langsmith/dist/utils/warn.js
1102
+ var warnedMessages = {};
1103
+ function warnOnce(message) {
1104
+ if (!warnedMessages[message]) {
1105
+ console.warn(message);
1106
+ warnedMessages[message] = true;
1107
+ }
1108
+ }
1109
+
1110
+ // ../../node_modules/.pnpm/langsmith@0.1.36_@langchain+core@0.3.26_openai@4.57.1_zod@3.23.8___langchain@0.3.8_@langchain_hhfvzcdxxvt4fjst2j6ox4bwsa/node_modules/langsmith/dist/client.js
1111
+ async function mergeRuntimeEnvIntoRunCreates(runs) {
1112
+ const runtimeEnv = await getRuntimeEnvironment();
1113
+ const envVars = getLangChainEnvVarsMetadata();
1114
+ return runs.map((run) => {
1115
+ var _a, _b;
1116
+ const extra = (_a = run.extra) != null ? _a : {};
1117
+ const metadata = extra.metadata;
1118
+ run.extra = {
1119
+ ...extra,
1120
+ runtime: {
1121
+ ...runtimeEnv,
1122
+ ...extra == null ? void 0 : extra.runtime
1123
+ },
1124
+ metadata: {
1125
+ ...envVars,
1126
+ ...envVars.revision_id || run.revision_id ? { revision_id: (_b = run.revision_id) != null ? _b : envVars.revision_id } : {},
1127
+ ...metadata
1128
+ }
1129
+ };
1130
+ return run;
1131
+ });
1132
+ }
1133
+ var getTracingSamplingRate = () => {
1134
+ const samplingRateStr = getEnvironmentVariable("LANGCHAIN_TRACING_SAMPLING_RATE");
1135
+ if (samplingRateStr === void 0) {
1136
+ return void 0;
1137
+ }
1138
+ const samplingRate = parseFloat(samplingRateStr);
1139
+ if (samplingRate < 0 || samplingRate > 1) {
1140
+ throw new Error(`LANGCHAIN_TRACING_SAMPLING_RATE must be between 0 and 1 if set. Got: ${samplingRate}`);
1141
+ }
1142
+ return samplingRate;
1143
+ };
1144
+ var isLocalhost = (url) => {
1145
+ const strippedUrl = url.replace("http://", "").replace("https://", "");
1146
+ const hostname = strippedUrl.split("/")[0].split(":")[0];
1147
+ return hostname === "localhost" || hostname === "127.0.0.1" || hostname === "::1";
1148
+ };
1149
+ var raiseForStatus = async (response, operation) => {
1150
+ const body = await response.text();
1151
+ if (!response.ok) {
1152
+ throw new Error(`Failed to ${operation}: ${response.status} ${response.statusText} ${body}`);
1153
+ }
1154
+ };
1155
+ async function toArray(iterable) {
1156
+ const result = [];
1157
+ for await (const item of iterable) {
1158
+ result.push(item);
1159
+ }
1160
+ return result;
1161
+ }
1162
+ function trimQuotes(str) {
1163
+ if (str === void 0) {
1164
+ return void 0;
1165
+ }
1166
+ return str.trim().replace(/^"(.*)"$/, "$1").replace(/^'(.*)'$/, "$1");
1167
+ }
1168
+ var handle429 = async (response) => {
1169
+ var _a;
1170
+ if ((response == null ? void 0 : response.status) === 429) {
1171
+ const retryAfter = parseInt((_a = response.headers.get("retry-after")) != null ? _a : "30", 10) * 1e3;
1172
+ if (retryAfter > 0) {
1173
+ await new Promise((resolve) => setTimeout(resolve, retryAfter));
1174
+ return true;
1175
+ }
1176
+ }
1177
+ return false;
1178
+ };
1179
+ var Queue = class {
1180
+ constructor() {
1181
+ Object.defineProperty(this, "items", {
1182
+ enumerable: true,
1183
+ configurable: true,
1184
+ writable: true,
1185
+ value: []
1186
+ });
1187
+ }
1188
+ get size() {
1189
+ return this.items.length;
1190
+ }
1191
+ push(item) {
1192
+ return new Promise((resolve) => {
1193
+ this.items.push([item, resolve]);
1194
+ });
1195
+ }
1196
+ pop(upToN) {
1197
+ if (upToN < 1) {
1198
+ throw new Error("Number of items to pop off may not be less than 1.");
1199
+ }
1200
+ const popped = [];
1201
+ while (popped.length < upToN && this.items.length) {
1202
+ const item = this.items.shift();
1203
+ if (item) {
1204
+ popped.push(item);
1205
+ } else {
1206
+ break;
1207
+ }
1208
+ }
1209
+ return [popped.map((it) => it[0]), () => popped.forEach((it) => it[1]())];
1210
+ }
1211
+ };
1212
+ var DEFAULT_BATCH_SIZE_LIMIT_BYTES = 20971520;
1213
+ var Client = class _Client {
1214
+ constructor(config = {}) {
1215
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m;
1216
+ Object.defineProperty(this, "apiKey", {
1217
+ enumerable: true,
1218
+ configurable: true,
1219
+ writable: true,
1220
+ value: void 0
1221
+ });
1222
+ Object.defineProperty(this, "apiUrl", {
1223
+ enumerable: true,
1224
+ configurable: true,
1225
+ writable: true,
1226
+ value: void 0
1227
+ });
1228
+ Object.defineProperty(this, "webUrl", {
1229
+ enumerable: true,
1230
+ configurable: true,
1231
+ writable: true,
1232
+ value: void 0
1233
+ });
1234
+ Object.defineProperty(this, "caller", {
1235
+ enumerable: true,
1236
+ configurable: true,
1237
+ writable: true,
1238
+ value: void 0
1239
+ });
1240
+ Object.defineProperty(this, "batchIngestCaller", {
1241
+ enumerable: true,
1242
+ configurable: true,
1243
+ writable: true,
1244
+ value: void 0
1245
+ });
1246
+ Object.defineProperty(this, "timeout_ms", {
1247
+ enumerable: true,
1248
+ configurable: true,
1249
+ writable: true,
1250
+ value: void 0
1251
+ });
1252
+ Object.defineProperty(this, "_tenantId", {
1253
+ enumerable: true,
1254
+ configurable: true,
1255
+ writable: true,
1256
+ value: null
1257
+ });
1258
+ Object.defineProperty(this, "hideInputs", {
1259
+ enumerable: true,
1260
+ configurable: true,
1261
+ writable: true,
1262
+ value: void 0
1263
+ });
1264
+ Object.defineProperty(this, "hideOutputs", {
1265
+ enumerable: true,
1266
+ configurable: true,
1267
+ writable: true,
1268
+ value: void 0
1269
+ });
1270
+ Object.defineProperty(this, "tracingSampleRate", {
1271
+ enumerable: true,
1272
+ configurable: true,
1273
+ writable: true,
1274
+ value: void 0
1275
+ });
1276
+ Object.defineProperty(this, "sampledPostUuids", {
1277
+ enumerable: true,
1278
+ configurable: true,
1279
+ writable: true,
1280
+ value: /* @__PURE__ */ new Set()
1281
+ });
1282
+ Object.defineProperty(this, "autoBatchTracing", {
1283
+ enumerable: true,
1284
+ configurable: true,
1285
+ writable: true,
1286
+ value: true
1287
+ });
1288
+ Object.defineProperty(this, "batchEndpointSupported", {
1289
+ enumerable: true,
1290
+ configurable: true,
1291
+ writable: true,
1292
+ value: void 0
1293
+ });
1294
+ Object.defineProperty(this, "autoBatchQueue", {
1295
+ enumerable: true,
1296
+ configurable: true,
1297
+ writable: true,
1298
+ value: new Queue()
1299
+ });
1300
+ Object.defineProperty(this, "pendingAutoBatchedRunLimit", {
1301
+ enumerable: true,
1302
+ configurable: true,
1303
+ writable: true,
1304
+ value: 100
1305
+ });
1306
+ Object.defineProperty(this, "autoBatchTimeout", {
1307
+ enumerable: true,
1308
+ configurable: true,
1309
+ writable: true,
1310
+ value: void 0
1311
+ });
1312
+ Object.defineProperty(this, "autoBatchInitialDelayMs", {
1313
+ enumerable: true,
1314
+ configurable: true,
1315
+ writable: true,
1316
+ value: 250
1317
+ });
1318
+ Object.defineProperty(this, "autoBatchAggregationDelayMs", {
1319
+ enumerable: true,
1320
+ configurable: true,
1321
+ writable: true,
1322
+ value: 50
1323
+ });
1324
+ Object.defineProperty(this, "serverInfo", {
1325
+ enumerable: true,
1326
+ configurable: true,
1327
+ writable: true,
1328
+ value: void 0
1329
+ });
1330
+ Object.defineProperty(this, "fetchOptions", {
1331
+ enumerable: true,
1332
+ configurable: true,
1333
+ writable: true,
1334
+ value: void 0
1335
+ });
1336
+ const defaultConfig = _Client.getDefaultClientConfig();
1337
+ this.tracingSampleRate = getTracingSamplingRate();
1338
+ this.apiUrl = (_b = trimQuotes((_a = config.apiUrl) != null ? _a : defaultConfig.apiUrl)) != null ? _b : "";
1339
+ this.apiKey = trimQuotes((_c = config.apiKey) != null ? _c : defaultConfig.apiKey);
1340
+ this.webUrl = trimQuotes((_d = config.webUrl) != null ? _d : defaultConfig.webUrl);
1341
+ this.timeout_ms = (_e = config.timeout_ms) != null ? _e : 12e3;
1342
+ this.caller = new AsyncCaller((_f = config.callerOptions) != null ? _f : {});
1343
+ this.batchIngestCaller = new AsyncCaller({
1344
+ ...(_g = config.callerOptions) != null ? _g : {},
1345
+ onFailedResponseHook: handle429
1346
+ });
1347
+ this.hideInputs = (_i = (_h = config.hideInputs) != null ? _h : config.anonymizer) != null ? _i : defaultConfig.hideInputs;
1348
+ this.hideOutputs = (_k = (_j = config.hideOutputs) != null ? _j : config.anonymizer) != null ? _k : defaultConfig.hideOutputs;
1349
+ this.autoBatchTracing = (_l = config.autoBatchTracing) != null ? _l : this.autoBatchTracing;
1350
+ this.pendingAutoBatchedRunLimit = (_m = config.pendingAutoBatchedRunLimit) != null ? _m : this.pendingAutoBatchedRunLimit;
1351
+ this.fetchOptions = config.fetchOptions || {};
1352
+ }
1353
+ static getDefaultClientConfig() {
1354
+ var _a;
1355
+ const apiKey = getEnvironmentVariable("LANGCHAIN_API_KEY");
1356
+ const apiUrl = (_a = getEnvironmentVariable("LANGCHAIN_ENDPOINT")) != null ? _a : "https://api.smith.langchain.com";
1357
+ const hideInputs = getEnvironmentVariable("LANGCHAIN_HIDE_INPUTS") === "true";
1358
+ const hideOutputs = getEnvironmentVariable("LANGCHAIN_HIDE_OUTPUTS") === "true";
1359
+ return {
1360
+ apiUrl,
1361
+ apiKey,
1362
+ webUrl: void 0,
1363
+ hideInputs,
1364
+ hideOutputs
1365
+ };
1366
+ }
1367
+ getHostUrl() {
1368
+ if (this.webUrl) {
1369
+ return this.webUrl;
1370
+ } else if (isLocalhost(this.apiUrl)) {
1371
+ this.webUrl = "http://localhost:3000";
1372
+ return this.webUrl;
1373
+ } else if (this.apiUrl.includes("/api") && !this.apiUrl.split(".", 1)[0].endsWith("api")) {
1374
+ this.webUrl = this.apiUrl.replace("/api", "");
1375
+ return this.webUrl;
1376
+ } else if (this.apiUrl.split(".", 1)[0].includes("dev")) {
1377
+ this.webUrl = "https://dev.smith.langchain.com";
1378
+ return this.webUrl;
1379
+ } else {
1380
+ this.webUrl = "https://smith.langchain.com";
1381
+ return this.webUrl;
1382
+ }
1383
+ }
1384
+ get headers() {
1385
+ const headers = {
1386
+ "User-Agent": `langsmith-js/${__version__}`
1387
+ };
1388
+ if (this.apiKey) {
1389
+ headers["x-api-key"] = `${this.apiKey}`;
1390
+ }
1391
+ return headers;
1392
+ }
1393
+ processInputs(inputs) {
1394
+ if (this.hideInputs === false) {
1395
+ return inputs;
1396
+ }
1397
+ if (this.hideInputs === true) {
1398
+ return {};
1399
+ }
1400
+ if (typeof this.hideInputs === "function") {
1401
+ return this.hideInputs(inputs);
1402
+ }
1403
+ return inputs;
1404
+ }
1405
+ processOutputs(outputs) {
1406
+ if (this.hideOutputs === false) {
1407
+ return outputs;
1408
+ }
1409
+ if (this.hideOutputs === true) {
1410
+ return {};
1411
+ }
1412
+ if (typeof this.hideOutputs === "function") {
1413
+ return this.hideOutputs(outputs);
1414
+ }
1415
+ return outputs;
1416
+ }
1417
+ prepareRunCreateOrUpdateInputs(run) {
1418
+ const runParams = { ...run };
1419
+ if (runParams.inputs !== void 0) {
1420
+ runParams.inputs = this.processInputs(runParams.inputs);
1421
+ }
1422
+ if (runParams.outputs !== void 0) {
1423
+ runParams.outputs = this.processOutputs(runParams.outputs);
1424
+ }
1425
+ return runParams;
1426
+ }
1427
+ async _getResponse(path, queryParams) {
1428
+ var _a;
1429
+ const paramsString = (_a = queryParams == null ? void 0 : queryParams.toString()) != null ? _a : "";
1430
+ const url = `${this.apiUrl}${path}?${paramsString}`;
1431
+ const response = await this.caller.call(fetch, url, {
1432
+ method: "GET",
1433
+ headers: this.headers,
1434
+ signal: AbortSignal.timeout(this.timeout_ms),
1435
+ ...this.fetchOptions
1436
+ });
1437
+ if (!response.ok) {
1438
+ throw new Error(`Failed to fetch ${path}: ${response.status} ${response.statusText}`);
1439
+ }
1440
+ return response;
1441
+ }
1442
+ async _get(path, queryParams) {
1443
+ const response = await this._getResponse(path, queryParams);
1444
+ return response.json();
1445
+ }
1446
+ async *_getPaginated(path, queryParams = new URLSearchParams()) {
1447
+ let offset = Number(queryParams.get("offset")) || 0;
1448
+ const limit = Number(queryParams.get("limit")) || 100;
1449
+ while (true) {
1450
+ queryParams.set("offset", String(offset));
1451
+ queryParams.set("limit", String(limit));
1452
+ const url = `${this.apiUrl}${path}?${queryParams}`;
1453
+ const response = await this.caller.call(fetch, url, {
1454
+ method: "GET",
1455
+ headers: this.headers,
1456
+ signal: AbortSignal.timeout(this.timeout_ms),
1457
+ ...this.fetchOptions
1458
+ });
1459
+ if (!response.ok) {
1460
+ throw new Error(`Failed to fetch ${path}: ${response.status} ${response.statusText}`);
1461
+ }
1462
+ const items = await response.json();
1463
+ if (items.length === 0) {
1464
+ break;
1465
+ }
1466
+ yield items;
1467
+ if (items.length < limit) {
1468
+ break;
1469
+ }
1470
+ offset += items.length;
1471
+ }
1472
+ }
1473
+ async *_getCursorPaginatedList(path, body = null, requestMethod = "POST", dataKey = "runs") {
1474
+ const bodyParams = body ? { ...body } : {};
1475
+ while (true) {
1476
+ const response = await this.caller.call(fetch, `${this.apiUrl}${path}`, {
1477
+ method: requestMethod,
1478
+ headers: { ...this.headers, "Content-Type": "application/json" },
1479
+ signal: AbortSignal.timeout(this.timeout_ms),
1480
+ ...this.fetchOptions,
1481
+ body: JSON.stringify(bodyParams)
1482
+ });
1483
+ const responseBody = await response.json();
1484
+ if (!responseBody) {
1485
+ break;
1486
+ }
1487
+ if (!responseBody[dataKey]) {
1488
+ break;
1489
+ }
1490
+ yield responseBody[dataKey];
1491
+ const cursors = responseBody.cursors;
1492
+ if (!cursors) {
1493
+ break;
1494
+ }
1495
+ if (!cursors.next) {
1496
+ break;
1497
+ }
1498
+ bodyParams.cursor = cursors.next;
1499
+ }
1500
+ }
1501
+ _filterForSampling(runs, patch = false) {
1502
+ if (this.tracingSampleRate === void 0) {
1503
+ return runs;
1504
+ }
1505
+ if (patch) {
1506
+ const sampled = [];
1507
+ for (const run of runs) {
1508
+ if (this.sampledPostUuids.has(run.id)) {
1509
+ sampled.push(run);
1510
+ this.sampledPostUuids.delete(run.id);
1511
+ }
1512
+ }
1513
+ return sampled;
1514
+ } else {
1515
+ const sampled = [];
1516
+ for (const run of runs) {
1517
+ if (Math.random() < this.tracingSampleRate) {
1518
+ sampled.push(run);
1519
+ this.sampledPostUuids.add(run.id);
1520
+ }
1521
+ }
1522
+ return sampled;
1523
+ }
1524
+ }
1525
+ async drainAutoBatchQueue() {
1526
+ while (this.autoBatchQueue.size >= 0) {
1527
+ const [batch, done] = this.autoBatchQueue.pop(this.pendingAutoBatchedRunLimit);
1528
+ if (!batch.length) {
1529
+ done();
1530
+ return;
1531
+ }
1532
+ try {
1533
+ await this.batchIngestRuns({
1534
+ runCreates: batch.filter((item) => item.action === "create").map((item) => item.item),
1535
+ runUpdates: batch.filter((item) => item.action === "update").map((item) => item.item)
1536
+ });
1537
+ } finally {
1538
+ done();
1539
+ }
1540
+ }
1541
+ }
1542
+ async processRunOperation(item, immediatelyTriggerBatch) {
1543
+ const oldTimeout = this.autoBatchTimeout;
1544
+ clearTimeout(this.autoBatchTimeout);
1545
+ this.autoBatchTimeout = void 0;
1546
+ const itemPromise = this.autoBatchQueue.push(item);
1547
+ if (immediatelyTriggerBatch || this.autoBatchQueue.size > this.pendingAutoBatchedRunLimit) {
1548
+ await this.drainAutoBatchQueue();
1549
+ }
1550
+ if (this.autoBatchQueue.size > 0) {
1551
+ this.autoBatchTimeout = setTimeout(() => {
1552
+ this.autoBatchTimeout = void 0;
1553
+ void this.drainAutoBatchQueue().catch(console.error);
1554
+ }, oldTimeout ? this.autoBatchAggregationDelayMs : this.autoBatchInitialDelayMs);
1555
+ }
1556
+ return itemPromise;
1557
+ }
1558
+ async _getServerInfo() {
1559
+ const response = await fetch(`${this.apiUrl}/info`, {
1560
+ method: "GET",
1561
+ headers: { Accept: "application/json" },
1562
+ signal: AbortSignal.timeout(this.timeout_ms),
1563
+ ...this.fetchOptions
1564
+ });
1565
+ if (!response.ok) {
1566
+ await response.text();
1567
+ throw new Error("Failed to retrieve server info.");
1568
+ }
1569
+ return response.json();
1570
+ }
1571
+ async batchEndpointIsSupported() {
1572
+ try {
1573
+ this.serverInfo = await this._getServerInfo();
1574
+ } catch (e) {
1575
+ return false;
1576
+ }
1577
+ return true;
1578
+ }
1579
+ async createRun(run) {
1580
+ var _a;
1581
+ if (!this._filterForSampling([run]).length) {
1582
+ return;
1583
+ }
1584
+ const headers = { ...this.headers, "Content-Type": "application/json" };
1585
+ const session_name = run.project_name;
1586
+ delete run.project_name;
1587
+ const runCreate = this.prepareRunCreateOrUpdateInputs({
1588
+ session_name,
1589
+ ...run,
1590
+ start_time: (_a = run.start_time) != null ? _a : Date.now()
1591
+ });
1592
+ if (this.autoBatchTracing && runCreate.trace_id !== void 0 && runCreate.dotted_order !== void 0) {
1593
+ void this.processRunOperation({
1594
+ action: "create",
1595
+ item: runCreate
1596
+ }).catch(console.error);
1597
+ return;
1598
+ }
1599
+ const mergedRunCreateParams = await mergeRuntimeEnvIntoRunCreates([
1600
+ runCreate
1601
+ ]);
1602
+ const response = await this.caller.call(fetch, `${this.apiUrl}/runs`, {
1603
+ method: "POST",
1604
+ headers,
1605
+ body: JSON.stringify(mergedRunCreateParams[0]),
1606
+ signal: AbortSignal.timeout(this.timeout_ms),
1607
+ ...this.fetchOptions
1608
+ });
1609
+ await raiseForStatus(response, "create run");
1610
+ }
1611
+ /**
1612
+ * Batch ingest/upsert multiple runs in the Langsmith system.
1613
+ * @param runs
1614
+ */
1615
+ async batchIngestRuns({ runCreates, runUpdates }) {
1616
+ var _a, _b, _c, _d, _e;
1617
+ if (runCreates === void 0 && runUpdates === void 0) {
1618
+ return;
1619
+ }
1620
+ let preparedCreateParams = (_a = runCreates == null ? void 0 : runCreates.map((create) => this.prepareRunCreateOrUpdateInputs(create))) != null ? _a : [];
1621
+ let preparedUpdateParams = (_b = runUpdates == null ? void 0 : runUpdates.map((update) => this.prepareRunCreateOrUpdateInputs(update))) != null ? _b : [];
1622
+ if (preparedCreateParams.length > 0 && preparedUpdateParams.length > 0) {
1623
+ const createById = preparedCreateParams.reduce((params, run) => {
1624
+ if (!run.id) {
1625
+ return params;
1626
+ }
1627
+ params[run.id] = run;
1628
+ return params;
1629
+ }, {});
1630
+ const standaloneUpdates = [];
1631
+ for (const updateParam of preparedUpdateParams) {
1632
+ if (updateParam.id !== void 0 && createById[updateParam.id]) {
1633
+ createById[updateParam.id] = {
1634
+ ...createById[updateParam.id],
1635
+ ...updateParam
1636
+ };
1637
+ } else {
1638
+ standaloneUpdates.push(updateParam);
1639
+ }
1640
+ }
1641
+ preparedCreateParams = Object.values(createById);
1642
+ preparedUpdateParams = standaloneUpdates;
1643
+ }
1644
+ const rawBatch = {
1645
+ post: this._filterForSampling(preparedCreateParams),
1646
+ patch: this._filterForSampling(preparedUpdateParams, true)
1647
+ };
1648
+ if (!rawBatch.post.length && !rawBatch.patch.length) {
1649
+ return;
1650
+ }
1651
+ preparedCreateParams = await mergeRuntimeEnvIntoRunCreates(preparedCreateParams);
1652
+ if (this.batchEndpointSupported === void 0) {
1653
+ this.batchEndpointSupported = await this.batchEndpointIsSupported();
1654
+ }
1655
+ if (!this.batchEndpointSupported) {
1656
+ this.autoBatchTracing = false;
1657
+ for (const preparedCreateParam of rawBatch.post) {
1658
+ await this.createRun(preparedCreateParam);
1659
+ }
1660
+ for (const preparedUpdateParam of rawBatch.patch) {
1661
+ if (preparedUpdateParam.id !== void 0) {
1662
+ await this.updateRun(preparedUpdateParam.id, preparedUpdateParam);
1663
+ }
1664
+ }
1665
+ return;
1666
+ }
1667
+ const sizeLimitBytes = (_e = (_d = (_c = this.serverInfo) == null ? void 0 : _c.batch_ingest_config) == null ? void 0 : _d.size_limit_bytes) != null ? _e : DEFAULT_BATCH_SIZE_LIMIT_BYTES;
1668
+ const batchChunks = {
1669
+ post: [],
1670
+ patch: []
1671
+ };
1672
+ let currentBatchSizeBytes = 0;
1673
+ for (const k of ["post", "patch"]) {
1674
+ const key = k;
1675
+ const batchItems = rawBatch[key].reverse();
1676
+ let batchItem = batchItems.pop();
1677
+ while (batchItem !== void 0) {
1678
+ const stringifiedBatchItem = JSON.stringify(batchItem);
1679
+ if (currentBatchSizeBytes > 0 && currentBatchSizeBytes + stringifiedBatchItem.length > sizeLimitBytes) {
1680
+ await this._postBatchIngestRuns(JSON.stringify(batchChunks));
1681
+ currentBatchSizeBytes = 0;
1682
+ batchChunks.post = [];
1683
+ batchChunks.patch = [];
1684
+ }
1685
+ currentBatchSizeBytes += stringifiedBatchItem.length;
1686
+ batchChunks[key].push(batchItem);
1687
+ batchItem = batchItems.pop();
1688
+ }
1689
+ }
1690
+ if (batchChunks.post.length > 0 || batchChunks.patch.length > 0) {
1691
+ await this._postBatchIngestRuns(JSON.stringify(batchChunks));
1692
+ }
1693
+ }
1694
+ async _postBatchIngestRuns(body) {
1695
+ const headers = {
1696
+ ...this.headers,
1697
+ "Content-Type": "application/json",
1698
+ Accept: "application/json"
1699
+ };
1700
+ const response = await this.batchIngestCaller.call(fetch, `${this.apiUrl}/runs/batch`, {
1701
+ method: "POST",
1702
+ headers,
1703
+ body,
1704
+ signal: AbortSignal.timeout(this.timeout_ms),
1705
+ ...this.fetchOptions
1706
+ });
1707
+ await raiseForStatus(response, "batch create run");
1708
+ }
1709
+ async updateRun(runId, run) {
1710
+ assertUuid(runId);
1711
+ if (run.inputs) {
1712
+ run.inputs = this.processInputs(run.inputs);
1713
+ }
1714
+ if (run.outputs) {
1715
+ run.outputs = this.processOutputs(run.outputs);
1716
+ }
1717
+ const data = { ...run, id: runId };
1718
+ if (!this._filterForSampling([data], true).length) {
1719
+ return;
1720
+ }
1721
+ if (this.autoBatchTracing && data.trace_id !== void 0 && data.dotted_order !== void 0) {
1722
+ if (run.end_time !== void 0 && data.parent_run_id === void 0) {
1723
+ await this.processRunOperation({ action: "update", item: data }, true);
1724
+ return;
1725
+ } else {
1726
+ void this.processRunOperation({ action: "update", item: data }).catch(console.error);
1727
+ }
1728
+ return;
1729
+ }
1730
+ const headers = { ...this.headers, "Content-Type": "application/json" };
1731
+ const response = await this.caller.call(fetch, `${this.apiUrl}/runs/${runId}`, {
1732
+ method: "PATCH",
1733
+ headers,
1734
+ body: JSON.stringify(run),
1735
+ signal: AbortSignal.timeout(this.timeout_ms),
1736
+ ...this.fetchOptions
1737
+ });
1738
+ await raiseForStatus(response, "update run");
1739
+ }
1740
+ async readRun(runId, { loadChildRuns } = { loadChildRuns: false }) {
1741
+ assertUuid(runId);
1742
+ let run = await this._get(`/runs/${runId}`);
1743
+ if (loadChildRuns && run.child_run_ids) {
1744
+ run = await this._loadChildRuns(run);
1745
+ }
1746
+ return run;
1747
+ }
1748
+ async getRunUrl({ runId, run, projectOpts }) {
1749
+ if (run !== void 0) {
1750
+ let sessionId;
1751
+ if (run.session_id) {
1752
+ sessionId = run.session_id;
1753
+ } else if (projectOpts == null ? void 0 : projectOpts.projectName) {
1754
+ sessionId = (await this.readProject({ projectName: projectOpts == null ? void 0 : projectOpts.projectName })).id;
1755
+ } else if (projectOpts == null ? void 0 : projectOpts.projectId) {
1756
+ sessionId = projectOpts == null ? void 0 : projectOpts.projectId;
1757
+ } else {
1758
+ const project = await this.readProject({
1759
+ projectName: getEnvironmentVariable("LANGCHAIN_PROJECT") || "default"
1760
+ });
1761
+ sessionId = project.id;
1762
+ }
1763
+ const tenantId = await this._getTenantId();
1764
+ return `${this.getHostUrl()}/o/${tenantId}/projects/p/${sessionId}/r/${run.id}?poll=true`;
1765
+ } else if (runId !== void 0) {
1766
+ const run_ = await this.readRun(runId);
1767
+ if (!run_.app_path) {
1768
+ throw new Error(`Run ${runId} has no app_path`);
1769
+ }
1770
+ const baseUrl = this.getHostUrl();
1771
+ return `${baseUrl}${run_.app_path}`;
1772
+ } else {
1773
+ throw new Error("Must provide either runId or run");
1774
+ }
1775
+ }
1776
+ async _loadChildRuns(run) {
1777
+ const childRuns = await toArray(this.listRuns({ id: run.child_run_ids }));
1778
+ const treemap = {};
1779
+ const runs = {};
1780
+ childRuns.sort((a, b) => {
1781
+ var _a, _b;
1782
+ return ((_a = a == null ? void 0 : a.dotted_order) != null ? _a : "").localeCompare((_b = b == null ? void 0 : b.dotted_order) != null ? _b : "");
1783
+ });
1784
+ for (const childRun of childRuns) {
1785
+ if (childRun.parent_run_id === null || childRun.parent_run_id === void 0) {
1786
+ throw new Error(`Child run ${childRun.id} has no parent`);
1787
+ }
1788
+ if (!(childRun.parent_run_id in treemap)) {
1789
+ treemap[childRun.parent_run_id] = [];
1790
+ }
1791
+ treemap[childRun.parent_run_id].push(childRun);
1792
+ runs[childRun.id] = childRun;
1793
+ }
1794
+ run.child_runs = treemap[run.id] || [];
1795
+ for (const runId in treemap) {
1796
+ if (runId !== run.id) {
1797
+ runs[runId].child_runs = treemap[runId];
1798
+ }
1799
+ }
1800
+ return run;
1801
+ }
1802
+ /**
1803
+ * List runs from the LangSmith server.
1804
+ * @param projectId - The ID of the project to filter by.
1805
+ * @param projectName - The name of the project to filter by.
1806
+ * @param parentRunId - The ID of the parent run to filter by.
1807
+ * @param traceId - The ID of the trace to filter by.
1808
+ * @param referenceExampleId - The ID of the reference example to filter by.
1809
+ * @param startTime - The start time to filter by.
1810
+ * @param isRoot - Indicates whether to only return root runs.
1811
+ * @param runType - The run type to filter by.
1812
+ * @param error - Indicates whether to filter by error runs.
1813
+ * @param id - The ID of the run to filter by.
1814
+ * @param query - The query string to filter by.
1815
+ * @param filter - The filter string to apply to the run spans.
1816
+ * @param traceFilter - The filter string to apply on the root run of the trace.
1817
+ * @param limit - The maximum number of runs to retrieve.
1818
+ * @returns {AsyncIterable<Run>} - The runs.
1819
+ *
1820
+ * @example
1821
+ * // List all runs in a project
1822
+ * const projectRuns = client.listRuns({ projectName: "<your_project>" });
1823
+ *
1824
+ * @example
1825
+ * // List LLM and Chat runs in the last 24 hours
1826
+ * const todaysLLMRuns = client.listRuns({
1827
+ * projectName: "<your_project>",
1828
+ * start_time: new Date(Date.now() - 24 * 60 * 60 * 1000),
1829
+ * run_type: "llm",
1830
+ * });
1831
+ *
1832
+ * @example
1833
+ * // List traces in a project
1834
+ * const rootRuns = client.listRuns({
1835
+ * projectName: "<your_project>",
1836
+ * execution_order: 1,
1837
+ * });
1838
+ *
1839
+ * @example
1840
+ * // List runs without errors
1841
+ * const correctRuns = client.listRuns({
1842
+ * projectName: "<your_project>",
1843
+ * error: false,
1844
+ * });
1845
+ *
1846
+ * @example
1847
+ * // List runs by run ID
1848
+ * const runIds = [
1849
+ * "a36092d2-4ad5-4fb4-9c0d-0dba9a2ed836",
1850
+ * "9398e6be-964f-4aa4-8ae9-ad78cd4b7074",
1851
+ * ];
1852
+ * const selectedRuns = client.listRuns({ run_ids: runIds });
1853
+ *
1854
+ * @example
1855
+ * // List all "chain" type runs that took more than 10 seconds and had `total_tokens` greater than 5000
1856
+ * const chainRuns = client.listRuns({
1857
+ * projectName: "<your_project>",
1858
+ * filter: 'and(eq(run_type, "chain"), gt(latency, 10), gt(total_tokens, 5000))',
1859
+ * });
1860
+ *
1861
+ * @example
1862
+ * // List all runs called "extractor" whose root of the trace was assigned feedback "user_score" score of 1
1863
+ * const goodExtractorRuns = client.listRuns({
1864
+ * projectName: "<your_project>",
1865
+ * filter: 'eq(name, "extractor")',
1866
+ * traceFilter: 'and(eq(feedback_key, "user_score"), eq(feedback_score, 1))',
1867
+ * });
1868
+ *
1869
+ * @example
1870
+ * // List all runs that started after a specific timestamp and either have "error" not equal to null or a "Correctness" feedback score equal to 0
1871
+ * const complexRuns = client.listRuns({
1872
+ * projectName: "<your_project>",
1873
+ * filter: 'and(gt(start_time, "2023-07-15T12:34:56Z"), or(neq(error, null), and(eq(feedback_key, "Correctness"), eq(feedback_score, 0.0))))',
1874
+ * });
1875
+ *
1876
+ * @example
1877
+ * // List all runs where `tags` include "experimental" or "beta" and `latency` is greater than 2 seconds
1878
+ * const taggedRuns = client.listRuns({
1879
+ * projectName: "<your_project>",
1880
+ * filter: 'and(or(has(tags, "experimental"), has(tags, "beta")), gt(latency, 2))',
1881
+ * });
1882
+ */
1883
+ async *listRuns(props) {
1884
+ const { projectId, projectName, parentRunId, traceId, referenceExampleId, startTime, executionOrder, isRoot, runType, error, id, query, filter, traceFilter, treeFilter, limit, select } = props;
1885
+ let projectIds = [];
1886
+ if (projectId) {
1887
+ projectIds = Array.isArray(projectId) ? projectId : [projectId];
1888
+ }
1889
+ if (projectName) {
1890
+ const projectNames = Array.isArray(projectName) ? projectName : [projectName];
1891
+ const projectIds_ = await Promise.all(projectNames.map((name) => this.readProject({ projectName: name }).then((project) => project.id)));
1892
+ projectIds.push(...projectIds_);
1893
+ }
1894
+ const default_select = [
1895
+ "app_path",
1896
+ "child_run_ids",
1897
+ "completion_cost",
1898
+ "completion_tokens",
1899
+ "dotted_order",
1900
+ "end_time",
1901
+ "error",
1902
+ "events",
1903
+ "extra",
1904
+ "feedback_stats",
1905
+ "first_token_time",
1906
+ "id",
1907
+ "inputs",
1908
+ "name",
1909
+ "outputs",
1910
+ "parent_run_id",
1911
+ "parent_run_ids",
1912
+ "prompt_cost",
1913
+ "prompt_tokens",
1914
+ "reference_example_id",
1915
+ "run_type",
1916
+ "session_id",
1917
+ "start_time",
1918
+ "status",
1919
+ "tags",
1920
+ "total_cost",
1921
+ "total_tokens",
1922
+ "trace_id"
1923
+ ];
1924
+ const body = {
1925
+ session: projectIds.length ? projectIds : null,
1926
+ run_type: runType,
1927
+ reference_example: referenceExampleId,
1928
+ query,
1929
+ filter,
1930
+ trace_filter: traceFilter,
1931
+ tree_filter: treeFilter,
1932
+ execution_order: executionOrder,
1933
+ parent_run: parentRunId,
1934
+ start_time: startTime ? startTime.toISOString() : null,
1935
+ error,
1936
+ id,
1937
+ limit,
1938
+ trace: traceId,
1939
+ select: select ? select : default_select,
1940
+ is_root: isRoot
1941
+ };
1942
+ let runsYielded = 0;
1943
+ for await (const runs of this._getCursorPaginatedList("/runs/query", body)) {
1944
+ if (limit) {
1945
+ if (runsYielded >= limit) {
1946
+ break;
1947
+ }
1948
+ if (runs.length + runsYielded > limit) {
1949
+ const newRuns = runs.slice(0, limit - runsYielded);
1950
+ yield* newRuns;
1951
+ break;
1952
+ }
1953
+ runsYielded += runs.length;
1954
+ yield* runs;
1955
+ } else {
1956
+ yield* runs;
1957
+ }
1958
+ }
1959
+ }
1960
+ async shareRun(runId, { shareId } = {}) {
1961
+ const data = {
1962
+ run_id: runId,
1963
+ share_token: shareId || v4_default()
1964
+ };
1965
+ assertUuid(runId);
1966
+ const response = await this.caller.call(fetch, `${this.apiUrl}/runs/${runId}/share`, {
1967
+ method: "PUT",
1968
+ headers: this.headers,
1969
+ body: JSON.stringify(data),
1970
+ signal: AbortSignal.timeout(this.timeout_ms),
1971
+ ...this.fetchOptions
1972
+ });
1973
+ const result = await response.json();
1974
+ if (result === null || !("share_token" in result)) {
1975
+ throw new Error("Invalid response from server");
1976
+ }
1977
+ return `${this.getHostUrl()}/public/${result["share_token"]}/r`;
1978
+ }
1979
+ async unshareRun(runId) {
1980
+ assertUuid(runId);
1981
+ const response = await this.caller.call(fetch, `${this.apiUrl}/runs/${runId}/share`, {
1982
+ method: "DELETE",
1983
+ headers: this.headers,
1984
+ signal: AbortSignal.timeout(this.timeout_ms),
1985
+ ...this.fetchOptions
1986
+ });
1987
+ await raiseForStatus(response, "unshare run");
1988
+ }
1989
+ async readRunSharedLink(runId) {
1990
+ assertUuid(runId);
1991
+ const response = await this.caller.call(fetch, `${this.apiUrl}/runs/${runId}/share`, {
1992
+ method: "GET",
1993
+ headers: this.headers,
1994
+ signal: AbortSignal.timeout(this.timeout_ms),
1995
+ ...this.fetchOptions
1996
+ });
1997
+ const result = await response.json();
1998
+ if (result === null || !("share_token" in result)) {
1999
+ return void 0;
2000
+ }
2001
+ return `${this.getHostUrl()}/public/${result["share_token"]}/r`;
2002
+ }
2003
+ async listSharedRuns(shareToken, { runIds } = {}) {
2004
+ const queryParams = new URLSearchParams({
2005
+ share_token: shareToken
2006
+ });
2007
+ if (runIds !== void 0) {
2008
+ for (const runId of runIds) {
2009
+ queryParams.append("id", runId);
2010
+ }
2011
+ }
2012
+ assertUuid(shareToken);
2013
+ const response = await this.caller.call(fetch, `${this.apiUrl}/public/${shareToken}/runs${queryParams}`, {
2014
+ method: "GET",
2015
+ headers: this.headers,
2016
+ signal: AbortSignal.timeout(this.timeout_ms),
2017
+ ...this.fetchOptions
2018
+ });
2019
+ const runs = await response.json();
2020
+ return runs;
2021
+ }
2022
+ async readDatasetSharedSchema(datasetId, datasetName) {
2023
+ if (!datasetId && !datasetName) {
2024
+ throw new Error("Either datasetId or datasetName must be given");
2025
+ }
2026
+ if (!datasetId) {
2027
+ const dataset = await this.readDataset({ datasetName });
2028
+ datasetId = dataset.id;
2029
+ }
2030
+ assertUuid(datasetId);
2031
+ const response = await this.caller.call(fetch, `${this.apiUrl}/datasets/${datasetId}/share`, {
2032
+ method: "GET",
2033
+ headers: this.headers,
2034
+ signal: AbortSignal.timeout(this.timeout_ms),
2035
+ ...this.fetchOptions
2036
+ });
2037
+ const shareSchema = await response.json();
2038
+ shareSchema.url = `${this.getHostUrl()}/public/${shareSchema.share_token}/d`;
2039
+ return shareSchema;
2040
+ }
2041
+ async shareDataset(datasetId, datasetName) {
2042
+ if (!datasetId && !datasetName) {
2043
+ throw new Error("Either datasetId or datasetName must be given");
2044
+ }
2045
+ if (!datasetId) {
2046
+ const dataset = await this.readDataset({ datasetName });
2047
+ datasetId = dataset.id;
2048
+ }
2049
+ const data = {
2050
+ dataset_id: datasetId
2051
+ };
2052
+ assertUuid(datasetId);
2053
+ const response = await this.caller.call(fetch, `${this.apiUrl}/datasets/${datasetId}/share`, {
2054
+ method: "PUT",
2055
+ headers: this.headers,
2056
+ body: JSON.stringify(data),
2057
+ signal: AbortSignal.timeout(this.timeout_ms),
2058
+ ...this.fetchOptions
2059
+ });
2060
+ const shareSchema = await response.json();
2061
+ shareSchema.url = `${this.getHostUrl()}/public/${shareSchema.share_token}/d`;
2062
+ return shareSchema;
2063
+ }
2064
+ async unshareDataset(datasetId) {
2065
+ assertUuid(datasetId);
2066
+ const response = await this.caller.call(fetch, `${this.apiUrl}/datasets/${datasetId}/share`, {
2067
+ method: "DELETE",
2068
+ headers: this.headers,
2069
+ signal: AbortSignal.timeout(this.timeout_ms),
2070
+ ...this.fetchOptions
2071
+ });
2072
+ await raiseForStatus(response, "unshare dataset");
2073
+ }
2074
+ async readSharedDataset(shareToken) {
2075
+ assertUuid(shareToken);
2076
+ const response = await this.caller.call(fetch, `${this.apiUrl}/public/${shareToken}/datasets`, {
2077
+ method: "GET",
2078
+ headers: this.headers,
2079
+ signal: AbortSignal.timeout(this.timeout_ms),
2080
+ ...this.fetchOptions
2081
+ });
2082
+ const dataset = await response.json();
2083
+ return dataset;
2084
+ }
2085
+ async createProject({ projectName, description = null, metadata = null, upsert = false, projectExtra = null, referenceDatasetId = null }) {
2086
+ const upsert_ = upsert ? `?upsert=true` : "";
2087
+ const endpoint = `${this.apiUrl}/sessions${upsert_}`;
2088
+ const extra = projectExtra || {};
2089
+ if (metadata) {
2090
+ extra["metadata"] = metadata;
2091
+ }
2092
+ const body = {
2093
+ name: projectName,
2094
+ extra,
2095
+ description
2096
+ };
2097
+ if (referenceDatasetId !== null) {
2098
+ body["reference_dataset_id"] = referenceDatasetId;
2099
+ }
2100
+ const response = await this.caller.call(fetch, endpoint, {
2101
+ method: "POST",
2102
+ headers: { ...this.headers, "Content-Type": "application/json" },
2103
+ body: JSON.stringify(body),
2104
+ signal: AbortSignal.timeout(this.timeout_ms),
2105
+ ...this.fetchOptions
2106
+ });
2107
+ const result = await response.json();
2108
+ if (!response.ok) {
2109
+ throw new Error(`Failed to create session ${projectName}: ${response.status} ${response.statusText}`);
2110
+ }
2111
+ return result;
2112
+ }
2113
+ async updateProject(projectId, { name = null, description = null, metadata = null, projectExtra = null, endTime = null }) {
2114
+ const endpoint = `${this.apiUrl}/sessions/${projectId}`;
2115
+ let extra = projectExtra;
2116
+ if (metadata) {
2117
+ extra = { ...extra || {}, metadata };
2118
+ }
2119
+ const body = {
2120
+ name,
2121
+ extra,
2122
+ description,
2123
+ end_time: endTime ? new Date(endTime).toISOString() : null
2124
+ };
2125
+ const response = await this.caller.call(fetch, endpoint, {
2126
+ method: "PATCH",
2127
+ headers: { ...this.headers, "Content-Type": "application/json" },
2128
+ body: JSON.stringify(body),
2129
+ signal: AbortSignal.timeout(this.timeout_ms),
2130
+ ...this.fetchOptions
2131
+ });
2132
+ const result = await response.json();
2133
+ if (!response.ok) {
2134
+ throw new Error(`Failed to update project ${projectId}: ${response.status} ${response.statusText}`);
2135
+ }
2136
+ return result;
2137
+ }
2138
+ async hasProject({ projectId, projectName }) {
2139
+ let path = "/sessions";
2140
+ const params = new URLSearchParams();
2141
+ if (projectId !== void 0 && projectName !== void 0) {
2142
+ throw new Error("Must provide either projectName or projectId, not both");
2143
+ } else if (projectId !== void 0) {
2144
+ assertUuid(projectId);
2145
+ path += `/${projectId}`;
2146
+ } else if (projectName !== void 0) {
2147
+ params.append("name", projectName);
2148
+ } else {
2149
+ throw new Error("Must provide projectName or projectId");
2150
+ }
2151
+ const response = await this.caller.call(fetch, `${this.apiUrl}${path}?${params}`, {
2152
+ method: "GET",
2153
+ headers: this.headers,
2154
+ signal: AbortSignal.timeout(this.timeout_ms),
2155
+ ...this.fetchOptions
2156
+ });
2157
+ try {
2158
+ const result = await response.json();
2159
+ if (!response.ok) {
2160
+ return false;
2161
+ }
2162
+ if (Array.isArray(result)) {
2163
+ return result.length > 0;
2164
+ }
2165
+ return true;
2166
+ } catch (e) {
2167
+ return false;
2168
+ }
2169
+ }
2170
+ async readProject({ projectId, projectName, includeStats }) {
2171
+ let path = "/sessions";
2172
+ const params = new URLSearchParams();
2173
+ if (projectId !== void 0 && projectName !== void 0) {
2174
+ throw new Error("Must provide either projectName or projectId, not both");
2175
+ } else if (projectId !== void 0) {
2176
+ assertUuid(projectId);
2177
+ path += `/${projectId}`;
2178
+ } else if (projectName !== void 0) {
2179
+ params.append("name", projectName);
2180
+ } else {
2181
+ throw new Error("Must provide projectName or projectId");
2182
+ }
2183
+ if (includeStats !== void 0) {
2184
+ params.append("include_stats", includeStats.toString());
2185
+ }
2186
+ const response = await this._get(path, params);
2187
+ let result;
2188
+ if (Array.isArray(response)) {
2189
+ if (response.length === 0) {
2190
+ throw new Error(`Project[id=${projectId}, name=${projectName}] not found`);
2191
+ }
2192
+ result = response[0];
2193
+ } else {
2194
+ result = response;
2195
+ }
2196
+ return result;
2197
+ }
2198
+ async getProjectUrl({ projectId, projectName }) {
2199
+ if (projectId === void 0 && projectName === void 0) {
2200
+ throw new Error("Must provide either projectName or projectId");
2201
+ }
2202
+ const project = await this.readProject({ projectId, projectName });
2203
+ const tenantId = await this._getTenantId();
2204
+ return `${this.getHostUrl()}/o/${tenantId}/projects/p/${project.id}`;
2205
+ }
2206
+ async getDatasetUrl({ datasetId, datasetName }) {
2207
+ if (datasetId === void 0 && datasetName === void 0) {
2208
+ throw new Error("Must provide either datasetName or datasetId");
2209
+ }
2210
+ const dataset = await this.readDataset({ datasetId, datasetName });
2211
+ const tenantId = await this._getTenantId();
2212
+ return `${this.getHostUrl()}/o/${tenantId}/datasets/${dataset.id}`;
2213
+ }
2214
+ async _getTenantId() {
2215
+ if (this._tenantId !== null) {
2216
+ return this._tenantId;
2217
+ }
2218
+ const queryParams = new URLSearchParams({ limit: "1" });
2219
+ for await (const projects of this._getPaginated("/sessions", queryParams)) {
2220
+ this._tenantId = projects[0].tenant_id;
2221
+ return projects[0].tenant_id;
2222
+ }
2223
+ throw new Error("No projects found to resolve tenant.");
2224
+ }
2225
+ async *listProjects({ projectIds, name, nameContains, referenceDatasetId, referenceDatasetName, referenceFree } = {}) {
2226
+ const params = new URLSearchParams();
2227
+ if (projectIds !== void 0) {
2228
+ for (const projectId of projectIds) {
2229
+ params.append("id", projectId);
2230
+ }
2231
+ }
2232
+ if (name !== void 0) {
2233
+ params.append("name", name);
2234
+ }
2235
+ if (nameContains !== void 0) {
2236
+ params.append("name_contains", nameContains);
2237
+ }
2238
+ if (referenceDatasetId !== void 0) {
2239
+ params.append("reference_dataset", referenceDatasetId);
2240
+ } else if (referenceDatasetName !== void 0) {
2241
+ const dataset = await this.readDataset({
2242
+ datasetName: referenceDatasetName
2243
+ });
2244
+ params.append("reference_dataset", dataset.id);
2245
+ }
2246
+ if (referenceFree !== void 0) {
2247
+ params.append("reference_free", referenceFree.toString());
2248
+ }
2249
+ for await (const projects of this._getPaginated("/sessions", params)) {
2250
+ yield* projects;
2251
+ }
2252
+ }
2253
+ async deleteProject({ projectId, projectName }) {
2254
+ let projectId_;
2255
+ if (projectId === void 0 && projectName === void 0) {
2256
+ throw new Error("Must provide projectName or projectId");
2257
+ } else if (projectId !== void 0 && projectName !== void 0) {
2258
+ throw new Error("Must provide either projectName or projectId, not both");
2259
+ } else if (projectId === void 0) {
2260
+ projectId_ = (await this.readProject({ projectName })).id;
2261
+ } else {
2262
+ projectId_ = projectId;
2263
+ }
2264
+ assertUuid(projectId_);
2265
+ const response = await this.caller.call(fetch, `${this.apiUrl}/sessions/${projectId_}`, {
2266
+ method: "DELETE",
2267
+ headers: this.headers,
2268
+ signal: AbortSignal.timeout(this.timeout_ms),
2269
+ ...this.fetchOptions
2270
+ });
2271
+ await raiseForStatus(response, `delete session ${projectId_} (${projectName})`);
2272
+ }
2273
+ async uploadCsv({ csvFile, fileName, inputKeys, outputKeys, description, dataType, name }) {
2274
+ const url = `${this.apiUrl}/datasets/upload`;
2275
+ const formData = new FormData();
2276
+ formData.append("file", csvFile, fileName);
2277
+ inputKeys.forEach((key) => {
2278
+ formData.append("input_keys", key);
2279
+ });
2280
+ outputKeys.forEach((key) => {
2281
+ formData.append("output_keys", key);
2282
+ });
2283
+ if (description) {
2284
+ formData.append("description", description);
2285
+ }
2286
+ if (dataType) {
2287
+ formData.append("data_type", dataType);
2288
+ }
2289
+ if (name) {
2290
+ formData.append("name", name);
2291
+ }
2292
+ const response = await this.caller.call(fetch, url, {
2293
+ method: "POST",
2294
+ headers: this.headers,
2295
+ body: formData,
2296
+ signal: AbortSignal.timeout(this.timeout_ms),
2297
+ ...this.fetchOptions
2298
+ });
2299
+ if (!response.ok) {
2300
+ const result2 = await response.json();
2301
+ if (result2.detail && result2.detail.includes("already exists")) {
2302
+ throw new Error(`Dataset ${fileName} already exists`);
2303
+ }
2304
+ throw new Error(`Failed to upload CSV: ${response.status} ${response.statusText}`);
2305
+ }
2306
+ const result = await response.json();
2307
+ return result;
2308
+ }
2309
+ async createDataset(name, { description, dataType } = {}) {
2310
+ const body = {
2311
+ name,
2312
+ description
2313
+ };
2314
+ if (dataType) {
2315
+ body.data_type = dataType;
2316
+ }
2317
+ const response = await this.caller.call(fetch, `${this.apiUrl}/datasets`, {
2318
+ method: "POST",
2319
+ headers: { ...this.headers, "Content-Type": "application/json" },
2320
+ body: JSON.stringify(body),
2321
+ signal: AbortSignal.timeout(this.timeout_ms),
2322
+ ...this.fetchOptions
2323
+ });
2324
+ if (!response.ok) {
2325
+ const result2 = await response.json();
2326
+ if (result2.detail && result2.detail.includes("already exists")) {
2327
+ throw new Error(`Dataset ${name} already exists`);
2328
+ }
2329
+ throw new Error(`Failed to create dataset ${response.status} ${response.statusText}`);
2330
+ }
2331
+ const result = await response.json();
2332
+ return result;
2333
+ }
2334
+ async readDataset({ datasetId, datasetName }) {
2335
+ let path = "/datasets";
2336
+ const params = new URLSearchParams({ limit: "1" });
2337
+ if (datasetId !== void 0 && datasetName !== void 0) {
2338
+ throw new Error("Must provide either datasetName or datasetId, not both");
2339
+ } else if (datasetId !== void 0) {
2340
+ assertUuid(datasetId);
2341
+ path += `/${datasetId}`;
2342
+ } else if (datasetName !== void 0) {
2343
+ params.append("name", datasetName);
2344
+ } else {
2345
+ throw new Error("Must provide datasetName or datasetId");
2346
+ }
2347
+ const response = await this._get(path, params);
2348
+ let result;
2349
+ if (Array.isArray(response)) {
2350
+ if (response.length === 0) {
2351
+ throw new Error(`Dataset[id=${datasetId}, name=${datasetName}] not found`);
2352
+ }
2353
+ result = response[0];
2354
+ } else {
2355
+ result = response;
2356
+ }
2357
+ return result;
2358
+ }
2359
+ async hasDataset({ datasetId, datasetName }) {
2360
+ try {
2361
+ await this.readDataset({ datasetId, datasetName });
2362
+ return true;
2363
+ } catch (e) {
2364
+ if (
2365
+ // eslint-disable-next-line no-instanceof/no-instanceof
2366
+ e instanceof Error && e.message.toLocaleLowerCase().includes("not found")
2367
+ ) {
2368
+ return false;
2369
+ }
2370
+ throw e;
2371
+ }
2372
+ }
2373
+ async diffDatasetVersions({ datasetId, datasetName, fromVersion, toVersion }) {
2374
+ let datasetId_ = datasetId;
2375
+ if (datasetId_ === void 0 && datasetName === void 0) {
2376
+ throw new Error("Must provide either datasetName or datasetId");
2377
+ } else if (datasetId_ !== void 0 && datasetName !== void 0) {
2378
+ throw new Error("Must provide either datasetName or datasetId, not both");
2379
+ } else if (datasetId_ === void 0) {
2380
+ const dataset = await this.readDataset({ datasetName });
2381
+ datasetId_ = dataset.id;
2382
+ }
2383
+ const urlParams = new URLSearchParams({
2384
+ from_version: typeof fromVersion === "string" ? fromVersion : fromVersion.toISOString(),
2385
+ to_version: typeof toVersion === "string" ? toVersion : toVersion.toISOString()
2386
+ });
2387
+ const response = await this._get(`/datasets/${datasetId_}/versions/diff`, urlParams);
2388
+ return response;
2389
+ }
2390
+ async readDatasetOpenaiFinetuning({ datasetId, datasetName }) {
2391
+ const path = "/datasets";
2392
+ if (datasetId !== void 0) {
2393
+ } else if (datasetName !== void 0) {
2394
+ datasetId = (await this.readDataset({ datasetName })).id;
2395
+ } else {
2396
+ throw new Error("Must provide datasetName or datasetId");
2397
+ }
2398
+ const response = await this._getResponse(`${path}/${datasetId}/openai_ft`);
2399
+ const datasetText = await response.text();
2400
+ const dataset = datasetText.trim().split("\n").map((line) => JSON.parse(line));
2401
+ return dataset;
2402
+ }
2403
+ async *listDatasets({ limit = 100, offset = 0, datasetIds, datasetName, datasetNameContains } = {}) {
2404
+ const path = "/datasets";
2405
+ const params = new URLSearchParams({
2406
+ limit: limit.toString(),
2407
+ offset: offset.toString()
2408
+ });
2409
+ if (datasetIds !== void 0) {
2410
+ for (const id_ of datasetIds) {
2411
+ params.append("id", id_);
2412
+ }
2413
+ }
2414
+ if (datasetName !== void 0) {
2415
+ params.append("name", datasetName);
2416
+ }
2417
+ if (datasetNameContains !== void 0) {
2418
+ params.append("name_contains", datasetNameContains);
2419
+ }
2420
+ for await (const datasets of this._getPaginated(path, params)) {
2421
+ yield* datasets;
2422
+ }
2423
+ }
2424
+ /**
2425
+ * Update a dataset
2426
+ * @param props The dataset details to update
2427
+ * @returns The updated dataset
2428
+ */
2429
+ async updateDataset(props) {
2430
+ const { datasetId, datasetName, ...update } = props;
2431
+ if (!datasetId && !datasetName) {
2432
+ throw new Error("Must provide either datasetName or datasetId");
2433
+ }
2434
+ const _datasetId = datasetId != null ? datasetId : (await this.readDataset({ datasetName })).id;
2435
+ assertUuid(_datasetId);
2436
+ const response = await this.caller.call(fetch, `${this.apiUrl}/datasets/${_datasetId}`, {
2437
+ method: "PATCH",
2438
+ headers: { ...this.headers, "Content-Type": "application/json" },
2439
+ body: JSON.stringify(update),
2440
+ signal: AbortSignal.timeout(this.timeout_ms),
2441
+ ...this.fetchOptions
2442
+ });
2443
+ if (!response.ok) {
2444
+ throw new Error(`Failed to update dataset ${_datasetId}: ${response.status} ${response.statusText}`);
2445
+ }
2446
+ return await response.json();
2447
+ }
2448
+ async deleteDataset({ datasetId, datasetName }) {
2449
+ let path = "/datasets";
2450
+ let datasetId_ = datasetId;
2451
+ if (datasetId !== void 0 && datasetName !== void 0) {
2452
+ throw new Error("Must provide either datasetName or datasetId, not both");
2453
+ } else if (datasetName !== void 0) {
2454
+ const dataset = await this.readDataset({ datasetName });
2455
+ datasetId_ = dataset.id;
2456
+ }
2457
+ if (datasetId_ !== void 0) {
2458
+ assertUuid(datasetId_);
2459
+ path += `/${datasetId_}`;
2460
+ } else {
2461
+ throw new Error("Must provide datasetName or datasetId");
2462
+ }
2463
+ const response = await this.caller.call(fetch, this.apiUrl + path, {
2464
+ method: "DELETE",
2465
+ headers: this.headers,
2466
+ signal: AbortSignal.timeout(this.timeout_ms),
2467
+ ...this.fetchOptions
2468
+ });
2469
+ if (!response.ok) {
2470
+ throw new Error(`Failed to delete ${path}: ${response.status} ${response.statusText}`);
2471
+ }
2472
+ await response.json();
2473
+ }
2474
+ async createExample(inputs, outputs, { datasetId, datasetName, createdAt, exampleId, metadata, split }) {
2475
+ let datasetId_ = datasetId;
2476
+ if (datasetId_ === void 0 && datasetName === void 0) {
2477
+ throw new Error("Must provide either datasetName or datasetId");
2478
+ } else if (datasetId_ !== void 0 && datasetName !== void 0) {
2479
+ throw new Error("Must provide either datasetName or datasetId, not both");
2480
+ } else if (datasetId_ === void 0) {
2481
+ const dataset = await this.readDataset({ datasetName });
2482
+ datasetId_ = dataset.id;
2483
+ }
2484
+ const createdAt_ = createdAt || /* @__PURE__ */ new Date();
2485
+ const data = {
2486
+ dataset_id: datasetId_,
2487
+ inputs,
2488
+ outputs,
2489
+ created_at: createdAt_ == null ? void 0 : createdAt_.toISOString(),
2490
+ id: exampleId,
2491
+ metadata,
2492
+ split
2493
+ };
2494
+ const response = await this.caller.call(fetch, `${this.apiUrl}/examples`, {
2495
+ method: "POST",
2496
+ headers: { ...this.headers, "Content-Type": "application/json" },
2497
+ body: JSON.stringify(data),
2498
+ signal: AbortSignal.timeout(this.timeout_ms),
2499
+ ...this.fetchOptions
2500
+ });
2501
+ if (!response.ok) {
2502
+ throw new Error(`Failed to create example: ${response.status} ${response.statusText}`);
2503
+ }
2504
+ const result = await response.json();
2505
+ return result;
2506
+ }
2507
+ async createExamples(props) {
2508
+ const { inputs, outputs, metadata, sourceRunIds, exampleIds, datasetId, datasetName } = props;
2509
+ let datasetId_ = datasetId;
2510
+ if (datasetId_ === void 0 && datasetName === void 0) {
2511
+ throw new Error("Must provide either datasetName or datasetId");
2512
+ } else if (datasetId_ !== void 0 && datasetName !== void 0) {
2513
+ throw new Error("Must provide either datasetName or datasetId, not both");
2514
+ } else if (datasetId_ === void 0) {
2515
+ const dataset = await this.readDataset({ datasetName });
2516
+ datasetId_ = dataset.id;
2517
+ }
2518
+ const formattedExamples = inputs.map((input, idx) => {
2519
+ return {
2520
+ dataset_id: datasetId_,
2521
+ inputs: input,
2522
+ outputs: outputs ? outputs[idx] : void 0,
2523
+ metadata: metadata ? metadata[idx] : void 0,
2524
+ split: props.splits ? props.splits[idx] : void 0,
2525
+ id: exampleIds ? exampleIds[idx] : void 0,
2526
+ source_run_id: sourceRunIds ? sourceRunIds[idx] : void 0
2527
+ };
2528
+ });
2529
+ const response = await this.caller.call(fetch, `${this.apiUrl}/examples/bulk`, {
2530
+ method: "POST",
2531
+ headers: { ...this.headers, "Content-Type": "application/json" },
2532
+ body: JSON.stringify(formattedExamples),
2533
+ signal: AbortSignal.timeout(this.timeout_ms),
2534
+ ...this.fetchOptions
2535
+ });
2536
+ if (!response.ok) {
2537
+ throw new Error(`Failed to create examples: ${response.status} ${response.statusText}`);
2538
+ }
2539
+ const result = await response.json();
2540
+ return result;
2541
+ }
2542
+ async createLLMExample(input, generation, options) {
2543
+ return this.createExample({ input }, { output: generation }, options);
2544
+ }
2545
+ async createChatExample(input, generations, options) {
2546
+ const finalInput = input.map((message) => {
2547
+ if (isLangChainMessage(message)) {
2548
+ return convertLangChainMessageToExample(message);
2549
+ }
2550
+ return message;
2551
+ });
2552
+ const finalOutput = isLangChainMessage(generations) ? convertLangChainMessageToExample(generations) : generations;
2553
+ return this.createExample({ input: finalInput }, { output: finalOutput }, options);
2554
+ }
2555
+ async readExample(exampleId) {
2556
+ assertUuid(exampleId);
2557
+ const path = `/examples/${exampleId}`;
2558
+ return await this._get(path);
2559
+ }
2560
+ async *listExamples({ datasetId, datasetName, exampleIds, asOf, splits, inlineS3Urls, metadata, limit, offset, filter } = {}) {
2561
+ let datasetId_;
2562
+ if (datasetId !== void 0 && datasetName !== void 0) {
2563
+ throw new Error("Must provide either datasetName or datasetId, not both");
2564
+ } else if (datasetId !== void 0) {
2565
+ datasetId_ = datasetId;
2566
+ } else if (datasetName !== void 0) {
2567
+ const dataset = await this.readDataset({ datasetName });
2568
+ datasetId_ = dataset.id;
2569
+ } else {
2570
+ throw new Error("Must provide a datasetName or datasetId");
2571
+ }
2572
+ const params = new URLSearchParams({ dataset: datasetId_ });
2573
+ const dataset_version = asOf ? typeof asOf === "string" ? asOf : asOf == null ? void 0 : asOf.toISOString() : void 0;
2574
+ if (dataset_version) {
2575
+ params.append("as_of", dataset_version);
2576
+ }
2577
+ const inlineS3Urls_ = inlineS3Urls != null ? inlineS3Urls : true;
2578
+ params.append("inline_s3_urls", inlineS3Urls_.toString());
2579
+ if (exampleIds !== void 0) {
2580
+ for (const id_ of exampleIds) {
2581
+ params.append("id", id_);
2582
+ }
2583
+ }
2584
+ if (splits !== void 0) {
2585
+ for (const split of splits) {
2586
+ params.append("splits", split);
2587
+ }
2588
+ }
2589
+ if (metadata !== void 0) {
2590
+ const serializedMetadata = JSON.stringify(metadata);
2591
+ params.append("metadata", serializedMetadata);
2592
+ }
2593
+ if (limit !== void 0) {
2594
+ params.append("limit", limit.toString());
2595
+ }
2596
+ if (offset !== void 0) {
2597
+ params.append("offset", offset.toString());
2598
+ }
2599
+ if (filter !== void 0) {
2600
+ params.append("filter", filter);
2601
+ }
2602
+ let i = 0;
2603
+ for await (const examples of this._getPaginated("/examples", params)) {
2604
+ for (const example of examples) {
2605
+ yield example;
2606
+ i++;
2607
+ }
2608
+ if (limit !== void 0 && i >= limit) {
2609
+ break;
2610
+ }
2611
+ }
2612
+ }
2613
+ async deleteExample(exampleId) {
2614
+ assertUuid(exampleId);
2615
+ const path = `/examples/${exampleId}`;
2616
+ const response = await this.caller.call(fetch, this.apiUrl + path, {
2617
+ method: "DELETE",
2618
+ headers: this.headers,
2619
+ signal: AbortSignal.timeout(this.timeout_ms),
2620
+ ...this.fetchOptions
2621
+ });
2622
+ if (!response.ok) {
2623
+ throw new Error(`Failed to delete ${path}: ${response.status} ${response.statusText}`);
2624
+ }
2625
+ await response.json();
2626
+ }
2627
+ async updateExample(exampleId, update) {
2628
+ assertUuid(exampleId);
2629
+ const response = await this.caller.call(fetch, `${this.apiUrl}/examples/${exampleId}`, {
2630
+ method: "PATCH",
2631
+ headers: { ...this.headers, "Content-Type": "application/json" },
2632
+ body: JSON.stringify(update),
2633
+ signal: AbortSignal.timeout(this.timeout_ms),
2634
+ ...this.fetchOptions
2635
+ });
2636
+ if (!response.ok) {
2637
+ throw new Error(`Failed to update example ${exampleId}: ${response.status} ${response.statusText}`);
2638
+ }
2639
+ const result = await response.json();
2640
+ return result;
2641
+ }
2642
+ /**
2643
+ * @deprecated This method is deprecated and will be removed in future LangSmith versions, use `evaluate` from `langsmith/evaluation` instead.
2644
+ */
2645
+ async evaluateRun(run, evaluator, { sourceInfo, loadChildRuns, referenceExample } = { loadChildRuns: false }) {
2646
+ warnOnce("This method is deprecated and will be removed in future LangSmith versions, use `evaluate` from `langsmith/evaluation` instead.");
2647
+ let run_;
2648
+ if (typeof run === "string") {
2649
+ run_ = await this.readRun(run, { loadChildRuns });
2650
+ } else if (typeof run === "object" && "id" in run) {
2651
+ run_ = run;
2652
+ } else {
2653
+ throw new Error(`Invalid run type: ${typeof run}`);
2654
+ }
2655
+ if (run_.reference_example_id !== null && run_.reference_example_id !== void 0) {
2656
+ referenceExample = await this.readExample(run_.reference_example_id);
2657
+ }
2658
+ const feedbackResult = await evaluator.evaluateRun(run_, referenceExample);
2659
+ const [_, feedbacks] = await this._logEvaluationFeedback(feedbackResult, run_, sourceInfo);
2660
+ return feedbacks[0];
2661
+ }
2662
+ async createFeedback(runId, key, { score, value, correction, comment, sourceInfo, feedbackSourceType = "api", sourceRunId, feedbackId, feedbackConfig, projectId, comparativeExperimentId }) {
2663
+ var _a;
2664
+ if (!runId && !projectId) {
2665
+ throw new Error("One of runId or projectId must be provided");
2666
+ }
2667
+ if (runId && projectId) {
2668
+ throw new Error("Only one of runId or projectId can be provided");
2669
+ }
2670
+ const feedback_source = {
2671
+ type: feedbackSourceType != null ? feedbackSourceType : "api",
2672
+ metadata: sourceInfo != null ? sourceInfo : {}
2673
+ };
2674
+ if (sourceRunId !== void 0 && (feedback_source == null ? void 0 : feedback_source.metadata) !== void 0 && !feedback_source.metadata["__run"]) {
2675
+ feedback_source.metadata["__run"] = { run_id: sourceRunId };
2676
+ }
2677
+ if ((feedback_source == null ? void 0 : feedback_source.metadata) !== void 0 && ((_a = feedback_source.metadata["__run"]) == null ? void 0 : _a.run_id) !== void 0) {
2678
+ assertUuid(feedback_source.metadata["__run"].run_id);
2679
+ }
2680
+ const feedback = {
2681
+ id: feedbackId != null ? feedbackId : v4_default(),
2682
+ run_id: runId,
2683
+ key,
2684
+ score,
2685
+ value,
2686
+ correction,
2687
+ comment,
2688
+ feedback_source,
2689
+ comparative_experiment_id: comparativeExperimentId,
2690
+ feedbackConfig,
2691
+ session_id: projectId
2692
+ };
2693
+ const url = `${this.apiUrl}/feedback`;
2694
+ const response = await this.caller.call(fetch, url, {
2695
+ method: "POST",
2696
+ headers: { ...this.headers, "Content-Type": "application/json" },
2697
+ body: JSON.stringify(feedback),
2698
+ signal: AbortSignal.timeout(this.timeout_ms),
2699
+ ...this.fetchOptions
2700
+ });
2701
+ await raiseForStatus(response, "create feedback");
2702
+ return feedback;
2703
+ }
2704
+ async updateFeedback(feedbackId, { score, value, correction, comment }) {
2705
+ const feedbackUpdate = {};
2706
+ if (score !== void 0 && score !== null) {
2707
+ feedbackUpdate["score"] = score;
2708
+ }
2709
+ if (value !== void 0 && value !== null) {
2710
+ feedbackUpdate["value"] = value;
2711
+ }
2712
+ if (correction !== void 0 && correction !== null) {
2713
+ feedbackUpdate["correction"] = correction;
2714
+ }
2715
+ if (comment !== void 0 && comment !== null) {
2716
+ feedbackUpdate["comment"] = comment;
2717
+ }
2718
+ assertUuid(feedbackId);
2719
+ const response = await this.caller.call(fetch, `${this.apiUrl}/feedback/${feedbackId}`, {
2720
+ method: "PATCH",
2721
+ headers: { ...this.headers, "Content-Type": "application/json" },
2722
+ body: JSON.stringify(feedbackUpdate),
2723
+ signal: AbortSignal.timeout(this.timeout_ms),
2724
+ ...this.fetchOptions
2725
+ });
2726
+ await raiseForStatus(response, "update feedback");
2727
+ }
2728
+ async readFeedback(feedbackId) {
2729
+ assertUuid(feedbackId);
2730
+ const path = `/feedback/${feedbackId}`;
2731
+ const response = await this._get(path);
2732
+ return response;
2733
+ }
2734
+ async deleteFeedback(feedbackId) {
2735
+ assertUuid(feedbackId);
2736
+ const path = `/feedback/${feedbackId}`;
2737
+ const response = await this.caller.call(fetch, this.apiUrl + path, {
2738
+ method: "DELETE",
2739
+ headers: this.headers,
2740
+ signal: AbortSignal.timeout(this.timeout_ms),
2741
+ ...this.fetchOptions
2742
+ });
2743
+ if (!response.ok) {
2744
+ throw new Error(`Failed to delete ${path}: ${response.status} ${response.statusText}`);
2745
+ }
2746
+ await response.json();
2747
+ }
2748
+ async *listFeedback({ runIds, feedbackKeys, feedbackSourceTypes } = {}) {
2749
+ const queryParams = new URLSearchParams();
2750
+ if (runIds) {
2751
+ queryParams.append("run", runIds.join(","));
2752
+ }
2753
+ if (feedbackKeys) {
2754
+ for (const key of feedbackKeys) {
2755
+ queryParams.append("key", key);
2756
+ }
2757
+ }
2758
+ if (feedbackSourceTypes) {
2759
+ for (const type of feedbackSourceTypes) {
2760
+ queryParams.append("source", type);
2761
+ }
2762
+ }
2763
+ for await (const feedbacks of this._getPaginated("/feedback", queryParams)) {
2764
+ yield* feedbacks;
2765
+ }
2766
+ }
2767
+ /**
2768
+ * Creates a presigned feedback token and URL.
2769
+ *
2770
+ * The token can be used to authorize feedback metrics without
2771
+ * needing an API key. This is useful for giving browser-based
2772
+ * applications the ability to submit feedback without needing
2773
+ * to expose an API key.
2774
+ *
2775
+ * @param runId - The ID of the run.
2776
+ * @param feedbackKey - The feedback key.
2777
+ * @param options - Additional options for the token.
2778
+ * @param options.expiration - The expiration time for the token.
2779
+ *
2780
+ * @returns A promise that resolves to a FeedbackIngestToken.
2781
+ */
2782
+ async createPresignedFeedbackToken(runId, feedbackKey, { expiration, feedbackConfig } = {}) {
2783
+ const body = {
2784
+ run_id: runId,
2785
+ feedback_key: feedbackKey,
2786
+ feedback_config: feedbackConfig
2787
+ };
2788
+ if (expiration) {
2789
+ if (typeof expiration === "string") {
2790
+ body["expires_at"] = expiration;
2791
+ } else if ((expiration == null ? void 0 : expiration.hours) || (expiration == null ? void 0 : expiration.minutes) || (expiration == null ? void 0 : expiration.days)) {
2792
+ body["expires_in"] = expiration;
2793
+ }
2794
+ } else {
2795
+ body["expires_in"] = {
2796
+ hours: 3
2797
+ };
2798
+ }
2799
+ const response = await this.caller.call(fetch, `${this.apiUrl}/feedback/tokens`, {
2800
+ method: "POST",
2801
+ headers: { ...this.headers, "Content-Type": "application/json" },
2802
+ body: JSON.stringify(body),
2803
+ signal: AbortSignal.timeout(this.timeout_ms),
2804
+ ...this.fetchOptions
2805
+ });
2806
+ const result = await response.json();
2807
+ return result;
2808
+ }
2809
+ async createComparativeExperiment({ name, experimentIds, referenceDatasetId, createdAt, description, metadata, id }) {
2810
+ var _a;
2811
+ if (experimentIds.length === 0) {
2812
+ throw new Error("At least one experiment is required");
2813
+ }
2814
+ if (!referenceDatasetId) {
2815
+ referenceDatasetId = (await this.readProject({
2816
+ projectId: experimentIds[0]
2817
+ })).reference_dataset_id;
2818
+ }
2819
+ if (!referenceDatasetId == null) {
2820
+ throw new Error("A reference dataset is required");
2821
+ }
2822
+ const body = {
2823
+ id,
2824
+ name,
2825
+ experiment_ids: experimentIds,
2826
+ reference_dataset_id: referenceDatasetId,
2827
+ description,
2828
+ created_at: (_a = createdAt != null ? createdAt : /* @__PURE__ */ new Date()) == null ? void 0 : _a.toISOString(),
2829
+ extra: {}
2830
+ };
2831
+ if (metadata)
2832
+ body.extra["metadata"] = metadata;
2833
+ const response = await this.caller.call(fetch, `${this.apiUrl}/datasets/comparative`, {
2834
+ method: "POST",
2835
+ headers: { ...this.headers, "Content-Type": "application/json" },
2836
+ body: JSON.stringify(body),
2837
+ signal: AbortSignal.timeout(this.timeout_ms),
2838
+ ...this.fetchOptions
2839
+ });
2840
+ return await response.json();
2841
+ }
2842
+ /**
2843
+ * Retrieves a list of presigned feedback tokens for a given run ID.
2844
+ * @param runId The ID of the run.
2845
+ * @returns An async iterable of FeedbackIngestToken objects.
2846
+ */
2847
+ async *listPresignedFeedbackTokens(runId) {
2848
+ assertUuid(runId);
2849
+ const params = new URLSearchParams({ run_id: runId });
2850
+ for await (const tokens of this._getPaginated("/feedback/tokens", params)) {
2851
+ yield* tokens;
2852
+ }
2853
+ }
2854
+ _selectEvalResults(results) {
2855
+ let results_;
2856
+ if ("results" in results) {
2857
+ results_ = results.results;
2858
+ } else {
2859
+ results_ = [results];
2860
+ }
2861
+ return results_;
2862
+ }
2863
+ async _logEvaluationFeedback(evaluatorResponse, run, sourceInfo) {
2864
+ const evalResults = this._selectEvalResults(evaluatorResponse);
2865
+ const feedbacks = [];
2866
+ for (const res of evalResults) {
2867
+ let sourceInfo_ = sourceInfo || {};
2868
+ if (res.evaluatorInfo) {
2869
+ sourceInfo_ = { ...res.evaluatorInfo, ...sourceInfo_ };
2870
+ }
2871
+ let runId_ = null;
2872
+ if (res.targetRunId) {
2873
+ runId_ = res.targetRunId;
2874
+ } else if (run) {
2875
+ runId_ = run.id;
2876
+ }
2877
+ feedbacks.push(await this.createFeedback(runId_, res.key, {
2878
+ score: res.score,
2879
+ value: res.value,
2880
+ comment: res.comment,
2881
+ correction: res.correction,
2882
+ sourceInfo: sourceInfo_,
2883
+ sourceRunId: res.sourceRunId,
2884
+ feedbackConfig: res.feedbackConfig,
2885
+ feedbackSourceType: "model"
2886
+ }));
2887
+ }
2888
+ return [evalResults, feedbacks];
2889
+ }
2890
+ async logEvaluationFeedback(evaluatorResponse, run, sourceInfo) {
2891
+ const [results] = await this._logEvaluationFeedback(evaluatorResponse, run, sourceInfo);
2892
+ return results;
2893
+ }
2894
+ };
2895
+
2896
+ // ../../node_modules/.pnpm/langsmith@0.1.36_@langchain+core@0.3.26_openai@4.57.1_zod@3.23.8___langchain@0.3.8_@langchain_hhfvzcdxxvt4fjst2j6ox4bwsa/node_modules/langsmith/dist/index.js
2897
+ var __version__ = "0.1.36";
2898
+
2899
+ // ../../node_modules/.pnpm/langsmith@0.1.36_@langchain+core@0.3.26_openai@4.57.1_zod@3.23.8___langchain@0.3.8_@langchain_hhfvzcdxxvt4fjst2j6ox4bwsa/node_modules/langsmith/dist/utils/env.js
2900
+ var globalEnv;
2901
+ var isBrowser = () => typeof window !== "undefined" && typeof window.document !== "undefined";
2902
+ var isWebWorker = () => typeof globalThis === "object" && globalThis.constructor && globalThis.constructor.name === "DedicatedWorkerGlobalScope";
2903
+ var isJsDom = () => typeof window !== "undefined" && window.name === "nodejs" || typeof navigator !== "undefined" && (navigator.userAgent.includes("Node.js") || navigator.userAgent.includes("jsdom"));
2904
+ var isDeno = () => typeof Deno !== "undefined";
2905
+ var isNode = () => typeof process !== "undefined" && typeof process.versions !== "undefined" && typeof process.versions.node !== "undefined" && !isDeno();
2906
+ var getEnv = () => {
2907
+ if (globalEnv) {
2908
+ return globalEnv;
2909
+ }
2910
+ if (isBrowser()) {
2911
+ globalEnv = "browser";
2912
+ } else if (isNode()) {
2913
+ globalEnv = "node";
2914
+ } else if (isWebWorker()) {
2915
+ globalEnv = "webworker";
2916
+ } else if (isJsDom()) {
2917
+ globalEnv = "jsdom";
2918
+ } else if (isDeno()) {
2919
+ globalEnv = "deno";
2920
+ } else {
2921
+ globalEnv = "other";
2922
+ }
2923
+ return globalEnv;
2924
+ };
2925
+ var runtimeEnvironment;
2926
+ async function getRuntimeEnvironment() {
2927
+ if (runtimeEnvironment === void 0) {
2928
+ const env = getEnv();
2929
+ const releaseEnv = getShas();
2930
+ runtimeEnvironment = {
2931
+ library: "langsmith",
2932
+ runtime: env,
2933
+ sdk: "langsmith-js",
2934
+ sdk_version: __version__,
2935
+ ...releaseEnv
2936
+ };
2937
+ }
2938
+ return runtimeEnvironment;
2939
+ }
2940
+ function getLangChainEnvVarsMetadata() {
2941
+ const allEnvVars = getEnvironmentVariables() || {};
2942
+ const envVars = {};
2943
+ const excluded = [
2944
+ "LANGCHAIN_API_KEY",
2945
+ "LANGCHAIN_ENDPOINT",
2946
+ "LANGCHAIN_TRACING_V2",
2947
+ "LANGCHAIN_PROJECT",
2948
+ "LANGCHAIN_SESSION"
2949
+ ];
2950
+ for (const [key, value] of Object.entries(allEnvVars)) {
2951
+ if (key.startsWith("LANGCHAIN_") && typeof value === "string" && !excluded.includes(key) && !key.toLowerCase().includes("key") && !key.toLowerCase().includes("secret") && !key.toLowerCase().includes("token")) {
2952
+ if (key === "LANGCHAIN_REVISION_ID") {
2953
+ envVars["revision_id"] = value;
2954
+ } else {
2955
+ envVars[key] = value;
2956
+ }
2957
+ }
2958
+ }
2959
+ return envVars;
2960
+ }
2961
+ function getEnvironmentVariables() {
2962
+ try {
2963
+ if (typeof process !== "undefined" && process.env) {
2964
+ return Object.entries(process.env).reduce((acc, [key, value]) => {
2965
+ acc[key] = String(value);
2966
+ return acc;
2967
+ }, {});
2968
+ }
2969
+ return void 0;
2970
+ } catch (e) {
2971
+ return void 0;
2972
+ }
2973
+ }
2974
+ function getEnvironmentVariable(name) {
2975
+ var _a;
2976
+ try {
2977
+ return typeof process !== "undefined" ? (
2978
+ // eslint-disable-next-line no-process-env
2979
+ (_a = process.env) == null ? void 0 : _a[name]
2980
+ ) : void 0;
2981
+ } catch (e) {
2982
+ return void 0;
2983
+ }
2984
+ }
2985
+ var cachedCommitSHAs;
2986
+ function getShas() {
2987
+ if (cachedCommitSHAs !== void 0) {
2988
+ return cachedCommitSHAs;
2989
+ }
2990
+ const common_release_envs = [
2991
+ "VERCEL_GIT_COMMIT_SHA",
2992
+ "NEXT_PUBLIC_VERCEL_GIT_COMMIT_SHA",
2993
+ "COMMIT_REF",
2994
+ "RENDER_GIT_COMMIT",
2995
+ "CI_COMMIT_SHA",
2996
+ "CIRCLE_SHA1",
2997
+ "CF_PAGES_COMMIT_SHA",
2998
+ "REACT_APP_GIT_SHA",
2999
+ "SOURCE_VERSION",
3000
+ "GITHUB_SHA",
3001
+ "TRAVIS_COMMIT",
3002
+ "GIT_COMMIT",
3003
+ "BUILD_VCS_NUMBER",
3004
+ "bamboo_planRepository_revision",
3005
+ "Build.SourceVersion",
3006
+ "BITBUCKET_COMMIT",
3007
+ "DRONE_COMMIT_SHA",
3008
+ "SEMAPHORE_GIT_SHA",
3009
+ "BUILDKITE_COMMIT"
3010
+ ];
3011
+ const shas = {};
3012
+ for (const env of common_release_envs) {
3013
+ const envVar = getEnvironmentVariable(env);
3014
+ if (envVar !== void 0) {
3015
+ shas[env] = envVar;
3016
+ }
3017
+ }
3018
+ cachedCommitSHAs = shas;
3019
+ return shas;
3020
+ }
3021
+
3022
+ // ../../node_modules/.pnpm/langsmith@0.1.36_@langchain+core@0.3.26_openai@4.57.1_zod@3.23.8___langchain@0.3.8_@langchain_hhfvzcdxxvt4fjst2j6ox4bwsa/node_modules/langsmith/dist/env.js
3023
+ var isTracingEnabled = (tracingEnabled) => {
3024
+ if (tracingEnabled !== void 0) {
3025
+ return tracingEnabled;
3026
+ }
3027
+ const envVars = [
3028
+ "LANGSMITH_TRACING_V2",
3029
+ "LANGCHAIN_TRACING_V2",
3030
+ "LANGSMITH_TRACING",
3031
+ "LANGCHAIN_TRACING"
3032
+ ];
3033
+ return !!envVars.find((envVar) => getEnvironmentVariable(envVar) === "true");
3034
+ };
3035
+
3036
+ // ../../node_modules/.pnpm/langsmith@0.1.36_@langchain+core@0.3.26_openai@4.57.1_zod@3.23.8___langchain@0.3.8_@langchain_hhfvzcdxxvt4fjst2j6ox4bwsa/node_modules/langsmith/dist/run_trees.js
3037
+ function stripNonAlphanumeric(input) {
3038
+ return input.replace(/[-:.]/g, "");
3039
+ }
3040
+ function convertToDottedOrderFormat(epoch, runId, executionOrder = 1) {
3041
+ const paddedOrder = executionOrder.toFixed(0).slice(0, 3).padStart(3, "0");
3042
+ return stripNonAlphanumeric(`${new Date(epoch).toISOString().slice(0, -1)}${paddedOrder}Z`) + runId;
3043
+ }
3044
+ var Baggage = class _Baggage {
3045
+ constructor(metadata, tags) {
3046
+ Object.defineProperty(this, "metadata", {
3047
+ enumerable: true,
3048
+ configurable: true,
3049
+ writable: true,
3050
+ value: void 0
3051
+ });
3052
+ Object.defineProperty(this, "tags", {
3053
+ enumerable: true,
3054
+ configurable: true,
3055
+ writable: true,
3056
+ value: void 0
3057
+ });
3058
+ this.metadata = metadata;
3059
+ this.tags = tags;
3060
+ }
3061
+ static fromHeader(value) {
3062
+ const items = value.split(",");
3063
+ let metadata = {};
3064
+ let tags = [];
3065
+ for (const item of items) {
3066
+ const [key, uriValue] = item.split("=");
3067
+ const value2 = decodeURIComponent(uriValue);
3068
+ if (key === "langsmith-metadata") {
3069
+ metadata = JSON.parse(value2);
3070
+ } else if (key === "langsmith-tags") {
3071
+ tags = value2.split(",");
3072
+ }
3073
+ }
3074
+ return new _Baggage(metadata, tags);
3075
+ }
3076
+ toHeader() {
3077
+ const items = [];
3078
+ if (this.metadata && Object.keys(this.metadata).length > 0) {
3079
+ items.push(`langsmith-metadata=${encodeURIComponent(JSON.stringify(this.metadata))}`);
3080
+ }
3081
+ if (this.tags && this.tags.length > 0) {
3082
+ items.push(`langsmith-tags=${encodeURIComponent(this.tags.join(","))}`);
3083
+ }
3084
+ return items.join(",");
3085
+ }
3086
+ };
3087
+ var RunTree = class _RunTree {
3088
+ constructor(originalConfig) {
3089
+ var _a, _b, _c, _d, _e;
3090
+ Object.defineProperty(this, "id", {
3091
+ enumerable: true,
3092
+ configurable: true,
3093
+ writable: true,
3094
+ value: void 0
3095
+ });
3096
+ Object.defineProperty(this, "name", {
3097
+ enumerable: true,
3098
+ configurable: true,
3099
+ writable: true,
3100
+ value: void 0
3101
+ });
3102
+ Object.defineProperty(this, "run_type", {
3103
+ enumerable: true,
3104
+ configurable: true,
3105
+ writable: true,
3106
+ value: void 0
3107
+ });
3108
+ Object.defineProperty(this, "project_name", {
3109
+ enumerable: true,
3110
+ configurable: true,
3111
+ writable: true,
3112
+ value: void 0
3113
+ });
3114
+ Object.defineProperty(this, "parent_run", {
3115
+ enumerable: true,
3116
+ configurable: true,
3117
+ writable: true,
3118
+ value: void 0
3119
+ });
3120
+ Object.defineProperty(this, "child_runs", {
3121
+ enumerable: true,
3122
+ configurable: true,
3123
+ writable: true,
3124
+ value: void 0
3125
+ });
3126
+ Object.defineProperty(this, "start_time", {
3127
+ enumerable: true,
3128
+ configurable: true,
3129
+ writable: true,
3130
+ value: void 0
3131
+ });
3132
+ Object.defineProperty(this, "end_time", {
3133
+ enumerable: true,
3134
+ configurable: true,
3135
+ writable: true,
3136
+ value: void 0
3137
+ });
3138
+ Object.defineProperty(this, "extra", {
3139
+ enumerable: true,
3140
+ configurable: true,
3141
+ writable: true,
3142
+ value: void 0
3143
+ });
3144
+ Object.defineProperty(this, "tags", {
3145
+ enumerable: true,
3146
+ configurable: true,
3147
+ writable: true,
3148
+ value: void 0
3149
+ });
3150
+ Object.defineProperty(this, "error", {
3151
+ enumerable: true,
3152
+ configurable: true,
3153
+ writable: true,
3154
+ value: void 0
3155
+ });
3156
+ Object.defineProperty(this, "serialized", {
3157
+ enumerable: true,
3158
+ configurable: true,
3159
+ writable: true,
3160
+ value: void 0
3161
+ });
3162
+ Object.defineProperty(this, "inputs", {
3163
+ enumerable: true,
3164
+ configurable: true,
3165
+ writable: true,
3166
+ value: void 0
3167
+ });
3168
+ Object.defineProperty(this, "outputs", {
3169
+ enumerable: true,
3170
+ configurable: true,
3171
+ writable: true,
3172
+ value: void 0
3173
+ });
3174
+ Object.defineProperty(this, "reference_example_id", {
3175
+ enumerable: true,
3176
+ configurable: true,
3177
+ writable: true,
3178
+ value: void 0
3179
+ });
3180
+ Object.defineProperty(this, "client", {
3181
+ enumerable: true,
3182
+ configurable: true,
3183
+ writable: true,
3184
+ value: void 0
3185
+ });
3186
+ Object.defineProperty(this, "events", {
3187
+ enumerable: true,
3188
+ configurable: true,
3189
+ writable: true,
3190
+ value: void 0
3191
+ });
3192
+ Object.defineProperty(this, "trace_id", {
3193
+ enumerable: true,
3194
+ configurable: true,
3195
+ writable: true,
3196
+ value: void 0
3197
+ });
3198
+ Object.defineProperty(this, "dotted_order", {
3199
+ enumerable: true,
3200
+ configurable: true,
3201
+ writable: true,
3202
+ value: void 0
3203
+ });
3204
+ Object.defineProperty(this, "tracingEnabled", {
3205
+ enumerable: true,
3206
+ configurable: true,
3207
+ writable: true,
3208
+ value: void 0
3209
+ });
3210
+ Object.defineProperty(this, "execution_order", {
3211
+ enumerable: true,
3212
+ configurable: true,
3213
+ writable: true,
3214
+ value: void 0
3215
+ });
3216
+ Object.defineProperty(this, "child_execution_order", {
3217
+ enumerable: true,
3218
+ configurable: true,
3219
+ writable: true,
3220
+ value: void 0
3221
+ });
3222
+ const defaultConfig = _RunTree.getDefaultConfig();
3223
+ const { metadata, ...config } = originalConfig;
3224
+ const client = (_a = config.client) != null ? _a : new Client();
3225
+ const dedupedMetadata = {
3226
+ ...metadata,
3227
+ ...(_b = config == null ? void 0 : config.extra) == null ? void 0 : _b.metadata
3228
+ };
3229
+ config.extra = { ...config.extra, metadata: dedupedMetadata };
3230
+ Object.assign(this, { ...defaultConfig, ...config, client });
3231
+ if (!this.trace_id) {
3232
+ if (this.parent_run) {
3233
+ this.trace_id = (_c = this.parent_run.trace_id) != null ? _c : this.id;
3234
+ } else {
3235
+ this.trace_id = this.id;
3236
+ }
3237
+ }
3238
+ (_d = this.execution_order) != null ? _d : this.execution_order = 1;
3239
+ (_e = this.child_execution_order) != null ? _e : this.child_execution_order = 1;
3240
+ if (!this.dotted_order) {
3241
+ const currentDottedOrder = convertToDottedOrderFormat(this.start_time, this.id, this.execution_order);
3242
+ if (this.parent_run) {
3243
+ this.dotted_order = this.parent_run.dotted_order + "." + currentDottedOrder;
3244
+ } else {
3245
+ this.dotted_order = currentDottedOrder;
3246
+ }
3247
+ }
3248
+ }
3249
+ static getDefaultConfig() {
3250
+ var _a, _b, _c;
3251
+ return {
3252
+ id: v4_default(),
3253
+ run_type: "chain",
3254
+ project_name: (_b = (_a = getEnvironmentVariable("LANGCHAIN_PROJECT")) != null ? _a : getEnvironmentVariable("LANGCHAIN_SESSION")) != null ? _b : (
3255
+ // TODO: Deprecate
3256
+ "default"
3257
+ ),
3258
+ child_runs: [],
3259
+ api_url: (_c = getEnvironmentVariable("LANGCHAIN_ENDPOINT")) != null ? _c : "http://localhost:1984",
3260
+ api_key: getEnvironmentVariable("LANGCHAIN_API_KEY"),
3261
+ caller_options: {},
3262
+ start_time: Date.now(),
3263
+ serialized: {},
3264
+ inputs: {},
3265
+ extra: {}
3266
+ };
3267
+ }
3268
+ createChild(config) {
3269
+ const child_execution_order = this.child_execution_order + 1;
3270
+ const child = new _RunTree({
3271
+ ...config,
3272
+ parent_run: this,
3273
+ project_name: this.project_name,
3274
+ client: this.client,
3275
+ tracingEnabled: this.tracingEnabled,
3276
+ execution_order: child_execution_order,
3277
+ child_execution_order
3278
+ });
3279
+ const visited = /* @__PURE__ */ new Set();
3280
+ let current = this;
3281
+ while (current != null && !visited.has(current.id)) {
3282
+ visited.add(current.id);
3283
+ current.child_execution_order = Math.max(current.child_execution_order, child_execution_order);
3284
+ current = current.parent_run;
3285
+ }
3286
+ this.child_runs.push(child);
3287
+ return child;
3288
+ }
3289
+ async end(outputs, error, endTime = Date.now()) {
3290
+ var _a, _b, _c;
3291
+ this.outputs = (_a = this.outputs) != null ? _a : outputs;
3292
+ this.error = (_b = this.error) != null ? _b : error;
3293
+ this.end_time = (_c = this.end_time) != null ? _c : endTime;
3294
+ }
3295
+ _convertToCreate(run, runtimeEnv, excludeChildRuns = true) {
3296
+ var _a, _b;
3297
+ const runExtra = (_a = run.extra) != null ? _a : {};
3298
+ if (!runExtra.runtime) {
3299
+ runExtra.runtime = {};
3300
+ }
3301
+ if (runtimeEnv) {
3302
+ for (const [k, v] of Object.entries(runtimeEnv)) {
3303
+ if (!runExtra.runtime[k]) {
3304
+ runExtra.runtime[k] = v;
3305
+ }
3306
+ }
3307
+ }
3308
+ let child_runs;
3309
+ let parent_run_id;
3310
+ if (!excludeChildRuns) {
3311
+ child_runs = run.child_runs.map((child_run) => this._convertToCreate(child_run, runtimeEnv, excludeChildRuns));
3312
+ parent_run_id = void 0;
3313
+ } else {
3314
+ parent_run_id = (_b = run.parent_run) == null ? void 0 : _b.id;
3315
+ child_runs = [];
3316
+ }
3317
+ const persistedRun = {
3318
+ id: run.id,
3319
+ name: run.name,
3320
+ start_time: run.start_time,
3321
+ end_time: run.end_time,
3322
+ run_type: run.run_type,
3323
+ reference_example_id: run.reference_example_id,
3324
+ extra: runExtra,
3325
+ serialized: run.serialized,
3326
+ error: run.error,
3327
+ inputs: run.inputs,
3328
+ outputs: run.outputs,
3329
+ session_name: run.project_name,
3330
+ child_runs,
3331
+ parent_run_id,
3332
+ trace_id: run.trace_id,
3333
+ dotted_order: run.dotted_order,
3334
+ tags: run.tags
3335
+ };
3336
+ return persistedRun;
3337
+ }
3338
+ async postRun(excludeChildRuns = true) {
3339
+ const runtimeEnv = await getRuntimeEnvironment();
3340
+ const runCreate = await this._convertToCreate(this, runtimeEnv, true);
3341
+ await this.client.createRun(runCreate);
3342
+ if (!excludeChildRuns) {
3343
+ warnOnce("Posting with excludeChildRuns=false is deprecated and will be removed in a future version.");
3344
+ for (const childRun of this.child_runs) {
3345
+ await childRun.postRun(false);
3346
+ }
3347
+ }
3348
+ }
3349
+ async patchRun() {
3350
+ var _a;
3351
+ const runUpdate = {
3352
+ end_time: this.end_time,
3353
+ error: this.error,
3354
+ inputs: this.inputs,
3355
+ outputs: this.outputs,
3356
+ parent_run_id: (_a = this.parent_run) == null ? void 0 : _a.id,
3357
+ reference_example_id: this.reference_example_id,
3358
+ extra: this.extra,
3359
+ events: this.events,
3360
+ dotted_order: this.dotted_order,
3361
+ trace_id: this.trace_id,
3362
+ tags: this.tags
3363
+ };
3364
+ await this.client.updateRun(this.id, runUpdate);
3365
+ }
3366
+ toJSON() {
3367
+ return this._convertToCreate(this, void 0, false);
3368
+ }
3369
+ static fromRunnableConfig(parentConfig, props) {
3370
+ var _a, _b, _c, _d, _e, _f, _g;
3371
+ const callbackManager = parentConfig == null ? void 0 : parentConfig.callbacks;
3372
+ let parentRun;
3373
+ let projectName;
3374
+ let client;
3375
+ let tracingEnabled = isTracingEnabled();
3376
+ if (callbackManager) {
3377
+ const parentRunId = (_b = (_a = callbackManager == null ? void 0 : callbackManager.getParentRunId) == null ? void 0 : _a.call(callbackManager)) != null ? _b : "";
3378
+ const langChainTracer = (_c = callbackManager == null ? void 0 : callbackManager.handlers) == null ? void 0 : _c.find((handler) => (handler == null ? void 0 : handler.name) == "langchain_tracer");
3379
+ parentRun = (_d = langChainTracer == null ? void 0 : langChainTracer.getRun) == null ? void 0 : _d.call(langChainTracer, parentRunId);
3380
+ projectName = langChainTracer == null ? void 0 : langChainTracer.projectName;
3381
+ client = langChainTracer == null ? void 0 : langChainTracer.client;
3382
+ tracingEnabled = tracingEnabled || !!langChainTracer;
3383
+ }
3384
+ if (!parentRun) {
3385
+ return new _RunTree({
3386
+ ...props,
3387
+ client,
3388
+ tracingEnabled,
3389
+ project_name: projectName
3390
+ });
3391
+ }
3392
+ const parentRunTree = new _RunTree({
3393
+ name: parentRun.name,
3394
+ id: parentRun.id,
3395
+ client,
3396
+ tracingEnabled,
3397
+ project_name: projectName,
3398
+ tags: [
3399
+ ...new Set(((_e = parentRun == null ? void 0 : parentRun.tags) != null ? _e : []).concat((_f = parentConfig == null ? void 0 : parentConfig.tags) != null ? _f : []))
3400
+ ],
3401
+ extra: {
3402
+ metadata: {
3403
+ ...(_g = parentRun == null ? void 0 : parentRun.extra) == null ? void 0 : _g.metadata,
3404
+ ...parentConfig == null ? void 0 : parentConfig.metadata
3405
+ }
3406
+ }
3407
+ });
3408
+ return parentRunTree.createChild(props);
3409
+ }
3410
+ static fromDottedOrder(dottedOrder) {
3411
+ return this.fromHeaders({ "langsmith-trace": dottedOrder });
3412
+ }
3413
+ static fromHeaders(headers, inheritArgs) {
3414
+ var _a, _b, _c, _d;
3415
+ const rawHeaders = "get" in headers && typeof headers.get === "function" ? {
3416
+ "langsmith-trace": headers.get("langsmith-trace"),
3417
+ baggage: headers.get("baggage")
3418
+ } : headers;
3419
+ const headerTrace = rawHeaders["langsmith-trace"];
3420
+ if (!headerTrace || typeof headerTrace !== "string")
3421
+ return void 0;
3422
+ const parentDottedOrder = headerTrace.trim();
3423
+ const parsedDottedOrder = parentDottedOrder.split(".").map((part) => {
3424
+ const [strTime, uuid] = part.split("Z");
3425
+ return { strTime, time: Date.parse(strTime + "Z"), uuid };
3426
+ });
3427
+ const traceId = parsedDottedOrder[0].uuid;
3428
+ const config = {
3429
+ ...inheritArgs,
3430
+ name: (_a = inheritArgs == null ? void 0 : inheritArgs["name"]) != null ? _a : "parent",
3431
+ run_type: (_b = inheritArgs == null ? void 0 : inheritArgs["run_type"]) != null ? _b : "chain",
3432
+ start_time: (_c = inheritArgs == null ? void 0 : inheritArgs["start_time"]) != null ? _c : Date.now(),
3433
+ id: (_d = parsedDottedOrder.at(-1)) == null ? void 0 : _d.uuid,
3434
+ trace_id: traceId,
3435
+ dotted_order: parentDottedOrder
3436
+ };
3437
+ if (rawHeaders["baggage"] && typeof rawHeaders["baggage"] === "string") {
3438
+ const baggage = Baggage.fromHeader(rawHeaders["baggage"]);
3439
+ config.metadata = baggage.metadata;
3440
+ config.tags = baggage.tags;
3441
+ }
3442
+ return new _RunTree(config);
3443
+ }
3444
+ toHeaders(headers) {
3445
+ var _a;
3446
+ const result = {
3447
+ "langsmith-trace": this.dotted_order,
3448
+ baggage: new Baggage((_a = this.extra) == null ? void 0 : _a.metadata, this.tags).toHeader()
3449
+ };
3450
+ if (headers) {
3451
+ for (const [key, value] of Object.entries(result)) {
3452
+ headers.set(key, value);
3453
+ }
3454
+ }
3455
+ return result;
3456
+ }
3457
+ };
3458
+ function isRunTree(x) {
3459
+ return x !== void 0 && typeof x.createChild === "function" && typeof x.postRun === "function";
3460
+ }
3461
+ function containsLangChainTracerLike(x) {
3462
+ return Array.isArray(x) && x.some((callback) => {
3463
+ return typeof callback.name === "string" && callback.name === "langchain_tracer";
3464
+ });
3465
+ }
3466
+ function isRunnableConfigLike(x) {
3467
+ var _a;
3468
+ return x !== void 0 && typeof x.callbacks === "object" && // Callback manager with a langchain tracer
3469
+ (containsLangChainTracerLike((_a = x.callbacks) == null ? void 0 : _a.handlers) || // Or it's an array with a LangChainTracerLike object within it
3470
+ containsLangChainTracerLike(x.callbacks));
3471
+ }
3472
+
3473
+ // ../../node_modules/.pnpm/langsmith@0.1.36_@langchain+core@0.3.26_openai@4.57.1_zod@3.23.8___langchain@0.3.8_@langchain_hhfvzcdxxvt4fjst2j6ox4bwsa/node_modules/langsmith/dist/singletons/traceable.js
3474
+ var MockAsyncLocalStorage = class {
3475
+ getStore() {
3476
+ return void 0;
3477
+ }
3478
+ run(_, callback) {
3479
+ return callback();
3480
+ }
3481
+ };
3482
+ var AsyncLocalStorageProvider = class {
3483
+ constructor() {
3484
+ Object.defineProperty(this, "asyncLocalStorage", {
3485
+ enumerable: true,
3486
+ configurable: true,
3487
+ writable: true,
3488
+ value: new MockAsyncLocalStorage()
3489
+ });
3490
+ Object.defineProperty(this, "hasBeenInitialized", {
3491
+ enumerable: true,
3492
+ configurable: true,
3493
+ writable: true,
3494
+ value: false
3495
+ });
3496
+ }
3497
+ getInstance() {
3498
+ return this.asyncLocalStorage;
3499
+ }
3500
+ initializeGlobalInstance(instance) {
3501
+ if (!this.hasBeenInitialized) {
3502
+ this.hasBeenInitialized = true;
3503
+ this.asyncLocalStorage = instance;
3504
+ }
3505
+ }
3506
+ };
3507
+ var AsyncLocalStorageProviderSingleton = new AsyncLocalStorageProvider();
3508
+ var ROOT = Symbol.for("langsmith:traceable:root");
3509
+ function isTraceableFunction(x) {
3510
+ return typeof x === "function" && "langsmith:traceable" in x;
3511
+ }
3512
+
3513
+ // ../../node_modules/.pnpm/langsmith@0.1.36_@langchain+core@0.3.26_openai@4.57.1_zod@3.23.8___langchain@0.3.8_@langchain_hhfvzcdxxvt4fjst2j6ox4bwsa/node_modules/langsmith/dist/utils/asserts.js
3514
+ function isPromiseMethod(x) {
3515
+ if (x === "then" || x === "catch" || x === "finally") {
3516
+ return true;
3517
+ }
3518
+ return false;
3519
+ }
3520
+ function isKVMap(x) {
3521
+ if (typeof x !== "object" || x == null) {
3522
+ return false;
3523
+ }
3524
+ const prototype = Object.getPrototypeOf(x);
3525
+ return (prototype === null || prototype === Object.prototype || Object.getPrototypeOf(prototype) === null) && !(Symbol.toStringTag in x) && !(Symbol.iterator in x);
3526
+ }
3527
+ var isAsyncIterable = (x) => x != null && typeof x === "object" && // eslint-disable-next-line @typescript-eslint/no-explicit-any
3528
+ typeof x[Symbol.asyncIterator] === "function";
3529
+ var isIteratorLike = (x) => x != null && typeof x === "object" && "next" in x && typeof x.next === "function";
3530
+ var GeneratorFunction = function* () {
3531
+ }.constructor;
3532
+ var isGenerator = (x) => (
3533
+ // eslint-disable-next-line no-instanceof/no-instanceof
3534
+ x != null && typeof x === "function" && x instanceof GeneratorFunction
3535
+ );
3536
+ var isThenable = (x) => x != null && typeof x === "object" && "then" in x && typeof x.then === "function";
3537
+ var isReadableStream = (x) => x != null && typeof x === "object" && "getReader" in x && typeof x.getReader === "function";
3538
+
3539
+ // ../../node_modules/.pnpm/langsmith@0.1.36_@langchain+core@0.3.26_openai@4.57.1_zod@3.23.8___langchain@0.3.8_@langchain_hhfvzcdxxvt4fjst2j6ox4bwsa/node_modules/langsmith/dist/traceable.js
3540
+ AsyncLocalStorageProviderSingleton.initializeGlobalInstance(new (0, _async_hooks.AsyncLocalStorage)());
3541
+ var handleRunInputs = (rawInputs) => {
3542
+ const firstInput = rawInputs[0];
3543
+ if (firstInput == null) {
3544
+ return {};
3545
+ }
3546
+ if (rawInputs.length > 1) {
3547
+ return { args: rawInputs };
3548
+ }
3549
+ if (isKVMap(firstInput)) {
3550
+ return firstInput;
3551
+ }
3552
+ return { input: firstInput };
3553
+ };
3554
+ var handleRunOutputs = (rawOutputs) => {
3555
+ if (isKVMap(rawOutputs)) {
3556
+ return rawOutputs;
3557
+ }
3558
+ return { outputs: rawOutputs };
3559
+ };
3560
+ var getTracingRunTree = (runTree, inputs, getInvocationParams) => {
3561
+ var _a;
3562
+ if (!isTracingEnabled(runTree.tracingEnabled)) {
3563
+ return void 0;
3564
+ }
3565
+ runTree.inputs = handleRunInputs(inputs);
3566
+ const invocationParams = getInvocationParams == null ? void 0 : getInvocationParams(...inputs);
3567
+ if (invocationParams != null) {
3568
+ (_a = runTree.extra) != null ? _a : runTree.extra = {};
3569
+ runTree.extra.metadata = {
3570
+ ...invocationParams,
3571
+ ...runTree.extra.metadata
3572
+ };
3573
+ }
3574
+ return runTree;
3575
+ };
3576
+ var getSerializablePromise = (arg) => {
3577
+ const proxyState = { current: void 0 };
3578
+ const promiseProxy = new Proxy(arg, {
3579
+ get(target, prop, receiver) {
3580
+ if (prop === "then") {
3581
+ const boundThen = arg[prop].bind(arg);
3582
+ return (resolve, reject = (x) => {
3583
+ throw x;
3584
+ }) => {
3585
+ return boundThen((value) => {
3586
+ proxyState.current = ["resolve", value];
3587
+ return resolve(value);
3588
+ }, (error) => {
3589
+ proxyState.current = ["reject", error];
3590
+ return reject(error);
3591
+ });
3592
+ };
3593
+ }
3594
+ if (prop === "catch") {
3595
+ const boundCatch = arg[prop].bind(arg);
3596
+ return (reject) => {
3597
+ return boundCatch((error) => {
3598
+ proxyState.current = ["reject", error];
3599
+ return reject(error);
3600
+ });
3601
+ };
3602
+ }
3603
+ if (prop === "toJSON") {
3604
+ return () => {
3605
+ var _a;
3606
+ if (!proxyState.current)
3607
+ return void 0;
3608
+ const [type, value] = (_a = proxyState.current) != null ? _a : [];
3609
+ if (type === "resolve")
3610
+ return value;
3611
+ return { error: value };
3612
+ };
3613
+ }
3614
+ return Reflect.get(target, prop, receiver);
3615
+ }
3616
+ });
3617
+ return promiseProxy;
3618
+ };
3619
+ var convertSerializableArg = (arg) => {
3620
+ if (isReadableStream(arg)) {
3621
+ const proxyState = [];
3622
+ const transform = new TransformStream({
3623
+ start: () => void 0,
3624
+ transform: (chunk, controller) => {
3625
+ proxyState.push(chunk);
3626
+ controller.enqueue(chunk);
3627
+ },
3628
+ flush: () => void 0
3629
+ });
3630
+ const pipeThrough = arg.pipeThrough(transform);
3631
+ Object.assign(pipeThrough, { toJSON: () => proxyState });
3632
+ return pipeThrough;
3633
+ }
3634
+ if (isAsyncIterable(arg)) {
3635
+ const proxyState = { current: [] };
3636
+ return new Proxy(arg, {
3637
+ get(target, prop, receiver) {
3638
+ if (prop === Symbol.asyncIterator) {
3639
+ return () => {
3640
+ const boundIterator = arg[Symbol.asyncIterator].bind(arg);
3641
+ const iterator = boundIterator();
3642
+ return new Proxy(iterator, {
3643
+ get(target2, prop2, receiver2) {
3644
+ if (prop2 === "next" || prop2 === "return" || prop2 === "throw") {
3645
+ const bound = iterator.next.bind(iterator);
3646
+ return (...args) => {
3647
+ const wrapped = getSerializablePromise(bound(...args));
3648
+ proxyState.current.push(wrapped);
3649
+ return wrapped;
3650
+ };
3651
+ }
3652
+ if (prop2 === "return" || prop2 === "throw") {
3653
+ return iterator.next.bind(iterator);
3654
+ }
3655
+ return Reflect.get(target2, prop2, receiver2);
3656
+ }
3657
+ });
3658
+ };
3659
+ }
3660
+ if (prop === "toJSON") {
3661
+ return () => {
3662
+ const onlyNexts = proxyState.current;
3663
+ const serialized = onlyNexts.map((next) => next.toJSON());
3664
+ const chunks = serialized.reduce((memo, next) => {
3665
+ if (next == null ? void 0 : next.value)
3666
+ memo.push(next.value);
3667
+ return memo;
3668
+ }, []);
3669
+ return chunks;
3670
+ };
3671
+ }
3672
+ return Reflect.get(target, prop, receiver);
3673
+ }
3674
+ });
3675
+ }
3676
+ if (!Array.isArray(arg) && isIteratorLike(arg)) {
3677
+ const proxyState = [];
3678
+ return new Proxy(arg, {
3679
+ get(target, prop, receiver) {
3680
+ var _a;
3681
+ if (prop === "next" || prop === "return" || prop === "throw") {
3682
+ const bound = (_a = arg[prop]) == null ? void 0 : _a.bind(arg);
3683
+ return (...args) => {
3684
+ const next = bound == null ? void 0 : bound(...args);
3685
+ if (next != null)
3686
+ proxyState.push(next);
3687
+ return next;
3688
+ };
3689
+ }
3690
+ if (prop === "toJSON") {
3691
+ return () => {
3692
+ const chunks = proxyState.reduce((memo, next) => {
3693
+ if (next.value)
3694
+ memo.push(next.value);
3695
+ return memo;
3696
+ }, []);
3697
+ return chunks;
3698
+ };
3699
+ }
3700
+ return Reflect.get(target, prop, receiver);
3701
+ }
3702
+ });
3703
+ }
3704
+ if (isThenable(arg)) {
3705
+ return getSerializablePromise(arg);
3706
+ }
3707
+ return arg;
3708
+ };
3709
+ function traceable(wrappedFunc, config) {
3710
+ const { aggregator, argsConfigPath, ...runTreeConfig } = config != null ? config : {};
3711
+ const traceableFunc = (...args) => {
3712
+ var _a, _b, _c;
3713
+ let ensuredConfig;
3714
+ try {
3715
+ let runtimeConfig;
3716
+ if (argsConfigPath) {
3717
+ const [index, path] = argsConfigPath;
3718
+ if (index === args.length - 1 && !path) {
3719
+ runtimeConfig = args.pop();
3720
+ } else if (index <= args.length && typeof args[index] === "object" && args[index] !== null) {
3721
+ if (path) {
3722
+ const { [path]: extracted, ...rest } = args[index];
3723
+ runtimeConfig = extracted;
3724
+ args[index] = rest;
3725
+ } else {
3726
+ runtimeConfig = args[index];
3727
+ args.splice(index, 1);
3728
+ }
3729
+ }
3730
+ }
3731
+ ensuredConfig = {
3732
+ name: wrappedFunc.name || "<lambda>",
3733
+ ...runTreeConfig,
3734
+ ...runtimeConfig,
3735
+ tags: [
3736
+ .../* @__PURE__ */ new Set([
3737
+ ...(_a = runTreeConfig == null ? void 0 : runTreeConfig.tags) != null ? _a : [],
3738
+ ...(_b = runtimeConfig == null ? void 0 : runtimeConfig.tags) != null ? _b : []
3739
+ ])
3740
+ ],
3741
+ metadata: {
3742
+ ...runTreeConfig == null ? void 0 : runTreeConfig.metadata,
3743
+ ...runtimeConfig == null ? void 0 : runtimeConfig.metadata
3744
+ }
3745
+ };
3746
+ } catch (err) {
3747
+ console.warn(`Failed to extract runtime config from args for ${(_c = runTreeConfig == null ? void 0 : runTreeConfig.name) != null ? _c : wrappedFunc.name}`, err);
3748
+ ensuredConfig = {
3749
+ name: wrappedFunc.name || "<lambda>",
3750
+ ...runTreeConfig
3751
+ };
3752
+ }
3753
+ const asyncLocalStorage = AsyncLocalStorageProviderSingleton.getInstance();
3754
+ const processedArgs = args;
3755
+ for (let i = 0; i < processedArgs.length; i++) {
3756
+ processedArgs[i] = convertSerializableArg(processedArgs[i]);
3757
+ }
3758
+ const [currentRunTree, rawInputs] = (() => {
3759
+ const [firstArg, ...restArgs] = processedArgs;
3760
+ if (isRunnableConfigLike(firstArg)) {
3761
+ return [
3762
+ getTracingRunTree(RunTree.fromRunnableConfig(firstArg, ensuredConfig), restArgs, config == null ? void 0 : config.getInvocationParams),
3763
+ restArgs
3764
+ ];
3765
+ }
3766
+ if (isRunTree(firstArg) && "callbackManager" in firstArg && firstArg.callbackManager != null) {
3767
+ return [firstArg, restArgs];
3768
+ }
3769
+ if (firstArg === ROOT || isRunTree(firstArg)) {
3770
+ const currentRunTree3 = getTracingRunTree(firstArg === ROOT ? new RunTree(ensuredConfig) : firstArg.createChild(ensuredConfig), restArgs, config == null ? void 0 : config.getInvocationParams);
3771
+ return [currentRunTree3, [currentRunTree3, ...restArgs]];
3772
+ }
3773
+ const prevRunFromStore = asyncLocalStorage.getStore();
3774
+ if (prevRunFromStore) {
3775
+ return [
3776
+ getTracingRunTree(prevRunFromStore.createChild(ensuredConfig), processedArgs, config == null ? void 0 : config.getInvocationParams),
3777
+ processedArgs
3778
+ ];
3779
+ }
3780
+ const currentRunTree2 = getTracingRunTree(new RunTree(ensuredConfig), processedArgs, config == null ? void 0 : config.getInvocationParams);
3781
+ return [currentRunTree2, processedArgs];
3782
+ })();
3783
+ return asyncLocalStorage.run(currentRunTree, () => {
3784
+ const postRunPromise = currentRunTree == null ? void 0 : currentRunTree.postRun();
3785
+ async function handleChunks(chunks) {
3786
+ if (aggregator !== void 0) {
3787
+ try {
3788
+ return await aggregator(chunks);
3789
+ } catch (e) {
3790
+ console.error(`[ERROR]: LangSmith aggregation failed: `, e);
3791
+ }
3792
+ }
3793
+ return chunks;
3794
+ }
3795
+ async function* wrapAsyncGeneratorForTracing(iterable, snapshot) {
3796
+ let finished = false;
3797
+ const chunks = [];
3798
+ try {
3799
+ const iterator = iterable[Symbol.asyncIterator]();
3800
+ while (true) {
3801
+ const { value, done } = await (snapshot ? snapshot(() => iterator.next()) : iterator.next());
3802
+ if (done) {
3803
+ finished = true;
3804
+ break;
3805
+ }
3806
+ chunks.push(value);
3807
+ yield value;
3808
+ }
3809
+ } catch (e) {
3810
+ await (currentRunTree == null ? void 0 : currentRunTree.end(void 0, String(e)));
3811
+ throw e;
3812
+ } finally {
3813
+ if (!finished)
3814
+ await (currentRunTree == null ? void 0 : currentRunTree.end(void 0, "Cancelled"));
3815
+ await (currentRunTree == null ? void 0 : currentRunTree.end(handleRunOutputs(await handleChunks(chunks))));
3816
+ await handleEnd();
3817
+ }
3818
+ }
3819
+ async function handleEnd() {
3820
+ const onEnd = config == null ? void 0 : config.on_end;
3821
+ if (onEnd) {
3822
+ if (!currentRunTree) {
3823
+ console.warn("Can not call 'on_end' if currentRunTree is undefined");
3824
+ } else {
3825
+ onEnd(currentRunTree);
3826
+ }
3827
+ }
3828
+ await postRunPromise;
3829
+ await (currentRunTree == null ? void 0 : currentRunTree.patchRun());
3830
+ }
3831
+ function gatherAll(iterator) {
3832
+ const chunks = [];
3833
+ while (true) {
3834
+ const next = iterator.next();
3835
+ chunks.push(next);
3836
+ if (next.done)
3837
+ break;
3838
+ }
3839
+ return chunks;
3840
+ }
3841
+ let returnValue;
3842
+ try {
3843
+ returnValue = wrappedFunc(...rawInputs);
3844
+ } catch (err) {
3845
+ returnValue = Promise.reject(err);
3846
+ }
3847
+ if (isAsyncIterable(returnValue)) {
3848
+ const snapshot = _async_hooks.AsyncLocalStorage.snapshot();
3849
+ return wrapAsyncGeneratorForTracing(returnValue, snapshot);
3850
+ }
3851
+ const tracedPromise = new Promise((resolve, reject) => {
3852
+ Promise.resolve(returnValue).then(async (rawOutput) => {
3853
+ if (isAsyncIterable(rawOutput)) {
3854
+ const snapshot = _async_hooks.AsyncLocalStorage.snapshot();
3855
+ return resolve(wrapAsyncGeneratorForTracing(rawOutput, snapshot));
3856
+ }
3857
+ if (isGenerator(wrappedFunc) && isIteratorLike(rawOutput)) {
3858
+ const chunks = gatherAll(rawOutput);
3859
+ await (currentRunTree == null ? void 0 : currentRunTree.end(handleRunOutputs(await handleChunks(chunks.reduce((memo, { value, done }) => {
3860
+ if (!done || typeof value !== "undefined") {
3861
+ memo.push(value);
3862
+ }
3863
+ return memo;
3864
+ }, [])))));
3865
+ await handleEnd();
3866
+ return function* () {
3867
+ for (const ret of chunks) {
3868
+ if (ret.done)
3869
+ return ret.value;
3870
+ yield ret.value;
3871
+ }
3872
+ }();
3873
+ }
3874
+ try {
3875
+ await (currentRunTree == null ? void 0 : currentRunTree.end(handleRunOutputs(rawOutput)));
3876
+ await handleEnd();
3877
+ } finally {
3878
+ return rawOutput;
3879
+ }
3880
+ }, async (error) => {
3881
+ await (currentRunTree == null ? void 0 : currentRunTree.end(void 0, String(error)));
3882
+ await handleEnd();
3883
+ throw error;
3884
+ }).then(resolve, reject);
3885
+ });
3886
+ if (typeof returnValue !== "object" || returnValue === null) {
3887
+ return tracedPromise;
3888
+ }
3889
+ return new Proxy(returnValue, {
3890
+ get(target, prop, receiver) {
3891
+ if (isPromiseMethod(prop)) {
3892
+ return tracedPromise[prop].bind(tracedPromise);
3893
+ }
3894
+ return Reflect.get(target, prop, receiver);
3895
+ }
3896
+ });
3897
+ });
3898
+ };
3899
+ Object.defineProperty(traceableFunc, "langsmith:traceable", {
3900
+ value: runTreeConfig
3901
+ });
3902
+ return traceableFunc;
3903
+ }
3904
+
3905
+ // ../../node_modules/.pnpm/langsmith@0.1.36_@langchain+core@0.3.26_openai@4.57.1_zod@3.23.8___langchain@0.3.8_@langchain_hhfvzcdxxvt4fjst2j6ox4bwsa/node_modules/langsmith/dist/wrappers/openai.js
3906
+ function _combineChatCompletionChoices(choices) {
3907
+ var _a, _b;
3908
+ const reversedChoices = choices.slice().reverse();
3909
+ const message = {
3910
+ role: "assistant",
3911
+ content: ""
3912
+ };
3913
+ for (const c of reversedChoices) {
3914
+ if (c.delta.role) {
3915
+ message["role"] = c.delta.role;
3916
+ break;
3917
+ }
3918
+ }
3919
+ const toolCalls = {};
3920
+ for (const c of choices) {
3921
+ if (c.delta.content) {
3922
+ message.content = message.content.concat(c.delta.content);
3923
+ }
3924
+ if (c.delta.function_call) {
3925
+ if (!message.function_call) {
3926
+ message.function_call = { name: "", arguments: "" };
3927
+ }
3928
+ if (c.delta.function_call.name) {
3929
+ message.function_call.name += c.delta.function_call.name;
3930
+ }
3931
+ if (c.delta.function_call.arguments) {
3932
+ message.function_call.arguments += c.delta.function_call.arguments;
3933
+ }
3934
+ }
3935
+ if (c.delta.tool_calls) {
3936
+ for (const tool_call of c.delta.tool_calls) {
3937
+ if (!toolCalls[c.index]) {
3938
+ toolCalls[c.index] = [];
3939
+ }
3940
+ toolCalls[c.index].push(tool_call);
3941
+ }
3942
+ }
3943
+ }
3944
+ if (Object.keys(toolCalls).length > 0) {
3945
+ message.tool_calls = [...Array(Object.keys(toolCalls).length)];
3946
+ for (const [index, toolCallChunks] of Object.entries(toolCalls)) {
3947
+ const idx = parseInt(index);
3948
+ message.tool_calls[idx] = {
3949
+ index: idx,
3950
+ id: ((_a = toolCallChunks.find((c) => c.id)) == null ? void 0 : _a.id) || null,
3951
+ type: ((_b = toolCallChunks.find((c) => c.type)) == null ? void 0 : _b.type) || null
3952
+ };
3953
+ for (const chunk of toolCallChunks) {
3954
+ if (chunk.function) {
3955
+ if (!message.tool_calls[idx].function) {
3956
+ message.tool_calls[idx].function = {
3957
+ name: "",
3958
+ arguments: ""
3959
+ };
3960
+ }
3961
+ if (chunk.function.name) {
3962
+ message.tool_calls[idx].function.name += chunk.function.name;
3963
+ }
3964
+ if (chunk.function.arguments) {
3965
+ message.tool_calls[idx].function.arguments += chunk.function.arguments;
3966
+ }
3967
+ }
3968
+ }
3969
+ }
3970
+ }
3971
+ return {
3972
+ index: choices[0].index,
3973
+ finish_reason: reversedChoices.find((c) => c.finish_reason) || null,
3974
+ message
3975
+ };
3976
+ }
3977
+ var chatAggregator = (chunks) => {
3978
+ if (!chunks || chunks.length === 0) {
3979
+ return { choices: [{ message: { role: "assistant", content: "" } }] };
3980
+ }
3981
+ const choicesByIndex = {};
3982
+ for (const chunk of chunks) {
3983
+ for (const choice of chunk.choices) {
3984
+ if (choicesByIndex[choice.index] === void 0) {
3985
+ choicesByIndex[choice.index] = [];
3986
+ }
3987
+ choicesByIndex[choice.index].push(choice);
3988
+ }
3989
+ }
3990
+ const aggregatedOutput = chunks[chunks.length - 1];
3991
+ aggregatedOutput.choices = Object.values(choicesByIndex).map((choices) => _combineChatCompletionChoices(choices));
3992
+ return aggregatedOutput;
3993
+ };
3994
+ var textAggregator = (allChunks) => {
3995
+ if (allChunks.length === 0) {
3996
+ return { choices: [{ text: "" }] };
3997
+ }
3998
+ const allContent = [];
3999
+ for (const chunk of allChunks) {
4000
+ const content2 = chunk.choices[0].text;
4001
+ if (content2 != null) {
4002
+ allContent.push(content2);
4003
+ }
4004
+ }
4005
+ const content = allContent.join("");
4006
+ const aggregatedOutput = allChunks[allChunks.length - 1];
4007
+ aggregatedOutput.choices = [
4008
+ { ...aggregatedOutput.choices[0], text: content }
4009
+ ];
4010
+ return aggregatedOutput;
4011
+ };
4012
+ var wrapOpenAI = (openai, options) => {
4013
+ if (isTraceableFunction(openai.chat.completions.create) || isTraceableFunction(openai.completions.create)) {
4014
+ throw new Error("This instance of OpenAI client has been already wrapped once.");
4015
+ }
4016
+ openai.chat.completions.create = traceable(openai.chat.completions.create.bind(openai.chat.completions), {
4017
+ name: "ChatOpenAI",
4018
+ run_type: "llm",
4019
+ aggregator: chatAggregator,
4020
+ argsConfigPath: [1, "langsmithExtra"],
4021
+ getInvocationParams: (payload) => {
4022
+ var _a, _b, _c;
4023
+ if (typeof payload !== "object" || payload == null)
4024
+ return void 0;
4025
+ const params = payload;
4026
+ const ls_stop = (_a = typeof params.stop === "string" ? [params.stop] : params.stop) != null ? _a : void 0;
4027
+ return {
4028
+ ls_provider: "openai",
4029
+ ls_model_type: "chat",
4030
+ ls_model_name: params.model,
4031
+ ls_max_tokens: (_b = params.max_tokens) != null ? _b : void 0,
4032
+ ls_temperature: (_c = params.temperature) != null ? _c : void 0,
4033
+ ls_stop
4034
+ };
4035
+ },
4036
+ ...options
4037
+ });
4038
+ openai.completions.create = traceable(openai.completions.create.bind(openai.completions), {
4039
+ name: "OpenAI",
4040
+ run_type: "llm",
4041
+ aggregator: textAggregator,
4042
+ argsConfigPath: [1, "langsmithExtra"],
4043
+ getInvocationParams: (payload) => {
4044
+ var _a, _b, _c;
4045
+ if (typeof payload !== "object" || payload == null)
4046
+ return void 0;
4047
+ const params = payload;
4048
+ const ls_stop = (_a = typeof params.stop === "string" ? [params.stop] : params.stop) != null ? _a : void 0;
4049
+ return {
4050
+ ls_provider: "openai",
4051
+ ls_model_type: "text",
4052
+ ls_model_name: params.model,
4053
+ ls_max_tokens: (_b = params.max_tokens) != null ? _b : void 0,
4054
+ ls_temperature: (_c = params.temperature) != null ? _c : void 0,
4055
+ ls_stop
4056
+ };
4057
+ },
4058
+ ...options
4059
+ });
4060
+ return openai;
4061
+ };
4062
+ var _wrapClient = (sdk, runName, options) => {
4063
+ return new Proxy(sdk, {
4064
+ get(target, propKey, receiver) {
4065
+ const originalValue = target[propKey];
4066
+ if (typeof originalValue === "function") {
4067
+ return traceable(originalValue.bind(target), Object.assign({ name: [runName, propKey.toString()].join("."), run_type: "llm" }, options));
4068
+ } else if (originalValue != null && !Array.isArray(originalValue) && // eslint-disable-next-line no-instanceof/no-instanceof
4069
+ !(originalValue instanceof Date) && typeof originalValue === "object") {
4070
+ return _wrapClient(originalValue, [runName, propKey.toString()].join("."), options);
4071
+ } else {
4072
+ return Reflect.get(target, propKey, receiver);
4073
+ }
4074
+ }
4075
+ });
4076
+ };
4077
+ var wrapSDK = (sdk, options) => {
4078
+ var _a, _b;
4079
+ return _wrapClient(sdk, (_b = options == null ? void 0 : options.runName) != null ? _b : (_a = sdk.constructor) == null ? void 0 : _a.name, {
4080
+ client: options == null ? void 0 : options.client
4081
+ });
4082
+ };
4083
+
4084
+
4085
+
4086
+ exports.wrapOpenAI = wrapOpenAI; exports.wrapSDK = wrapSDK;