braintrust 1.0.2 → 1.0.3
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.
- package/dev/dist/index.d.mts +30 -25
- package/dev/dist/index.d.ts +30 -25
- package/dev/dist/index.js +336 -325
- package/dev/dist/index.mjs +259 -248
- package/dist/browser.d.mts +2313 -322
- package/dist/browser.d.ts +2313 -322
- package/dist/browser.js +2819 -198
- package/dist/browser.mjs +2681 -60
- package/dist/cli.js +358 -160
- package/dist/index.d.mts +254 -284
- package/dist/index.d.ts +254 -284
- package/dist/index.js +484 -470
- package/dist/index.mjs +335 -321
- package/package.json +6 -2
package/dist/browser.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { newObj[key] = obj[key]; } } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; } var _class; var _class2; var _class3; var _class4; var _class5; var _class6; var _class7; var _class8; var _class9; var _class10; var _class11; var _class12; var _class13; var _class14; var _class15;var __defProp = Object.defineProperty;
|
|
1
|
+
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { newObj[key] = obj[key]; } } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; } var _class; var _class2; var _class3; var _class4; var _class5; var _class6; var _class7; var _class8; var _class9; var _class10; var _class11; var _class12; var _class13; var _class14; var _class15; var _class16; var _class17; var _class18; var _class19;var __defProp = Object.defineProperty;
|
|
2
2
|
var __export = (target, all) => {
|
|
3
3
|
for (var name in all)
|
|
4
4
|
__defProp(target, name, { get: all[name], enumerable: true });
|
|
@@ -24,7 +24,9 @@ var iso = {
|
|
|
24
24
|
getCallerLocation: () => void 0,
|
|
25
25
|
newAsyncLocalStorage: () => new DefaultAsyncLocalStorage(),
|
|
26
26
|
processOn: (_0, _1) => {
|
|
27
|
-
}
|
|
27
|
+
},
|
|
28
|
+
basename: (filepath) => filepath.split(/[\\/]/).pop() || filepath,
|
|
29
|
+
writeln: (text) => console.log(text)
|
|
28
30
|
};
|
|
29
31
|
var isomorph_default = iso;
|
|
30
32
|
|
|
@@ -1054,6 +1056,93 @@ function _urljoin(...parts) {
|
|
|
1054
1056
|
(x, i) => x.replace(/^\//, "").replace(i < parts.length - 1 ? /\/$/ : "", "")
|
|
1055
1057
|
).filter((x) => x.trim() !== "").join("/");
|
|
1056
1058
|
}
|
|
1059
|
+
function slugify(text, options) {
|
|
1060
|
+
if (typeof text !== "string") {
|
|
1061
|
+
throw new Error("slugify: string argument expected");
|
|
1062
|
+
}
|
|
1063
|
+
const charMap = {
|
|
1064
|
+
// Currency and symbols
|
|
1065
|
+
$: "dollar",
|
|
1066
|
+
"%": "percent",
|
|
1067
|
+
"&": "and",
|
|
1068
|
+
// Latin characters
|
|
1069
|
+
\u00C0: "A",
|
|
1070
|
+
\u00C1: "A",
|
|
1071
|
+
\u00C2: "A",
|
|
1072
|
+
\u00C3: "A",
|
|
1073
|
+
\u00C4: "A",
|
|
1074
|
+
\u00C5: "A",
|
|
1075
|
+
\u00C6: "AE",
|
|
1076
|
+
\u00C7: "C",
|
|
1077
|
+
\u00C8: "E",
|
|
1078
|
+
\u00C9: "E",
|
|
1079
|
+
\u00CA: "E",
|
|
1080
|
+
\u00CB: "E",
|
|
1081
|
+
\u00CC: "I",
|
|
1082
|
+
\u00CD: "I",
|
|
1083
|
+
\u00CE: "I",
|
|
1084
|
+
\u00CF: "I",
|
|
1085
|
+
\u00D1: "N",
|
|
1086
|
+
\u00D2: "O",
|
|
1087
|
+
\u00D3: "O",
|
|
1088
|
+
\u00D4: "O",
|
|
1089
|
+
\u00D5: "O",
|
|
1090
|
+
\u00D6: "O",
|
|
1091
|
+
\u00D8: "O",
|
|
1092
|
+
\u00D9: "U",
|
|
1093
|
+
\u00DA: "U",
|
|
1094
|
+
\u00DB: "U",
|
|
1095
|
+
\u00DC: "U",
|
|
1096
|
+
\u00DD: "Y",
|
|
1097
|
+
\u00E0: "a",
|
|
1098
|
+
\u00E1: "a",
|
|
1099
|
+
\u00E2: "a",
|
|
1100
|
+
\u00E3: "a",
|
|
1101
|
+
\u00E4: "a",
|
|
1102
|
+
\u00E5: "a",
|
|
1103
|
+
\u00E6: "ae",
|
|
1104
|
+
\u00E7: "c",
|
|
1105
|
+
\u00E8: "e",
|
|
1106
|
+
\u00E9: "e",
|
|
1107
|
+
\u00EA: "e",
|
|
1108
|
+
\u00EB: "e",
|
|
1109
|
+
\u00EC: "i",
|
|
1110
|
+
\u00ED: "i",
|
|
1111
|
+
\u00EE: "i",
|
|
1112
|
+
\u00EF: "i",
|
|
1113
|
+
\u00F1: "n",
|
|
1114
|
+
\u00F2: "o",
|
|
1115
|
+
\u00F3: "o",
|
|
1116
|
+
\u00F4: "o",
|
|
1117
|
+
\u00F5: "o",
|
|
1118
|
+
\u00F6: "o",
|
|
1119
|
+
\u00F8: "o",
|
|
1120
|
+
\u00F9: "u",
|
|
1121
|
+
\u00FA: "u",
|
|
1122
|
+
\u00FB: "u",
|
|
1123
|
+
\u00FC: "u",
|
|
1124
|
+
\u00FD: "y",
|
|
1125
|
+
\u00FF: "y"
|
|
1126
|
+
};
|
|
1127
|
+
const replacement = "-";
|
|
1128
|
+
const trim = _optionalChain([options, 'optionalAccess', _12 => _12.trim]) !== false;
|
|
1129
|
+
let slug = text.normalize().split("").reduce((result, ch) => {
|
|
1130
|
+
const mapped = charMap[ch] || ch;
|
|
1131
|
+
const appendChar = mapped === replacement ? " " : mapped;
|
|
1132
|
+
return result + appendChar.replace(/[^\w\s$*_+~.()'"!\-:@]+/g, "");
|
|
1133
|
+
}, "");
|
|
1134
|
+
if (_optionalChain([options, 'optionalAccess', _13 => _13.strict])) {
|
|
1135
|
+
slug = slug.replace(/[^A-Za-z0-9\s]/g, "");
|
|
1136
|
+
}
|
|
1137
|
+
if (trim) {
|
|
1138
|
+
slug = slug.trim();
|
|
1139
|
+
}
|
|
1140
|
+
slug = slug.replace(/\s+/g, replacement);
|
|
1141
|
+
if (_optionalChain([options, 'optionalAccess', _14 => _14.lower])) {
|
|
1142
|
+
slug = slug.toLowerCase();
|
|
1143
|
+
}
|
|
1144
|
+
return slug;
|
|
1145
|
+
}
|
|
1057
1146
|
|
|
1058
1147
|
// util/span_identifier_v4.ts
|
|
1059
1148
|
|
|
@@ -1294,6 +1383,15 @@ function prettifyXact(valueString) {
|
|
|
1294
1383
|
const encoded = modularMultiply(value, COPRIME);
|
|
1295
1384
|
return encoded.toString(16).padStart(16, "0");
|
|
1296
1385
|
}
|
|
1386
|
+
function loadPrettyXact(encodedHex) {
|
|
1387
|
+
if (encodedHex.length !== 16) {
|
|
1388
|
+
return encodedHex;
|
|
1389
|
+
}
|
|
1390
|
+
const value = BigInt(`0x${encodedHex}`);
|
|
1391
|
+
const multipliedInverse = modularMultiply(value, COPRIME_INVERSE);
|
|
1392
|
+
const withTopBits = TOP_BITS | multipliedInverse;
|
|
1393
|
+
return withTopBits.toString();
|
|
1394
|
+
}
|
|
1297
1395
|
|
|
1298
1396
|
// util/zod_util.ts
|
|
1299
1397
|
|
|
@@ -2709,10 +2807,10 @@ var BraintrustStream = class _BraintrustStream {
|
|
|
2709
2807
|
if (this.memoizedFinalValue) {
|
|
2710
2808
|
return this.memoizedFinalValue;
|
|
2711
2809
|
}
|
|
2712
|
-
this.memoizedFinalValue = new Promise((resolve,
|
|
2713
|
-
this.stream.pipeThrough(createFinalValuePassThroughStream(resolve,
|
|
2810
|
+
this.memoizedFinalValue = new Promise((resolve, reject2) => {
|
|
2811
|
+
this.stream.pipeThrough(createFinalValuePassThroughStream(resolve, reject2), {
|
|
2714
2812
|
signal: this.signal
|
|
2715
|
-
}).pipeTo(devNullWritableStream(), { signal: this.signal }).catch(
|
|
2813
|
+
}).pipeTo(devNullWritableStream(), { signal: this.signal }).catch(reject2);
|
|
2716
2814
|
});
|
|
2717
2815
|
return this.memoizedFinalValue;
|
|
2718
2816
|
}
|
|
@@ -3145,7 +3243,7 @@ function runCatchFinally(f, catchF, finallyF) {
|
|
|
3145
3243
|
function getCurrentUnixTimestamp() {
|
|
3146
3244
|
return (/* @__PURE__ */ new Date()).getTime() / 1e3;
|
|
3147
3245
|
}
|
|
3148
|
-
function
|
|
3246
|
+
function isEmpty2(a) {
|
|
3149
3247
|
return a === void 0 || a === null;
|
|
3150
3248
|
}
|
|
3151
3249
|
var LazyValue = (_class2 = class {
|
|
@@ -3210,6 +3308,12 @@ function addAzureBlobHeaders(headers, url) {
|
|
|
3210
3308
|
headers["x-ms-blob-type"] = "BlockBlob";
|
|
3211
3309
|
}
|
|
3212
3310
|
}
|
|
3311
|
+
var InternalAbortError = class extends Error {
|
|
3312
|
+
constructor(message) {
|
|
3313
|
+
super(message);
|
|
3314
|
+
this.name = "InternalAbortError";
|
|
3315
|
+
}
|
|
3316
|
+
};
|
|
3213
3317
|
function filterFrom(record, keys) {
|
|
3214
3318
|
const out = {};
|
|
3215
3319
|
for (const k of Object.keys(record)) {
|
|
@@ -3346,7 +3450,7 @@ var NoopSpan = (_class4 = class {
|
|
|
3346
3450
|
return this;
|
|
3347
3451
|
}
|
|
3348
3452
|
end(args) {
|
|
3349
|
-
return _nullishCoalesce(_optionalChain([args, 'optionalAccess',
|
|
3453
|
+
return _nullishCoalesce(_optionalChain([args, 'optionalAccess', _15 => _15.endTime]), () => ( getCurrentUnixTimestamp()));
|
|
3350
3454
|
}
|
|
3351
3455
|
async export() {
|
|
3352
3456
|
return "";
|
|
@@ -3551,8 +3655,8 @@ var BraintrustState = (_class5 = class _BraintrustState {
|
|
|
3551
3655
|
setFetch(fetch2) {
|
|
3552
3656
|
this.loginParams.fetch = fetch2;
|
|
3553
3657
|
this.fetch = fetch2;
|
|
3554
|
-
_optionalChain([this, 'access',
|
|
3555
|
-
_optionalChain([this, 'access',
|
|
3658
|
+
_optionalChain([this, 'access', _16 => _16._apiConn, 'optionalAccess', _17 => _17.setFetch, 'call', _18 => _18(fetch2)]);
|
|
3659
|
+
_optionalChain([this, 'access', _19 => _19._appConn, 'optionalAccess', _20 => _20.setFetch, 'call', _21 => _21(fetch2)]);
|
|
3556
3660
|
}
|
|
3557
3661
|
setMaskingFunction(maskingFunction) {
|
|
3558
3662
|
this.bgLogger().setMaskingFunction(maskingFunction);
|
|
@@ -3564,7 +3668,7 @@ var BraintrustState = (_class5 = class _BraintrustState {
|
|
|
3564
3668
|
const newState = await loginToState({
|
|
3565
3669
|
...this.loginParams,
|
|
3566
3670
|
...Object.fromEntries(
|
|
3567
|
-
Object.entries(loginParams).filter(([k, v]) => !
|
|
3671
|
+
Object.entries(loginParams).filter(([k, v]) => !isEmpty2(v))
|
|
3568
3672
|
)
|
|
3569
3673
|
});
|
|
3570
3674
|
this.copyLoginInfo(newState);
|
|
@@ -3664,7 +3768,7 @@ function useTestBackgroundLogger() {
|
|
|
3664
3768
|
return logger;
|
|
3665
3769
|
}
|
|
3666
3770
|
function clearTestBackgroundLogger() {
|
|
3667
|
-
_optionalChain([_internalGetGlobalState, 'call',
|
|
3771
|
+
_optionalChain([_internalGetGlobalState, 'call', _22 => _22(), 'optionalAccess', _23 => _23.setOverrideBgLogger, 'call', _24 => _24(null)]);
|
|
3668
3772
|
}
|
|
3669
3773
|
function initTestExperiment(experimentName, projectName) {
|
|
3670
3774
|
setInitialTestState();
|
|
@@ -4229,7 +4333,7 @@ function logFeedbackImpl(state, parentObjectType, parentObjectId, {
|
|
|
4229
4333
|
if (!VALID_SOURCES.includes(source)) {
|
|
4230
4334
|
throw new Error(`source must be one of ${VALID_SOURCES}`);
|
|
4231
4335
|
}
|
|
4232
|
-
if (
|
|
4336
|
+
if (isEmpty2(scores) && isEmpty2(expected) && isEmpty2(tags) && isEmpty2(comment)) {
|
|
4233
4337
|
throw new Error(
|
|
4234
4338
|
"At least one of scores, expected, tags, or comment must be specified"
|
|
4235
4339
|
);
|
|
@@ -4242,7 +4346,7 @@ function logFeedbackImpl(state, parentObjectType, parentObjectId, {
|
|
|
4242
4346
|
});
|
|
4243
4347
|
let { metadata, ...updateEvent } = deepCopyEvent(validatedEvent);
|
|
4244
4348
|
updateEvent = Object.fromEntries(
|
|
4245
|
-
Object.entries(updateEvent).filter(([_, v]) => !
|
|
4349
|
+
Object.entries(updateEvent).filter(([_, v]) => !isEmpty2(v))
|
|
4246
4350
|
);
|
|
4247
4351
|
const parentIds = async () => new SpanComponentsV3({
|
|
4248
4352
|
object_type: parentObjectType,
|
|
@@ -4261,7 +4365,7 @@ function logFeedbackImpl(state, parentObjectType, parentObjectId, {
|
|
|
4261
4365
|
});
|
|
4262
4366
|
state.bgLogger().log([record]);
|
|
4263
4367
|
}
|
|
4264
|
-
if (!
|
|
4368
|
+
if (!isEmpty2(comment)) {
|
|
4265
4369
|
const record = new LazyValue(async () => {
|
|
4266
4370
|
return {
|
|
4267
4371
|
id: _uuid.v4.call(void 0, ),
|
|
@@ -4375,9 +4479,9 @@ async function permalink(slug, opts) {
|
|
|
4375
4479
|
if (slug === "") {
|
|
4376
4480
|
return NOOP_SPAN_PERMALINK;
|
|
4377
4481
|
}
|
|
4378
|
-
const state = _nullishCoalesce(_optionalChain([opts, 'optionalAccess',
|
|
4482
|
+
const state = _nullishCoalesce(_optionalChain([opts, 'optionalAccess', _25 => _25.state]), () => ( _globalState));
|
|
4379
4483
|
const getOrgName = async () => {
|
|
4380
|
-
if (_optionalChain([opts, 'optionalAccess',
|
|
4484
|
+
if (_optionalChain([opts, 'optionalAccess', _26 => _26.orgName])) {
|
|
4381
4485
|
return opts.orgName;
|
|
4382
4486
|
}
|
|
4383
4487
|
await state.login({});
|
|
@@ -4387,7 +4491,7 @@ async function permalink(slug, opts) {
|
|
|
4387
4491
|
return state.orgName;
|
|
4388
4492
|
};
|
|
4389
4493
|
const getAppUrl = async () => {
|
|
4390
|
-
if (_optionalChain([opts, 'optionalAccess',
|
|
4494
|
+
if (_optionalChain([opts, 'optionalAccess', _27 => _27.appUrl])) {
|
|
4391
4495
|
return opts.appUrl;
|
|
4392
4496
|
}
|
|
4393
4497
|
await state.login({});
|
|
@@ -4520,7 +4624,7 @@ var Logger = (_class6 = class {
|
|
|
4520
4624
|
* @returns The `id` of the logged event.
|
|
4521
4625
|
*/
|
|
4522
4626
|
log(event, options) {
|
|
4523
|
-
if (this.calledStartSpan && !_optionalChain([options, 'optionalAccess',
|
|
4627
|
+
if (this.calledStartSpan && !_optionalChain([options, 'optionalAccess', _28 => _28.allowConcurrentWithSpans])) {
|
|
4524
4628
|
throw new Error(
|
|
4525
4629
|
"Cannot run toplevel `log` method while using spans. To log to the span, call `logger.traced` and then log with `span.log`"
|
|
4526
4630
|
);
|
|
@@ -4588,12 +4692,12 @@ var Logger = (_class6 = class {
|
|
|
4588
4692
|
state: this.state,
|
|
4589
4693
|
...startSpanParentArgs({
|
|
4590
4694
|
state: this.state,
|
|
4591
|
-
parent: _optionalChain([args, 'optionalAccess',
|
|
4695
|
+
parent: _optionalChain([args, 'optionalAccess', _29 => _29.parent]),
|
|
4592
4696
|
parentObjectType: this.parentObjectType(),
|
|
4593
4697
|
parentObjectId: this.lazyId,
|
|
4594
4698
|
parentComputeObjectMetadataArgs: this.computeMetadataArgs,
|
|
4595
|
-
parentSpanIds: _optionalChain([args, 'optionalAccess',
|
|
4596
|
-
propagatedEvent: _optionalChain([args, 'optionalAccess',
|
|
4699
|
+
parentSpanIds: _optionalChain([args, 'optionalAccess', _30 => _30.parentSpanIds]),
|
|
4700
|
+
propagatedEvent: _optionalChain([args, 'optionalAccess', _31 => _31.propagatedEvent])
|
|
4597
4701
|
}),
|
|
4598
4702
|
defaultRootType: "task" /* TASK */
|
|
4599
4703
|
});
|
|
@@ -4838,7 +4942,7 @@ var HTTPBackgroundLogger = (_class8 = class _HTTPBackgroundLogger {
|
|
|
4838
4942
|
this.queue.clear();
|
|
4839
4943
|
return;
|
|
4840
4944
|
}
|
|
4841
|
-
const batchSize = _nullishCoalesce(_optionalChain([args, 'optionalAccess',
|
|
4945
|
+
const batchSize = _nullishCoalesce(_optionalChain([args, 'optionalAccess', _32 => _32.batchSize]), () => ( this.defaultBatchSize));
|
|
4842
4946
|
const wrappedItems = this.queue.drain();
|
|
4843
4947
|
if (wrappedItems.length === 0) {
|
|
4844
4948
|
return;
|
|
@@ -5103,10 +5207,10 @@ Error: ${errorText}`;
|
|
|
5103
5207
|
} catch (err) {
|
|
5104
5208
|
if (err instanceof AggregateError) {
|
|
5105
5209
|
for (const e of err.errors) {
|
|
5106
|
-
_optionalChain([this, 'access',
|
|
5210
|
+
_optionalChain([this, 'access', _33 => _33.onFlushError, 'optionalCall', _34 => _34(e)]);
|
|
5107
5211
|
}
|
|
5108
5212
|
} else {
|
|
5109
|
-
_optionalChain([this, 'access',
|
|
5213
|
+
_optionalChain([this, 'access', _35 => _35.onFlushError, 'optionalCall', _36 => _36(err)]);
|
|
5110
5214
|
}
|
|
5111
5215
|
this.activeFlushError = err;
|
|
5112
5216
|
} finally {
|
|
@@ -5173,7 +5277,7 @@ function init(projectOrOptions, optionalOptions) {
|
|
|
5173
5277
|
const state = _nullishCoalesce(stateArg, () => ( _globalState));
|
|
5174
5278
|
state.enforceQueueSizeLimit(false);
|
|
5175
5279
|
if (open) {
|
|
5176
|
-
if (
|
|
5280
|
+
if (isEmpty2(experiment)) {
|
|
5177
5281
|
throw new Error(`Cannot open an experiment without specifying its name`);
|
|
5178
5282
|
}
|
|
5179
5283
|
const lazyMetadata2 = new LazyValue(
|
|
@@ -5412,7 +5516,7 @@ async function computeLoggerMetadata(state, {
|
|
|
5412
5516
|
}) {
|
|
5413
5517
|
await state.login({});
|
|
5414
5518
|
const org_id = state.orgId;
|
|
5415
|
-
if (
|
|
5519
|
+
if (isEmpty2(project_id)) {
|
|
5416
5520
|
const response = await state.appConn().post_json("api/project/register", {
|
|
5417
5521
|
project_name: project_name || GLOBAL_PROJECT,
|
|
5418
5522
|
org_id
|
|
@@ -5425,7 +5529,7 @@ async function computeLoggerMetadata(state, {
|
|
|
5425
5529
|
fullInfo: response.project
|
|
5426
5530
|
}
|
|
5427
5531
|
};
|
|
5428
|
-
} else if (
|
|
5532
|
+
} else if (isEmpty2(project_name)) {
|
|
5429
5533
|
const response = await state.appConn().get_json("api/project", {
|
|
5430
5534
|
id: project_id
|
|
5431
5535
|
});
|
|
@@ -5506,9 +5610,9 @@ async function loadPrompt({
|
|
|
5506
5610
|
);
|
|
5507
5611
|
}
|
|
5508
5612
|
if (id) {
|
|
5509
|
-
} else if (
|
|
5613
|
+
} else if (isEmpty2(projectName) && isEmpty2(projectId)) {
|
|
5510
5614
|
throw new Error("Must specify either projectName or projectId");
|
|
5511
|
-
} else if (
|
|
5615
|
+
} else if (isEmpty2(slug)) {
|
|
5512
5616
|
throw new Error("Must specify slug");
|
|
5513
5617
|
}
|
|
5514
5618
|
const state = _nullishCoalesce(stateArg, () => ( _globalState));
|
|
@@ -5610,7 +5714,7 @@ async function login(options = {}) {
|
|
|
5610
5714
|
const { forceLogin = false } = options || {};
|
|
5611
5715
|
if (_globalState.loggedIn && !forceLogin) {
|
|
5612
5716
|
let checkUpdatedParam2 = function(varname, arg, orig) {
|
|
5613
|
-
if (!
|
|
5717
|
+
if (!isEmpty2(arg) && !isEmpty2(orig) && arg !== orig) {
|
|
5614
5718
|
throw new Error(
|
|
5615
5719
|
`Re-logging in with different ${varname} (${arg}) than original (${orig}). To force re-login, pass \`forceLogin: true\``
|
|
5616
5720
|
);
|
|
@@ -5719,24 +5823,24 @@ async function summarize(options = {}) {
|
|
|
5719
5823
|
return await e.summarize(options);
|
|
5720
5824
|
}
|
|
5721
5825
|
function currentExperiment(options) {
|
|
5722
|
-
const state = _nullishCoalesce(_optionalChain([options, 'optionalAccess',
|
|
5826
|
+
const state = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _37 => _37.state]), () => ( _globalState));
|
|
5723
5827
|
return state.currentExperiment;
|
|
5724
5828
|
}
|
|
5725
5829
|
function currentLogger(options) {
|
|
5726
|
-
const state = _nullishCoalesce(_optionalChain([options, 'optionalAccess',
|
|
5727
|
-
return castLogger(state.currentLogger, _optionalChain([options, 'optionalAccess',
|
|
5830
|
+
const state = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _38 => _38.state]), () => ( _globalState));
|
|
5831
|
+
return castLogger(state.currentLogger, _optionalChain([options, 'optionalAccess', _39 => _39.asyncFlush]));
|
|
5728
5832
|
}
|
|
5729
5833
|
function currentSpan(options) {
|
|
5730
|
-
const state = _nullishCoalesce(_optionalChain([options, 'optionalAccess',
|
|
5834
|
+
const state = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _40 => _40.state]), () => ( _globalState));
|
|
5731
5835
|
return _nullishCoalesce(state.contextManager.getCurrentSpan(), () => ( NOOP_SPAN));
|
|
5732
5836
|
}
|
|
5733
5837
|
function getSpanParentObject(options) {
|
|
5734
|
-
const state = _nullishCoalesce(_optionalChain([options, 'optionalAccess',
|
|
5838
|
+
const state = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _41 => _41.state]), () => ( _globalState));
|
|
5735
5839
|
const parentSpan = currentSpan({ state });
|
|
5736
5840
|
if (!Object.is(parentSpan, NOOP_SPAN)) {
|
|
5737
5841
|
return parentSpan;
|
|
5738
5842
|
}
|
|
5739
|
-
const parentStr = _nullishCoalesce(_optionalChain([options, 'optionalAccess',
|
|
5843
|
+
const parentStr = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _42 => _42.parent]), () => ( state.currentParent.getStore()));
|
|
5740
5844
|
if (parentStr) return getSpanComponentsClass().fromStr(parentStr);
|
|
5741
5845
|
const experiment = currentExperiment();
|
|
5742
5846
|
if (experiment) {
|
|
@@ -5765,7 +5869,7 @@ function traced(callback, args) {
|
|
|
5765
5869
|
const { span, isSyncFlushLogger } = startSpanAndIsLogger(args);
|
|
5766
5870
|
const ret = runCatchFinally(
|
|
5767
5871
|
() => {
|
|
5768
|
-
if (_nullishCoalesce(_optionalChain([args, 'optionalAccess',
|
|
5872
|
+
if (_nullishCoalesce(_optionalChain([args, 'optionalAccess', _43 => _43.setCurrent]), () => ( true))) {
|
|
5769
5873
|
return withCurrent(span, callback);
|
|
5770
5874
|
} else {
|
|
5771
5875
|
return callback(span);
|
|
@@ -5777,7 +5881,7 @@ function traced(callback, args) {
|
|
|
5777
5881
|
},
|
|
5778
5882
|
() => span.end()
|
|
5779
5883
|
);
|
|
5780
|
-
if (_optionalChain([args, 'optionalAccess',
|
|
5884
|
+
if (_optionalChain([args, 'optionalAccess', _44 => _44.asyncFlush]) === void 0 || _optionalChain([args, 'optionalAccess', _45 => _45.asyncFlush])) {
|
|
5781
5885
|
return ret;
|
|
5782
5886
|
} else {
|
|
5783
5887
|
return (async () => {
|
|
@@ -5901,14 +6005,14 @@ function wrapTraced(fn, args) {
|
|
|
5901
6005
|
};
|
|
5902
6006
|
const hasExplicitInput = args && args.event && "input" in args.event && args.event.input !== void 0;
|
|
5903
6007
|
const hasExplicitOutput = args && args.event && args.event.output !== void 0;
|
|
5904
|
-
const noTraceIO = _optionalChain([args, 'optionalAccess',
|
|
6008
|
+
const noTraceIO = _optionalChain([args, 'optionalAccess', _46 => _46.noTraceIO]) || hasExplicitInput || hasExplicitOutput;
|
|
5905
6009
|
if (isGeneratorFunction(fn)) {
|
|
5906
6010
|
return wrapTracedSyncGenerator(fn, spanArgs, !!noTraceIO);
|
|
5907
6011
|
}
|
|
5908
6012
|
if (isAsyncGeneratorFunction(fn)) {
|
|
5909
6013
|
return wrapTracedAsyncGenerator(fn, spanArgs, !!noTraceIO);
|
|
5910
6014
|
}
|
|
5911
|
-
if (_optionalChain([args, 'optionalAccess',
|
|
6015
|
+
if (_optionalChain([args, 'optionalAccess', _47 => _47.asyncFlush])) {
|
|
5912
6016
|
return ((...fnArgs) => traced((span) => {
|
|
5913
6017
|
if (!hasExplicitInput) {
|
|
5914
6018
|
span.log({ input: fnArgs });
|
|
@@ -5946,17 +6050,17 @@ function startSpan(args) {
|
|
|
5946
6050
|
return startSpanAndIsLogger(args).span;
|
|
5947
6051
|
}
|
|
5948
6052
|
async function flush(options) {
|
|
5949
|
-
const state = _nullishCoalesce(_optionalChain([options, 'optionalAccess',
|
|
6053
|
+
const state = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _48 => _48.state]), () => ( _globalState));
|
|
5950
6054
|
return await state.bgLogger().flush();
|
|
5951
6055
|
}
|
|
5952
6056
|
function setFetch(fetch2) {
|
|
5953
6057
|
_globalState.setFetch(fetch2);
|
|
5954
6058
|
}
|
|
5955
6059
|
function startSpanAndIsLogger(args) {
|
|
5956
|
-
const state = _nullishCoalesce(_optionalChain([args, 'optionalAccess',
|
|
6060
|
+
const state = _nullishCoalesce(_optionalChain([args, 'optionalAccess', _49 => _49.state]), () => ( _globalState));
|
|
5957
6061
|
const parentObject = getSpanParentObject({
|
|
5958
|
-
asyncFlush: _optionalChain([args, 'optionalAccess',
|
|
5959
|
-
parent: _optionalChain([args, 'optionalAccess',
|
|
6062
|
+
asyncFlush: _optionalChain([args, 'optionalAccess', _50 => _50.asyncFlush]),
|
|
6063
|
+
parent: _optionalChain([args, 'optionalAccess', _51 => _51.parent]),
|
|
5960
6064
|
state
|
|
5961
6065
|
});
|
|
5962
6066
|
if (parentObject instanceof SpanComponentsV3 || parentObject instanceof SpanComponentsV4) {
|
|
@@ -5973,14 +6077,14 @@ function startSpanAndIsLogger(args) {
|
|
|
5973
6077
|
),
|
|
5974
6078
|
parentComputeObjectMetadataArgs: _nullishCoalesce(parentObject.data.compute_object_metadata_args, () => ( void 0)),
|
|
5975
6079
|
parentSpanIds,
|
|
5976
|
-
propagatedEvent: _nullishCoalesce(_optionalChain([args, 'optionalAccess',
|
|
6080
|
+
propagatedEvent: _nullishCoalesce(_optionalChain([args, 'optionalAccess', _52 => _52.propagatedEvent]), () => ( // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
|
|
5977
6081
|
(_nullishCoalesce(parentObject.data.propagated_event, () => ( void 0)))))
|
|
5978
6082
|
});
|
|
5979
6083
|
return {
|
|
5980
6084
|
span,
|
|
5981
6085
|
isSyncFlushLogger: parentObject.data.object_type === 2 /* PROJECT_LOGS */ && // Since there's no parent logger here, we're free to choose the async flush
|
|
5982
6086
|
// behavior, and therefore propagate along whatever we get from the arguments
|
|
5983
|
-
_optionalChain([args, 'optionalAccess',
|
|
6087
|
+
_optionalChain([args, 'optionalAccess', _53 => _53.asyncFlush]) === false
|
|
5984
6088
|
};
|
|
5985
6089
|
} else {
|
|
5986
6090
|
const span = parentObject.startSpan(args);
|
|
@@ -6172,10 +6276,10 @@ function extractAttachments(event, attachments) {
|
|
|
6172
6276
|
event[key] = value.reference;
|
|
6173
6277
|
continue;
|
|
6174
6278
|
}
|
|
6175
|
-
if (_optionalChain([value, 'optionalAccess',
|
|
6279
|
+
if (_optionalChain([value, 'optionalAccess', _54 => _54.type]) === BRAINTRUST_ATTACHMENT && value.key && !value.uploader) {
|
|
6176
6280
|
continue;
|
|
6177
6281
|
}
|
|
6178
|
-
if (_optionalChain([value, 'optionalAccess',
|
|
6282
|
+
if (_optionalChain([value, 'optionalAccess', _55 => _55.reference, 'optionalAccess', _56 => _56.type]) === BRAINTRUST_ATTACHMENT && _optionalChain([value, 'optionalAccess', _57 => _57.uploader])) {
|
|
6179
6283
|
const attachment = new Attachment({
|
|
6180
6284
|
data: value.dataDebugString,
|
|
6181
6285
|
filename: value.reference.filename,
|
|
@@ -6219,15 +6323,15 @@ async function resolveAttachmentsToBase64(event, state) {
|
|
|
6219
6323
|
return event;
|
|
6220
6324
|
}
|
|
6221
6325
|
function validateAndSanitizeExperimentLogFullArgs(event, hasDataset) {
|
|
6222
|
-
if ("input" in event && !
|
|
6326
|
+
if ("input" in event && !isEmpty2(event.input) && "inputs" in event && !isEmpty2(event.inputs) || !("input" in event) && !("inputs" in event)) {
|
|
6223
6327
|
throw new Error(
|
|
6224
6328
|
"Exactly one of input or inputs (deprecated) must be specified. Prefer input."
|
|
6225
6329
|
);
|
|
6226
6330
|
}
|
|
6227
|
-
if (
|
|
6331
|
+
if (isEmpty2(event.output)) {
|
|
6228
6332
|
throw new Error("output must be specified");
|
|
6229
6333
|
}
|
|
6230
|
-
if (
|
|
6334
|
+
if (isEmpty2(event.scores)) {
|
|
6231
6335
|
throw new Error("scores must be specified");
|
|
6232
6336
|
}
|
|
6233
6337
|
if (hasDataset && event.datasetRecordId === void 0) {
|
|
@@ -6326,7 +6430,7 @@ var ObjectFetcher = (_class9 = class {
|
|
|
6326
6430
|
}
|
|
6327
6431
|
return;
|
|
6328
6432
|
}
|
|
6329
|
-
for await (const record of this.fetchRecordsFromApi(_optionalChain([options, 'optionalAccess',
|
|
6433
|
+
for await (const record of this.fetchRecordsFromApi(_optionalChain([options, 'optionalAccess', _58 => _58.batchSize]))) {
|
|
6330
6434
|
yield record;
|
|
6331
6435
|
}
|
|
6332
6436
|
}
|
|
@@ -6336,7 +6440,7 @@ var ObjectFetcher = (_class9 = class {
|
|
|
6336
6440
|
async fetchedData(options) {
|
|
6337
6441
|
if (this._fetchedData === void 0) {
|
|
6338
6442
|
const data = [];
|
|
6339
|
-
for await (const record of this.fetchRecordsFromApi(_optionalChain([options, 'optionalAccess',
|
|
6443
|
+
for await (const record of this.fetchRecordsFromApi(_optionalChain([options, 'optionalAccess', _59 => _59.batchSize]))) {
|
|
6340
6444
|
data.push(record);
|
|
6341
6445
|
}
|
|
6342
6446
|
this._fetchedData = data;
|
|
@@ -6431,7 +6535,7 @@ var Experiment2 = (_class10 = class extends ObjectFetcher {
|
|
|
6431
6535
|
* @returns The `id` of the logged event.
|
|
6432
6536
|
*/
|
|
6433
6537
|
log(event, options) {
|
|
6434
|
-
if (this.calledStartSpan && !_optionalChain([options, 'optionalAccess',
|
|
6538
|
+
if (this.calledStartSpan && !_optionalChain([options, 'optionalAccess', _60 => _60.allowConcurrentWithSpans])) {
|
|
6435
6539
|
throw new Error(
|
|
6436
6540
|
"Cannot run toplevel `log` method while using spans. To log to the span, call `experiment.traced` and then log with `span.log`"
|
|
6437
6541
|
);
|
|
@@ -6484,12 +6588,12 @@ var Experiment2 = (_class10 = class extends ObjectFetcher {
|
|
|
6484
6588
|
state: this.state,
|
|
6485
6589
|
...startSpanParentArgs({
|
|
6486
6590
|
state: this.state,
|
|
6487
|
-
parent: _optionalChain([args, 'optionalAccess',
|
|
6591
|
+
parent: _optionalChain([args, 'optionalAccess', _61 => _61.parent]),
|
|
6488
6592
|
parentObjectType: this.parentObjectType(),
|
|
6489
6593
|
parentObjectId: this.lazyId,
|
|
6490
6594
|
parentComputeObjectMetadataArgs: void 0,
|
|
6491
6595
|
parentSpanIds: void 0,
|
|
6492
|
-
propagatedEvent: _optionalChain([args, 'optionalAccess',
|
|
6596
|
+
propagatedEvent: _optionalChain([args, 'optionalAccess', _62 => _62.propagatedEvent])
|
|
6493
6597
|
}),
|
|
6494
6598
|
defaultRootType: "eval" /* EVAL */
|
|
6495
6599
|
});
|
|
@@ -6827,10 +6931,10 @@ var SpanImpl = (_class11 = class _SpanImpl {
|
|
|
6827
6931
|
...serializableInternalData,
|
|
6828
6932
|
[IS_MERGE_FIELD]: this.isMerge
|
|
6829
6933
|
});
|
|
6830
|
-
if (_optionalChain([partialRecord, 'access',
|
|
6831
|
-
this.loggedEndTime = _optionalChain([partialRecord, 'access',
|
|
6934
|
+
if (_optionalChain([partialRecord, 'access', _63 => _63.metrics, 'optionalAccess', _64 => _64.end])) {
|
|
6935
|
+
this.loggedEndTime = _optionalChain([partialRecord, 'access', _65 => _65.metrics, 'optionalAccess', _66 => _66.end]);
|
|
6832
6936
|
}
|
|
6833
|
-
if ((_nullishCoalesce(partialRecord.tags, () => ( []))).length > 0 && _optionalChain([this, 'access',
|
|
6937
|
+
if ((_nullishCoalesce(partialRecord.tags, () => ( []))).length > 0 && _optionalChain([this, 'access', _67 => _67._spanParents, 'optionalAccess', _68 => _68.length])) {
|
|
6834
6938
|
throw new Error("Tags can only be logged to the root span");
|
|
6835
6939
|
}
|
|
6836
6940
|
const computeRecord = async () => ({
|
|
@@ -6875,18 +6979,18 @@ var SpanImpl = (_class11 = class _SpanImpl {
|
|
|
6875
6979
|
);
|
|
6876
6980
|
}
|
|
6877
6981
|
startSpan(args) {
|
|
6878
|
-
const parentSpanIds = _optionalChain([args, 'optionalAccess',
|
|
6982
|
+
const parentSpanIds = _optionalChain([args, 'optionalAccess', _69 => _69.parent]) ? void 0 : { spanId: this._spanId, rootSpanId: this._rootSpanId };
|
|
6879
6983
|
return new _SpanImpl({
|
|
6880
6984
|
state: this._state,
|
|
6881
6985
|
...args,
|
|
6882
6986
|
...startSpanParentArgs({
|
|
6883
6987
|
state: this._state,
|
|
6884
|
-
parent: _optionalChain([args, 'optionalAccess',
|
|
6988
|
+
parent: _optionalChain([args, 'optionalAccess', _70 => _70.parent]),
|
|
6885
6989
|
parentObjectType: this.parentObjectType,
|
|
6886
6990
|
parentObjectId: this.parentObjectId,
|
|
6887
6991
|
parentComputeObjectMetadataArgs: this.parentComputeObjectMetadataArgs,
|
|
6888
6992
|
parentSpanIds,
|
|
6889
|
-
propagatedEvent: _nullishCoalesce(_optionalChain([args, 'optionalAccess',
|
|
6993
|
+
propagatedEvent: _nullishCoalesce(_optionalChain([args, 'optionalAccess', _71 => _71.propagatedEvent]), () => ( this.propagatedEvent))
|
|
6890
6994
|
})
|
|
6891
6995
|
});
|
|
6892
6996
|
}
|
|
@@ -6900,12 +7004,12 @@ var SpanImpl = (_class11 = class _SpanImpl {
|
|
|
6900
7004
|
...args,
|
|
6901
7005
|
...startSpanParentArgs({
|
|
6902
7006
|
state: this._state,
|
|
6903
|
-
parent: _optionalChain([args, 'optionalAccess',
|
|
7007
|
+
parent: _optionalChain([args, 'optionalAccess', _72 => _72.parent]),
|
|
6904
7008
|
parentObjectType: this.parentObjectType,
|
|
6905
7009
|
parentObjectId: this.parentObjectId,
|
|
6906
7010
|
parentComputeObjectMetadataArgs: this.parentComputeObjectMetadataArgs,
|
|
6907
7011
|
parentSpanIds,
|
|
6908
|
-
propagatedEvent: _nullishCoalesce(_optionalChain([args, 'optionalAccess',
|
|
7012
|
+
propagatedEvent: _nullishCoalesce(_optionalChain([args, 'optionalAccess', _73 => _73.propagatedEvent]), () => ( this.propagatedEvent))
|
|
6909
7013
|
}),
|
|
6910
7014
|
spanId
|
|
6911
7015
|
});
|
|
@@ -6914,7 +7018,7 @@ var SpanImpl = (_class11 = class _SpanImpl {
|
|
|
6914
7018
|
let endTime;
|
|
6915
7019
|
let internalData = {};
|
|
6916
7020
|
if (!this.loggedEndTime) {
|
|
6917
|
-
endTime = _nullishCoalesce(_optionalChain([args, 'optionalAccess',
|
|
7021
|
+
endTime = _nullishCoalesce(_optionalChain([args, 'optionalAccess', _74 => _74.endTime]), () => ( getCurrentUnixTimestamp()));
|
|
6918
7022
|
internalData = { metrics: { end: endTime } };
|
|
6919
7023
|
} else {
|
|
6920
7024
|
endTime = this.loggedEndTime;
|
|
@@ -6957,8 +7061,8 @@ var SpanImpl = (_class11 = class _SpanImpl {
|
|
|
6957
7061
|
const args = this.parentComputeObjectMetadataArgs;
|
|
6958
7062
|
switch (this.parentObjectType) {
|
|
6959
7063
|
case 2 /* PROJECT_LOGS */: {
|
|
6960
|
-
const projectID = _optionalChain([args, 'optionalAccess',
|
|
6961
|
-
const projectName = _optionalChain([args, 'optionalAccess',
|
|
7064
|
+
const projectID = _optionalChain([args, 'optionalAccess', _75 => _75.project_id]) || this.parentObjectId.getSync().value;
|
|
7065
|
+
const projectName = _optionalChain([args, 'optionalAccess', _76 => _76.project_name]);
|
|
6962
7066
|
if (projectID) {
|
|
6963
7067
|
return `${baseUrl}/object?object_type=project_logs&object_id=${projectID}&id=${this._id}`;
|
|
6964
7068
|
} else if (projectName) {
|
|
@@ -6968,7 +7072,7 @@ var SpanImpl = (_class11 = class _SpanImpl {
|
|
|
6968
7072
|
}
|
|
6969
7073
|
}
|
|
6970
7074
|
case 1 /* EXPERIMENT */: {
|
|
6971
|
-
const expID = _optionalChain([args, 'optionalAccess',
|
|
7075
|
+
const expID = _optionalChain([args, 'optionalAccess', _77 => _77.experiment_id]) || _optionalChain([this, 'access', _78 => _78.parentObjectId, 'optionalAccess', _79 => _79.getSync, 'call', _80 => _80(), 'optionalAccess', _81 => _81.value]);
|
|
6972
7076
|
if (!expID) {
|
|
6973
7077
|
return getErrPermlink("provide-experiment-id");
|
|
6974
7078
|
} else {
|
|
@@ -7023,14 +7127,14 @@ function splitLoggingData({
|
|
|
7023
7127
|
if (value instanceof BraintrustStream) {
|
|
7024
7128
|
const streamCopy = value.copy();
|
|
7025
7129
|
lazyInternalData[key] = new LazyValue(async () => {
|
|
7026
|
-
return await new Promise((resolve,
|
|
7027
|
-
streamCopy.toReadableStream().pipeThrough(createFinalValuePassThroughStream(resolve,
|
|
7130
|
+
return await new Promise((resolve, reject2) => {
|
|
7131
|
+
streamCopy.toReadableStream().pipeThrough(createFinalValuePassThroughStream(resolve, reject2)).pipeTo(devNullWritableStream());
|
|
7028
7132
|
});
|
|
7029
7133
|
});
|
|
7030
7134
|
} else if (value instanceof ReadableStream) {
|
|
7031
7135
|
lazyInternalData[key] = new LazyValue(async () => {
|
|
7032
|
-
return await new Promise((resolve,
|
|
7033
|
-
value.pipeThrough(createFinalValuePassThroughStream(resolve,
|
|
7136
|
+
return await new Promise((resolve, reject2) => {
|
|
7137
|
+
value.pipeThrough(createFinalValuePassThroughStream(resolve, reject2)).pipeTo(devNullWritableStream());
|
|
7034
7138
|
});
|
|
7035
7139
|
});
|
|
7036
7140
|
} else {
|
|
@@ -7287,7 +7391,7 @@ function renderMessage(render, message) {
|
|
|
7287
7391
|
return {
|
|
7288
7392
|
...message,
|
|
7289
7393
|
..."content" in message ? {
|
|
7290
|
-
content:
|
|
7394
|
+
content: isEmpty2(message.content) ? void 0 : typeof message.content === "string" ? render(message.content) : message.content.map((c) => {
|
|
7291
7395
|
switch (c.type) {
|
|
7292
7396
|
case "text":
|
|
7293
7397
|
return { ...c, text: render(c.text) };
|
|
@@ -7324,7 +7428,7 @@ function renderMessage(render, message) {
|
|
|
7324
7428
|
})
|
|
7325
7429
|
} : {},
|
|
7326
7430
|
..."tool_calls" in message ? {
|
|
7327
|
-
tool_calls:
|
|
7431
|
+
tool_calls: isEmpty2(message.tool_calls) ? void 0 : message.tool_calls.map((t) => {
|
|
7328
7432
|
return {
|
|
7329
7433
|
type: t.type,
|
|
7330
7434
|
id: render(t.id),
|
|
@@ -7424,13 +7528,13 @@ var Prompt2 = (_class13 = class _Prompt {
|
|
|
7424
7528
|
return "slug" in this.metadata ? this.metadata.slug : this.metadata.id;
|
|
7425
7529
|
}
|
|
7426
7530
|
get prompt() {
|
|
7427
|
-
return _optionalChain([this, 'access',
|
|
7531
|
+
return _optionalChain([this, 'access', _82 => _82.getParsedPromptData, 'call', _83 => _83(), 'optionalAccess', _84 => _84.prompt]);
|
|
7428
7532
|
}
|
|
7429
7533
|
get version() {
|
|
7430
7534
|
return this.metadata[TRANSACTION_ID_FIELD];
|
|
7431
7535
|
}
|
|
7432
7536
|
get options() {
|
|
7433
|
-
return _optionalChain([this, 'access',
|
|
7537
|
+
return _optionalChain([this, 'access', _85 => _85.getParsedPromptData, 'call', _86 => _86(), 'optionalAccess', _87 => _87.options]) || {};
|
|
7434
7538
|
}
|
|
7435
7539
|
get promptData() {
|
|
7436
7540
|
return this.getParsedPromptData();
|
|
@@ -7473,11 +7577,11 @@ var Prompt2 = (_class13 = class _Prompt {
|
|
|
7473
7577
|
([k, _v]) => !BRAINTRUST_PARAMS.includes(k)
|
|
7474
7578
|
)
|
|
7475
7579
|
),
|
|
7476
|
-
...!
|
|
7580
|
+
...!isEmpty2(this.options.model) ? {
|
|
7477
7581
|
model: this.options.model
|
|
7478
7582
|
} : {}
|
|
7479
7583
|
};
|
|
7480
|
-
if (!("model" in params) ||
|
|
7584
|
+
if (!("model" in params) || isEmpty2(params.model)) {
|
|
7481
7585
|
throw new Error(
|
|
7482
7586
|
"No model specified. Either specify it in the prompt or as a default"
|
|
7483
7587
|
);
|
|
@@ -7581,7 +7685,7 @@ var Prompt2 = (_class13 = class _Prompt {
|
|
|
7581
7685
|
return {
|
|
7582
7686
|
type: "chat",
|
|
7583
7687
|
messages,
|
|
7584
|
-
..._optionalChain([prompt, 'access',
|
|
7688
|
+
..._optionalChain([prompt, 'access', _88 => _88.tools, 'optionalAccess', _89 => _89.trim, 'call', _90 => _90()]) ? {
|
|
7585
7689
|
tools: render(prompt.tools)
|
|
7586
7690
|
} : void 0
|
|
7587
7691
|
};
|
|
@@ -7691,9 +7795,9 @@ async function getPromptVersions(projectId, promptId) {
|
|
|
7691
7795
|
);
|
|
7692
7796
|
}
|
|
7693
7797
|
const result = await response.json();
|
|
7694
|
-
return _optionalChain([result, 'access',
|
|
7695
|
-
(entry) => ["upsert", "merge"].includes(_optionalChain([entry, 'access',
|
|
7696
|
-
), 'access',
|
|
7798
|
+
return _optionalChain([result, 'access', _91 => _91.data, 'optionalAccess', _92 => _92.filter, 'call', _93 => _93(
|
|
7799
|
+
(entry) => ["upsert", "merge"].includes(_optionalChain([entry, 'access', _94 => _94.audit_data, 'optionalAccess', _95 => _95.action]))
|
|
7800
|
+
), 'access', _96 => _96.map, 'call', _97 => _97((entry) => prettifyXact(entry._xact_id))]) || [];
|
|
7697
7801
|
}
|
|
7698
7802
|
function resetIdGenStateForTests() {
|
|
7699
7803
|
const state = _internalGetGlobalState();
|
|
@@ -7747,18 +7851,24 @@ function configureBrowser() {
|
|
|
7747
7851
|
browserConfigured = true;
|
|
7748
7852
|
}
|
|
7749
7853
|
|
|
7750
|
-
// src/exports
|
|
7751
|
-
var
|
|
7752
|
-
__export(
|
|
7854
|
+
// src/exports.ts
|
|
7855
|
+
var exports_exports = {};
|
|
7856
|
+
__export(exports_exports, {
|
|
7753
7857
|
Attachment: () => Attachment,
|
|
7858
|
+
AttachmentReference: () => AttachmentReference,
|
|
7754
7859
|
BaseAttachment: () => BaseAttachment,
|
|
7860
|
+
BaseExperiment: () => BaseExperiment,
|
|
7755
7861
|
BraintrustMiddleware: () => BraintrustMiddleware,
|
|
7756
7862
|
BraintrustState: () => BraintrustState,
|
|
7757
7863
|
BraintrustStream: () => BraintrustStream,
|
|
7864
|
+
CodeFunction: () => CodeFunction,
|
|
7865
|
+
CodePrompt: () => CodePrompt,
|
|
7758
7866
|
ContextManager: () => ContextManager,
|
|
7759
7867
|
DEFAULT_FETCH_BATCH_SIZE: () => DEFAULT_FETCH_BATCH_SIZE,
|
|
7760
7868
|
Dataset: () => Dataset2,
|
|
7761
7869
|
ERR_PERMALINK: () => ERR_PERMALINK,
|
|
7870
|
+
Eval: () => Eval,
|
|
7871
|
+
EvalResultWithSummary: () => EvalResultWithSummary,
|
|
7762
7872
|
Experiment: () => Experiment2,
|
|
7763
7873
|
ExternalAttachment: () => ExternalAttachment,
|
|
7764
7874
|
FailedHTTPResponse: () => FailedHTTPResponse,
|
|
@@ -7771,22 +7881,30 @@ __export(exports_browser_exports, {
|
|
|
7771
7881
|
NOOP_SPAN: () => NOOP_SPAN,
|
|
7772
7882
|
NOOP_SPAN_PERMALINK: () => NOOP_SPAN_PERMALINK,
|
|
7773
7883
|
NoopSpan: () => NoopSpan,
|
|
7884
|
+
Project: () => Project2,
|
|
7885
|
+
ProjectNameIdMap: () => ProjectNameIdMap,
|
|
7774
7886
|
Prompt: () => Prompt2,
|
|
7887
|
+
PromptBuilder: () => PromptBuilder,
|
|
7775
7888
|
ReadonlyAttachment: () => ReadonlyAttachment,
|
|
7776
7889
|
ReadonlyExperiment: () => ReadonlyExperiment,
|
|
7890
|
+
Reporter: () => Reporter,
|
|
7891
|
+
ScorerBuilder: () => ScorerBuilder,
|
|
7777
7892
|
SpanImpl: () => SpanImpl,
|
|
7778
7893
|
TestBackgroundLogger: () => TestBackgroundLogger,
|
|
7894
|
+
ToolBuilder: () => ToolBuilder,
|
|
7779
7895
|
UUIDGenerator: () => UUIDGenerator,
|
|
7780
7896
|
X_CACHED_HEADER: () => X_CACHED_HEADER,
|
|
7781
7897
|
_exportsForTestingOnly: () => _exportsForTestingOnly,
|
|
7782
7898
|
_internalGetGlobalState: () => _internalGetGlobalState,
|
|
7783
7899
|
_internalSetInitialState: () => _internalSetInitialState,
|
|
7784
7900
|
braintrustStreamChunkSchema: () => braintrustStreamChunkSchema,
|
|
7901
|
+
buildLocalSummary: () => buildLocalSummary,
|
|
7785
7902
|
createFinalValuePassThroughStream: () => createFinalValuePassThroughStream,
|
|
7786
7903
|
currentExperiment: () => currentExperiment,
|
|
7787
7904
|
currentLogger: () => currentLogger,
|
|
7788
7905
|
currentSpan: () => currentSpan,
|
|
7789
7906
|
deepCopyEvent: () => deepCopyEvent,
|
|
7907
|
+
defaultErrorScoreHandler: () => defaultErrorScoreHandler,
|
|
7790
7908
|
deserializePlainStringAsJSON: () => deserializePlainStringAsJSON,
|
|
7791
7909
|
devNullWritableStream: () => devNullWritableStream,
|
|
7792
7910
|
evaluatorDefinitionSchema: () => evaluatorDefinitionSchema,
|
|
@@ -7811,13 +7929,21 @@ __export(exports_browser_exports, {
|
|
|
7811
7929
|
newId: () => newId,
|
|
7812
7930
|
parseCachedHeader: () => parseCachedHeader,
|
|
7813
7931
|
permalink: () => permalink,
|
|
7932
|
+
projects: () => projects,
|
|
7933
|
+
promptContentsSchema: () => promptContentsSchema,
|
|
7934
|
+
promptDefinitionSchema: () => promptDefinitionSchema,
|
|
7935
|
+
promptDefinitionToPromptData: () => promptDefinitionToPromptData,
|
|
7936
|
+
promptDefinitionWithToolsSchema: () => promptDefinitionWithToolsSchema,
|
|
7814
7937
|
renderMessage: () => renderMessage,
|
|
7815
7938
|
renderPromptParams: () => renderPromptParams,
|
|
7939
|
+
reportFailures: () => reportFailures,
|
|
7940
|
+
runEvaluator: () => runEvaluator,
|
|
7816
7941
|
setFetch: () => setFetch,
|
|
7817
7942
|
setMaskingFunction: () => setMaskingFunction,
|
|
7818
7943
|
spanComponentsToObjectId: () => spanComponentsToObjectId,
|
|
7819
7944
|
startSpan: () => startSpan,
|
|
7820
7945
|
summarize: () => summarize,
|
|
7946
|
+
toolFunctionDefinitionSchema: () => ToolFunctionDefinition,
|
|
7821
7947
|
traceable: () => traceable,
|
|
7822
7948
|
traced: () => traced,
|
|
7823
7949
|
updateSpan: () => updateSpan,
|
|
@@ -7827,6 +7953,7 @@ __export(exports_browser_exports, {
|
|
|
7827
7953
|
withLogger: () => withLogger,
|
|
7828
7954
|
withParent: () => withParent,
|
|
7829
7955
|
wrapAISDK: () => wrapAISDK,
|
|
7956
|
+
wrapAISDKModel: () => wrapAISDKModel,
|
|
7830
7957
|
wrapAnthropic: () => wrapAnthropic,
|
|
7831
7958
|
wrapClaudeAgentSDK: () => wrapClaudeAgentSDK,
|
|
7832
7959
|
wrapGoogleGenAI: () => wrapGoogleGenAI,
|
|
@@ -7973,7 +8100,7 @@ function parseSpanFromResponseCreateParams(params) {
|
|
|
7973
8100
|
}
|
|
7974
8101
|
function parseEventFromResponseCreateResult(result) {
|
|
7975
8102
|
const data = {};
|
|
7976
|
-
if (_optionalChain([result, 'optionalAccess',
|
|
8103
|
+
if (_optionalChain([result, 'optionalAccess', _98 => _98.output]) !== void 0) {
|
|
7977
8104
|
data.output = processImagesInOutput(result.output);
|
|
7978
8105
|
}
|
|
7979
8106
|
if (result) {
|
|
@@ -7982,7 +8109,7 @@ function parseEventFromResponseCreateResult(result) {
|
|
|
7982
8109
|
data.metadata = metadata;
|
|
7983
8110
|
}
|
|
7984
8111
|
}
|
|
7985
|
-
data.metrics = parseMetricsFromUsage(_optionalChain([result, 'optionalAccess',
|
|
8112
|
+
data.metrics = parseMetricsFromUsage(_optionalChain([result, 'optionalAccess', _99 => _99.usage]));
|
|
7986
8113
|
return data;
|
|
7987
8114
|
}
|
|
7988
8115
|
function processImagesInOutput(output) {
|
|
@@ -8036,7 +8163,7 @@ function parseSpanFromResponseParseParams(params) {
|
|
|
8036
8163
|
}
|
|
8037
8164
|
function parseEventFromResponseParseResult(result) {
|
|
8038
8165
|
const data = {};
|
|
8039
|
-
if (_optionalChain([result, 'optionalAccess',
|
|
8166
|
+
if (_optionalChain([result, 'optionalAccess', _100 => _100.output]) !== void 0) {
|
|
8040
8167
|
data.output = processImagesInOutput(result.output);
|
|
8041
8168
|
}
|
|
8042
8169
|
if (result) {
|
|
@@ -8045,7 +8172,7 @@ function parseEventFromResponseParseResult(result) {
|
|
|
8045
8172
|
data.metadata = metadata;
|
|
8046
8173
|
}
|
|
8047
8174
|
}
|
|
8048
|
-
data.metrics = parseMetricsFromUsage(_optionalChain([result, 'optionalAccess',
|
|
8175
|
+
data.metrics = parseMetricsFromUsage(_optionalChain([result, 'optionalAccess', _101 => _101.usage]));
|
|
8049
8176
|
return data;
|
|
8050
8177
|
}
|
|
8051
8178
|
function traceResponseCreateStream(stream, timedSpan) {
|
|
@@ -8062,7 +8189,7 @@ function traceResponseCreateStream(stream, timedSpan) {
|
|
|
8062
8189
|
return result;
|
|
8063
8190
|
}
|
|
8064
8191
|
const item = result.value;
|
|
8065
|
-
if (!item || !_optionalChain([item, 'optionalAccess',
|
|
8192
|
+
if (!item || !_optionalChain([item, 'optionalAccess', _102 => _102.type]) || !_optionalChain([item, 'optionalAccess', _103 => _103.response])) {
|
|
8066
8193
|
return result;
|
|
8067
8194
|
}
|
|
8068
8195
|
const event = parseLogFromItem(item);
|
|
@@ -8073,14 +8200,14 @@ function traceResponseCreateStream(stream, timedSpan) {
|
|
|
8073
8200
|
};
|
|
8074
8201
|
}
|
|
8075
8202
|
function parseLogFromItem(item) {
|
|
8076
|
-
if (!item || !_optionalChain([item, 'optionalAccess',
|
|
8203
|
+
if (!item || !_optionalChain([item, 'optionalAccess', _104 => _104.type]) || !_optionalChain([item, 'optionalAccess', _105 => _105.response])) {
|
|
8077
8204
|
return {};
|
|
8078
8205
|
}
|
|
8079
8206
|
const response = item.response;
|
|
8080
8207
|
switch (item.type) {
|
|
8081
8208
|
case "response.completed":
|
|
8082
8209
|
const data = {};
|
|
8083
|
-
if (_optionalChain([response, 'optionalAccess',
|
|
8210
|
+
if (_optionalChain([response, 'optionalAccess', _106 => _106.output]) !== void 0) {
|
|
8084
8211
|
data.output = processImagesInOutput(response.output);
|
|
8085
8212
|
}
|
|
8086
8213
|
if (response) {
|
|
@@ -8089,7 +8216,7 @@ function parseLogFromItem(item) {
|
|
|
8089
8216
|
data.metadata = metadata;
|
|
8090
8217
|
}
|
|
8091
8218
|
}
|
|
8092
|
-
data.metrics = parseMetricsFromUsage(_optionalChain([response, 'optionalAccess',
|
|
8219
|
+
data.metrics = parseMetricsFromUsage(_optionalChain([response, 'optionalAccess', _107 => _107.usage]));
|
|
8093
8220
|
return data;
|
|
8094
8221
|
default:
|
|
8095
8222
|
return {};
|
|
@@ -8286,8 +8413,8 @@ function wrapOpenAIv4(openai) {
|
|
|
8286
8413
|
const embeddingProxy = createEndpointProxy(openai.embeddings, wrapEmbeddings);
|
|
8287
8414
|
const moderationProxy = createEndpointProxy(openai.moderations, wrapModerations);
|
|
8288
8415
|
let betaProxy2;
|
|
8289
|
-
if (_optionalChain([openai, 'access',
|
|
8290
|
-
const betaChatCompletionProxy = new Proxy(_optionalChain([openai, 'optionalAccess',
|
|
8416
|
+
if (_optionalChain([openai, 'access', _108 => _108.beta, 'optionalAccess', _109 => _109.chat, 'optionalAccess', _110 => _110.completions, 'optionalAccess', _111 => _111.stream])) {
|
|
8417
|
+
const betaChatCompletionProxy = new Proxy(_optionalChain([openai, 'optionalAccess', _112 => _112.beta, 'optionalAccess', _113 => _113.chat, 'access', _114 => _114.completions]), {
|
|
8291
8418
|
get(target, name, receiver) {
|
|
8292
8419
|
const baseVal = Reflect.get(target, name, receiver);
|
|
8293
8420
|
if (name === "parse") {
|
|
@@ -8335,7 +8462,7 @@ function wrapOpenAIv4(openai) {
|
|
|
8335
8462
|
});
|
|
8336
8463
|
}
|
|
8337
8464
|
function logCompletionResponse(startTime, response, span) {
|
|
8338
|
-
const metrics = parseMetricsFromUsage(_optionalChain([response, 'optionalAccess',
|
|
8465
|
+
const metrics = parseMetricsFromUsage(_optionalChain([response, 'optionalAccess', _115 => _115.usage]));
|
|
8339
8466
|
metrics.time_to_first_token = getCurrentUnixTimestamp() - startTime;
|
|
8340
8467
|
span.log({
|
|
8341
8468
|
output: response.choices,
|
|
@@ -8408,13 +8535,13 @@ function wrapBetaChatCompletionStream(completion) {
|
|
|
8408
8535
|
var LEGACY_CACHED_HEADER = "x-cached";
|
|
8409
8536
|
var X_CACHED_HEADER = "x-bt-cached";
|
|
8410
8537
|
function parseCachedHeader(value) {
|
|
8411
|
-
return
|
|
8538
|
+
return isEmpty2(value) ? void 0 : ["true", "hit"].includes(value.toLowerCase()) ? 1 : 0;
|
|
8412
8539
|
}
|
|
8413
8540
|
function logHeaders(response, span) {
|
|
8414
8541
|
const cachedHeader = response.headers.get(X_CACHED_HEADER);
|
|
8415
|
-
if (
|
|
8542
|
+
if (isEmpty2(cachedHeader)) {
|
|
8416
8543
|
const legacyCacheHeader = response.headers.get(LEGACY_CACHED_HEADER);
|
|
8417
|
-
if (!
|
|
8544
|
+
if (!isEmpty2(legacyCacheHeader)) {
|
|
8418
8545
|
span.log({
|
|
8419
8546
|
metrics: {
|
|
8420
8547
|
cached: parseCachedHeader(legacyCacheHeader)
|
|
@@ -8565,7 +8692,7 @@ function parseChatCompletionParams(params) {
|
|
|
8565
8692
|
function processEmbeddingResponse(result, span) {
|
|
8566
8693
|
span.log({
|
|
8567
8694
|
output: { embedding_length: result.data[0].embedding.length },
|
|
8568
|
-
metrics: parseMetricsFromUsage(_optionalChain([result, 'optionalAccess',
|
|
8695
|
+
metrics: parseMetricsFromUsage(_optionalChain([result, 'optionalAccess', _116 => _116.usage]))
|
|
8569
8696
|
});
|
|
8570
8697
|
}
|
|
8571
8698
|
function processModerationResponse(result, span) {
|
|
@@ -8595,10 +8722,10 @@ function postprocessStreamingResults(allResults) {
|
|
|
8595
8722
|
if (result.usage) {
|
|
8596
8723
|
metrics = {
|
|
8597
8724
|
...metrics,
|
|
8598
|
-
...parseMetricsFromUsage(_optionalChain([result, 'optionalAccess',
|
|
8725
|
+
...parseMetricsFromUsage(_optionalChain([result, 'optionalAccess', _117 => _117.usage]))
|
|
8599
8726
|
};
|
|
8600
8727
|
}
|
|
8601
|
-
const delta = _optionalChain([result, 'access',
|
|
8728
|
+
const delta = _optionalChain([result, 'access', _118 => _118.choices, 'optionalAccess', _119 => _119[0], 'optionalAccess', _120 => _120.delta]);
|
|
8602
8729
|
if (!delta) {
|
|
8603
8730
|
continue;
|
|
8604
8731
|
}
|
|
@@ -8924,7 +9051,7 @@ var resolveModel = (model, ai) => {
|
|
|
8924
9051
|
if (typeof model !== "string") {
|
|
8925
9052
|
return model;
|
|
8926
9053
|
}
|
|
8927
|
-
const provider = _nullishCoalesce(_nullishCoalesce(globalThis.AI_SDK_DEFAULT_PROVIDER, () => ( _optionalChain([ai, 'optionalAccess',
|
|
9054
|
+
const provider = _nullishCoalesce(_nullishCoalesce(globalThis.AI_SDK_DEFAULT_PROVIDER, () => ( _optionalChain([ai, 'optionalAccess', _121 => _121.gateway]))), () => ( null));
|
|
8928
9055
|
if (provider && typeof provider.languageModel === "function") {
|
|
8929
9056
|
return provider.languageModel(model);
|
|
8930
9057
|
}
|
|
@@ -8939,7 +9066,7 @@ var wrapModel = (model, ai) => {
|
|
|
8939
9066
|
return resolvedModel;
|
|
8940
9067
|
}
|
|
8941
9068
|
const originalDoGenerate = resolvedModel.doGenerate.bind(resolvedModel);
|
|
8942
|
-
const originalDoStream = _optionalChain([resolvedModel, 'access',
|
|
9069
|
+
const originalDoStream = _optionalChain([resolvedModel, 'access', _122 => _122.doStream, 'optionalAccess', _123 => _123.bind, 'call', _124 => _124(resolvedModel)]);
|
|
8943
9070
|
const wrappedDoGenerate = async (options) => {
|
|
8944
9071
|
return traced(
|
|
8945
9072
|
async (span) => {
|
|
@@ -9022,9 +9149,9 @@ var wrapModel = (model, ai) => {
|
|
|
9022
9149
|
case "raw":
|
|
9023
9150
|
if (chunk.rawValue) {
|
|
9024
9151
|
const rawVal = chunk.rawValue;
|
|
9025
|
-
if (_optionalChain([rawVal, 'access',
|
|
9152
|
+
if (_optionalChain([rawVal, 'access', _125 => _125.delta, 'optionalAccess', _126 => _126.content])) {
|
|
9026
9153
|
text += rawVal.delta.content;
|
|
9027
|
-
} else if (_optionalChain([rawVal, 'access',
|
|
9154
|
+
} else if (_optionalChain([rawVal, 'access', _127 => _127.choices, 'optionalAccess', _128 => _128[0], 'optionalAccess', _129 => _129.delta, 'optionalAccess', _130 => _130.content])) {
|
|
9028
9155
|
text += rawVal.choices[0].delta.content;
|
|
9029
9156
|
} else if (typeof rawVal.text === "string") {
|
|
9030
9157
|
text += rawVal.text;
|
|
@@ -9146,10 +9273,10 @@ var makeStreamTextWrapper = (name, options, streamText, aiSDK) => {
|
|
|
9146
9273
|
}
|
|
9147
9274
|
});
|
|
9148
9275
|
}
|
|
9149
|
-
_optionalChain([params, 'access',
|
|
9276
|
+
_optionalChain([params, 'access', _131 => _131.onChunk, 'optionalCall', _132 => _132(chunk)]);
|
|
9150
9277
|
},
|
|
9151
9278
|
onFinish: async (event) => {
|
|
9152
|
-
_optionalChain([params, 'access',
|
|
9279
|
+
_optionalChain([params, 'access', _133 => _133.onFinish, 'optionalCall', _134 => _134(event)]);
|
|
9153
9280
|
span.log({
|
|
9154
9281
|
output: await processOutput(event, options.denyOutputPaths),
|
|
9155
9282
|
metrics: extractTokenMetrics(event)
|
|
@@ -9157,7 +9284,7 @@ var makeStreamTextWrapper = (name, options, streamText, aiSDK) => {
|
|
|
9157
9284
|
span.end();
|
|
9158
9285
|
},
|
|
9159
9286
|
onError: async (err) => {
|
|
9160
|
-
_optionalChain([params, 'access',
|
|
9287
|
+
_optionalChain([params, 'access', _135 => _135.onError, 'optionalCall', _136 => _136(err)]);
|
|
9161
9288
|
span.log({
|
|
9162
9289
|
error: serializeError(err)
|
|
9163
9290
|
});
|
|
@@ -9244,10 +9371,10 @@ var wrapStreamObject = (streamObject, options = {}, aiSDK) => {
|
|
|
9244
9371
|
}
|
|
9245
9372
|
});
|
|
9246
9373
|
}
|
|
9247
|
-
_optionalChain([params, 'access',
|
|
9374
|
+
_optionalChain([params, 'access', _137 => _137.onChunk, 'optionalCall', _138 => _138(chunk)]);
|
|
9248
9375
|
},
|
|
9249
9376
|
onFinish: async (event) => {
|
|
9250
|
-
_optionalChain([params, 'access',
|
|
9377
|
+
_optionalChain([params, 'access', _139 => _139.onFinish, 'optionalCall', _140 => _140(event)]);
|
|
9251
9378
|
span.log({
|
|
9252
9379
|
output: await processOutput(event, options.denyOutputPaths),
|
|
9253
9380
|
metrics: extractTokenMetrics(event)
|
|
@@ -9255,7 +9382,7 @@ var wrapStreamObject = (streamObject, options = {}, aiSDK) => {
|
|
|
9255
9382
|
span.end();
|
|
9256
9383
|
},
|
|
9257
9384
|
onError: async (err) => {
|
|
9258
|
-
_optionalChain([params, 'access',
|
|
9385
|
+
_optionalChain([params, 'access', _141 => _141.onError, 'optionalCall', _142 => _142(err)]);
|
|
9259
9386
|
span.log({
|
|
9260
9387
|
error: serializeError(err)
|
|
9261
9388
|
});
|
|
@@ -9303,7 +9430,7 @@ var wrapStreamObject = (streamObject, options = {}, aiSDK) => {
|
|
|
9303
9430
|
};
|
|
9304
9431
|
var wrapTools = (tools) => {
|
|
9305
9432
|
if (!tools) return tools;
|
|
9306
|
-
const inferName = (tool,
|
|
9433
|
+
const inferName = (tool, fallback2) => tool && (tool.name || tool.toolName || tool.id) || fallback2;
|
|
9307
9434
|
if (Array.isArray(tools)) {
|
|
9308
9435
|
return tools.map((tool, idx) => {
|
|
9309
9436
|
const name = inferName(tool, `tool[${idx}]`);
|
|
@@ -9392,7 +9519,7 @@ var serializeError = (error) => {
|
|
|
9392
9519
|
return String(error);
|
|
9393
9520
|
};
|
|
9394
9521
|
var serializeModel = (model) => {
|
|
9395
|
-
return typeof model === "string" ? model : _optionalChain([model, 'optionalAccess',
|
|
9522
|
+
return typeof model === "string" ? model : _optionalChain([model, 'optionalAccess', _143 => _143.modelId]);
|
|
9396
9523
|
};
|
|
9397
9524
|
var isZodSchema = (value) => {
|
|
9398
9525
|
return value != null && typeof value === "object" && "_def" in value && typeof value._def === "object";
|
|
@@ -9539,7 +9666,7 @@ var convertImageToAttachment = (image, explicitMimeType) => {
|
|
|
9539
9666
|
try {
|
|
9540
9667
|
if (typeof image === "string" && image.startsWith("data:")) {
|
|
9541
9668
|
const [mimeTypeSection, base64Data] = image.split(",");
|
|
9542
|
-
const mimeType = _optionalChain([mimeTypeSection, 'access',
|
|
9669
|
+
const mimeType = _optionalChain([mimeTypeSection, 'access', _144 => _144.match, 'call', _145 => _145(/data:(.*?);/), 'optionalAccess', _146 => _146[1]]);
|
|
9543
9670
|
if (mimeType && base64Data) {
|
|
9544
9671
|
const blob = convertDataToBlob(base64Data, mimeType);
|
|
9545
9672
|
if (blob) {
|
|
@@ -9698,7 +9825,7 @@ var convertFileToAttachment = (file, index) => {
|
|
|
9698
9825
|
};
|
|
9699
9826
|
function extractTokenMetrics(result) {
|
|
9700
9827
|
const metrics = {};
|
|
9701
|
-
const usage = _optionalChain([result, 'optionalAccess',
|
|
9828
|
+
const usage = _optionalChain([result, 'optionalAccess', _147 => _147.usage]);
|
|
9702
9829
|
if (!usage) {
|
|
9703
9830
|
return metrics;
|
|
9704
9831
|
}
|
|
@@ -9815,6 +9942,279 @@ var omit = (obj, paths) => {
|
|
|
9815
9942
|
return result;
|
|
9816
9943
|
};
|
|
9817
9944
|
|
|
9945
|
+
// src/wrappers/ai-sdk/deprecated/wrapAISDKModel.ts
|
|
9946
|
+
function wrapAISDKModel(model) {
|
|
9947
|
+
const m = model;
|
|
9948
|
+
if (_optionalChain([m, 'optionalAccess', _148 => _148.specificationVersion]) === "v1" && typeof _optionalChain([m, 'optionalAccess', _149 => _149.provider]) === "string" && typeof _optionalChain([m, 'optionalAccess', _150 => _150.modelId]) === "string") {
|
|
9949
|
+
return new BraintrustLanguageModelWrapper(m);
|
|
9950
|
+
} else {
|
|
9951
|
+
console.warn("Unsupported AI SDK model. Not wrapping.");
|
|
9952
|
+
return model;
|
|
9953
|
+
}
|
|
9954
|
+
}
|
|
9955
|
+
var BraintrustLanguageModelWrapper = class {
|
|
9956
|
+
constructor(model) {
|
|
9957
|
+
this.model = model;
|
|
9958
|
+
if (typeof this.model.supportsUrl === "function") {
|
|
9959
|
+
this.supportsUrl = (url) => this.model.supportsUrl(url);
|
|
9960
|
+
}
|
|
9961
|
+
}
|
|
9962
|
+
|
|
9963
|
+
get specificationVersion() {
|
|
9964
|
+
return this.model.specificationVersion;
|
|
9965
|
+
}
|
|
9966
|
+
get provider() {
|
|
9967
|
+
return this.model.provider;
|
|
9968
|
+
}
|
|
9969
|
+
get modelId() {
|
|
9970
|
+
return this.model.modelId;
|
|
9971
|
+
}
|
|
9972
|
+
get defaultObjectGenerationMode() {
|
|
9973
|
+
return this.model.defaultObjectGenerationMode;
|
|
9974
|
+
}
|
|
9975
|
+
get supportsImageUrls() {
|
|
9976
|
+
return this.model.supportsImageUrls;
|
|
9977
|
+
}
|
|
9978
|
+
get supportsStructuredOutputs() {
|
|
9979
|
+
return this.model.supportsStructuredOutputs;
|
|
9980
|
+
}
|
|
9981
|
+
// For the first cut, do not support custom span_info arguments. We can
|
|
9982
|
+
// propagate those via async local storage
|
|
9983
|
+
async doGenerate(options) {
|
|
9984
|
+
const span = startSpan({
|
|
9985
|
+
name: "Chat Completion",
|
|
9986
|
+
spanAttributes: {
|
|
9987
|
+
type: "llm"
|
|
9988
|
+
}
|
|
9989
|
+
});
|
|
9990
|
+
const { prompt, mode, ...rest } = options;
|
|
9991
|
+
const startTime = getCurrentUnixTimestamp();
|
|
9992
|
+
try {
|
|
9993
|
+
const ret = await this.model.doGenerate(options);
|
|
9994
|
+
span.log({
|
|
9995
|
+
input: postProcessPrompt(prompt),
|
|
9996
|
+
metadata: {
|
|
9997
|
+
model: this.modelId,
|
|
9998
|
+
...rest,
|
|
9999
|
+
..."tools" in mode && mode.tools ? { tools: convertTools(mode.tools) } : "tool" in mode && mode.tool ? { tools: convertTools([mode.tool]) } : {}
|
|
10000
|
+
},
|
|
10001
|
+
output: postProcessOutput(ret.text, ret.toolCalls, ret.finishReason),
|
|
10002
|
+
metrics: {
|
|
10003
|
+
time_to_first_token: getCurrentUnixTimestamp() - startTime,
|
|
10004
|
+
tokens: !isEmpty2(ret.usage) ? ret.usage.promptTokens + ret.usage.completionTokens : void 0,
|
|
10005
|
+
prompt_tokens: _optionalChain([ret, 'access', _151 => _151.usage, 'optionalAccess', _152 => _152.promptTokens]),
|
|
10006
|
+
completion_tokens: _optionalChain([ret, 'access', _153 => _153.usage, 'optionalAccess', _154 => _154.completionTokens]),
|
|
10007
|
+
cached: parseCachedHeader(
|
|
10008
|
+
_nullishCoalesce(_optionalChain([ret, 'access', _155 => _155.rawResponse, 'optionalAccess', _156 => _156.headers, 'optionalAccess', _157 => _157[X_CACHED_HEADER]]), () => ( _optionalChain([ret, 'access', _158 => _158.rawResponse, 'optionalAccess', _159 => _159.headers, 'optionalAccess', _160 => _160[LEGACY_CACHED_HEADER]])))
|
|
10009
|
+
)
|
|
10010
|
+
}
|
|
10011
|
+
});
|
|
10012
|
+
return ret;
|
|
10013
|
+
} finally {
|
|
10014
|
+
span.end();
|
|
10015
|
+
}
|
|
10016
|
+
}
|
|
10017
|
+
async doStream(options) {
|
|
10018
|
+
const { prompt, mode, ...rest } = options;
|
|
10019
|
+
const startTime = getCurrentUnixTimestamp();
|
|
10020
|
+
const span = startSpan({
|
|
10021
|
+
name: "Chat Completion",
|
|
10022
|
+
spanAttributes: {
|
|
10023
|
+
type: "llm"
|
|
10024
|
+
}
|
|
10025
|
+
});
|
|
10026
|
+
span.log({
|
|
10027
|
+
input: postProcessPrompt(prompt),
|
|
10028
|
+
metadata: {
|
|
10029
|
+
model: this.modelId,
|
|
10030
|
+
...rest,
|
|
10031
|
+
..."tools" in mode && mode.tools ? { tools: convertTools(mode.tools) } : "tool" in mode && mode.tool ? { tools: convertTools([mode.tool]) } : {}
|
|
10032
|
+
}
|
|
10033
|
+
});
|
|
10034
|
+
let ended = false;
|
|
10035
|
+
const end = () => {
|
|
10036
|
+
if (!ended) {
|
|
10037
|
+
span.end();
|
|
10038
|
+
ended = true;
|
|
10039
|
+
}
|
|
10040
|
+
};
|
|
10041
|
+
try {
|
|
10042
|
+
const ret = await this.model.doStream(options);
|
|
10043
|
+
let time_to_first_token = void 0;
|
|
10044
|
+
let usage = void 0;
|
|
10045
|
+
let fullText = void 0;
|
|
10046
|
+
const toolCalls = {};
|
|
10047
|
+
let finishReason = void 0;
|
|
10048
|
+
return {
|
|
10049
|
+
...ret,
|
|
10050
|
+
stream: ret.stream.pipeThrough(
|
|
10051
|
+
new TransformStream({
|
|
10052
|
+
transform(chunk, controller) {
|
|
10053
|
+
if (time_to_first_token === void 0) {
|
|
10054
|
+
time_to_first_token = getCurrentUnixTimestamp() - startTime;
|
|
10055
|
+
span.log({ metrics: { time_to_first_token } });
|
|
10056
|
+
}
|
|
10057
|
+
switch (chunk.type) {
|
|
10058
|
+
case "text-delta":
|
|
10059
|
+
if (fullText === void 0) {
|
|
10060
|
+
fullText = "";
|
|
10061
|
+
}
|
|
10062
|
+
fullText += chunk.textDelta;
|
|
10063
|
+
break;
|
|
10064
|
+
case "tool-call":
|
|
10065
|
+
toolCalls[chunk.toolCallId] = {
|
|
10066
|
+
toolCallType: chunk.toolCallType,
|
|
10067
|
+
toolCallId: chunk.toolCallId,
|
|
10068
|
+
toolName: chunk.toolName,
|
|
10069
|
+
args: chunk.args
|
|
10070
|
+
};
|
|
10071
|
+
break;
|
|
10072
|
+
case "tool-call-delta":
|
|
10073
|
+
if (toolCalls[chunk.toolCallId] === void 0) {
|
|
10074
|
+
toolCalls[chunk.toolCallId] = {
|
|
10075
|
+
toolCallType: chunk.toolCallType,
|
|
10076
|
+
toolCallId: chunk.toolCallId,
|
|
10077
|
+
toolName: chunk.toolName,
|
|
10078
|
+
args: ""
|
|
10079
|
+
};
|
|
10080
|
+
}
|
|
10081
|
+
toolCalls[chunk.toolCallId].args += chunk.argsTextDelta;
|
|
10082
|
+
break;
|
|
10083
|
+
case "finish":
|
|
10084
|
+
usage = chunk.usage;
|
|
10085
|
+
finishReason = chunk.finishReason;
|
|
10086
|
+
break;
|
|
10087
|
+
}
|
|
10088
|
+
controller.enqueue(chunk);
|
|
10089
|
+
},
|
|
10090
|
+
async flush(controller) {
|
|
10091
|
+
span.log({
|
|
10092
|
+
output: postProcessOutput(
|
|
10093
|
+
fullText,
|
|
10094
|
+
Object.keys(toolCalls).length > 0 ? Object.values(toolCalls) : void 0,
|
|
10095
|
+
finishReason
|
|
10096
|
+
),
|
|
10097
|
+
metrics: {
|
|
10098
|
+
time_to_first_token,
|
|
10099
|
+
tokens: !isEmpty2(usage) ? usage.promptTokens + usage.completionTokens : void 0,
|
|
10100
|
+
prompt_tokens: _optionalChain([usage, 'optionalAccess', _161 => _161.promptTokens]),
|
|
10101
|
+
completion_tokens: _optionalChain([usage, 'optionalAccess', _162 => _162.completionTokens]),
|
|
10102
|
+
cached: parseCachedHeader(
|
|
10103
|
+
_nullishCoalesce(_optionalChain([ret, 'access', _163 => _163.rawResponse, 'optionalAccess', _164 => _164.headers, 'optionalAccess', _165 => _165[X_CACHED_HEADER]]), () => ( _optionalChain([ret, 'access', _166 => _166.rawResponse, 'optionalAccess', _167 => _167.headers, 'optionalAccess', _168 => _168[LEGACY_CACHED_HEADER]])))
|
|
10104
|
+
)
|
|
10105
|
+
}
|
|
10106
|
+
});
|
|
10107
|
+
end();
|
|
10108
|
+
controller.terminate();
|
|
10109
|
+
}
|
|
10110
|
+
})
|
|
10111
|
+
)
|
|
10112
|
+
};
|
|
10113
|
+
} finally {
|
|
10114
|
+
end();
|
|
10115
|
+
}
|
|
10116
|
+
}
|
|
10117
|
+
};
|
|
10118
|
+
function convertTools(tools) {
|
|
10119
|
+
return tools.map((tool) => {
|
|
10120
|
+
const { type: _, ...rest } = tool;
|
|
10121
|
+
return {
|
|
10122
|
+
type: tool.type,
|
|
10123
|
+
function: rest
|
|
10124
|
+
};
|
|
10125
|
+
});
|
|
10126
|
+
}
|
|
10127
|
+
function postProcessPrompt(prompt) {
|
|
10128
|
+
return prompt.flatMap((message) => {
|
|
10129
|
+
switch (message.role) {
|
|
10130
|
+
case "system":
|
|
10131
|
+
return [
|
|
10132
|
+
{
|
|
10133
|
+
role: "system",
|
|
10134
|
+
content: message.content
|
|
10135
|
+
}
|
|
10136
|
+
];
|
|
10137
|
+
case "assistant":
|
|
10138
|
+
const textPart = message.content.find(
|
|
10139
|
+
(part) => part.type === "text"
|
|
10140
|
+
);
|
|
10141
|
+
const toolCallParts = message.content.filter(
|
|
10142
|
+
(part) => part.type === "tool-call"
|
|
10143
|
+
);
|
|
10144
|
+
return [
|
|
10145
|
+
{
|
|
10146
|
+
role: "assistant",
|
|
10147
|
+
content: _optionalChain([textPart, 'optionalAccess', _169 => _169.text]),
|
|
10148
|
+
...toolCallParts.length > 0 ? {
|
|
10149
|
+
tool_calls: toolCallParts.map((part) => ({
|
|
10150
|
+
id: part.toolCallId,
|
|
10151
|
+
function: {
|
|
10152
|
+
name: part.toolName,
|
|
10153
|
+
arguments: JSON.stringify(part.args)
|
|
10154
|
+
},
|
|
10155
|
+
type: "function"
|
|
10156
|
+
}))
|
|
10157
|
+
} : {}
|
|
10158
|
+
}
|
|
10159
|
+
];
|
|
10160
|
+
case "user":
|
|
10161
|
+
return [
|
|
10162
|
+
{
|
|
10163
|
+
role: "user",
|
|
10164
|
+
content: message.content.map((part) => {
|
|
10165
|
+
switch (part.type) {
|
|
10166
|
+
case "text":
|
|
10167
|
+
return {
|
|
10168
|
+
type: "text",
|
|
10169
|
+
text: part.text,
|
|
10170
|
+
...part.providerMetadata ? { providerMetadata: part.providerMetadata } : {}
|
|
10171
|
+
};
|
|
10172
|
+
case "image":
|
|
10173
|
+
return {
|
|
10174
|
+
type: "image_url",
|
|
10175
|
+
image_url: {
|
|
10176
|
+
url: part.image.toString(),
|
|
10177
|
+
...part.providerMetadata ? { providerMetadata: part.providerMetadata } : {}
|
|
10178
|
+
}
|
|
10179
|
+
};
|
|
10180
|
+
default:
|
|
10181
|
+
return part;
|
|
10182
|
+
}
|
|
10183
|
+
})
|
|
10184
|
+
}
|
|
10185
|
+
];
|
|
10186
|
+
case "tool":
|
|
10187
|
+
return message.content.map((part) => ({
|
|
10188
|
+
role: "tool",
|
|
10189
|
+
tool_call_id: part.toolCallId,
|
|
10190
|
+
content: JSON.stringify(part.result)
|
|
10191
|
+
}));
|
|
10192
|
+
}
|
|
10193
|
+
});
|
|
10194
|
+
}
|
|
10195
|
+
function postProcessOutput(text, toolCalls, finishReason) {
|
|
10196
|
+
return [
|
|
10197
|
+
{
|
|
10198
|
+
index: 0,
|
|
10199
|
+
message: {
|
|
10200
|
+
role: "assistant",
|
|
10201
|
+
content: _nullishCoalesce(text, () => ( "")),
|
|
10202
|
+
...toolCalls && toolCalls.length > 0 ? {
|
|
10203
|
+
tool_calls: toolCalls.map((toolCall) => ({
|
|
10204
|
+
id: toolCall.toolCallId,
|
|
10205
|
+
function: {
|
|
10206
|
+
name: toolCall.toolName,
|
|
10207
|
+
arguments: toolCall.args
|
|
10208
|
+
},
|
|
10209
|
+
type: "function"
|
|
10210
|
+
}))
|
|
10211
|
+
} : {}
|
|
10212
|
+
},
|
|
10213
|
+
finish_reason: finishReason
|
|
10214
|
+
}
|
|
10215
|
+
];
|
|
10216
|
+
}
|
|
10217
|
+
|
|
9818
10218
|
// src/wrappers/anthropic-tokens-util.ts
|
|
9819
10219
|
function finalizeAnthropicTokens(metrics) {
|
|
9820
10220
|
const prompt_tokens = (metrics.prompt_tokens || 0) + (metrics.prompt_cached_tokens || 0) + (metrics.prompt_cache_creation_tokens || 0);
|
|
@@ -9837,23 +10237,23 @@ function extractAnthropicCacheTokens(cacheReadTokens = 0, cacheCreationTokens =
|
|
|
9837
10237
|
|
|
9838
10238
|
// src/wrappers/ai-sdk/deprecated/BraintrustMiddleware.ts
|
|
9839
10239
|
function detectProviderFromResult(result) {
|
|
9840
|
-
if (!_optionalChain([result, 'optionalAccess',
|
|
10240
|
+
if (!_optionalChain([result, 'optionalAccess', _170 => _170.providerMetadata])) {
|
|
9841
10241
|
return void 0;
|
|
9842
10242
|
}
|
|
9843
10243
|
const keys = Object.keys(result.providerMetadata);
|
|
9844
|
-
return _optionalChain([keys, 'optionalAccess',
|
|
10244
|
+
return _optionalChain([keys, 'optionalAccess', _171 => _171.at, 'call', _172 => _172(0)]);
|
|
9845
10245
|
}
|
|
9846
10246
|
function extractModelFromResult(result) {
|
|
9847
|
-
if (_optionalChain([result, 'optionalAccess',
|
|
10247
|
+
if (_optionalChain([result, 'optionalAccess', _173 => _173.response, 'optionalAccess', _174 => _174.modelId])) {
|
|
9848
10248
|
return result.response.modelId;
|
|
9849
10249
|
}
|
|
9850
|
-
if (_optionalChain([result, 'optionalAccess',
|
|
10250
|
+
if (_optionalChain([result, 'optionalAccess', _175 => _175.request, 'optionalAccess', _176 => _176.body, 'optionalAccess', _177 => _177.model])) {
|
|
9851
10251
|
return result.request.body.model;
|
|
9852
10252
|
}
|
|
9853
10253
|
return void 0;
|
|
9854
10254
|
}
|
|
9855
10255
|
function extractModelFromWrapGenerateCallback(model) {
|
|
9856
|
-
return _optionalChain([model, 'optionalAccess',
|
|
10256
|
+
return _optionalChain([model, 'optionalAccess', _178 => _178.modelId]);
|
|
9857
10257
|
}
|
|
9858
10258
|
function camelToSnake(str) {
|
|
9859
10259
|
return str.replace(/[A-Z]/g, (letter) => `_${letter.toLowerCase()}`);
|
|
@@ -9898,7 +10298,7 @@ function normalizeUsageMetrics(usage, provider, providerMetadata) {
|
|
|
9898
10298
|
metrics.prompt_cached_tokens = cachedInputTokens;
|
|
9899
10299
|
}
|
|
9900
10300
|
if (provider === "anthropic") {
|
|
9901
|
-
const anthropicMetadata = _optionalChain([providerMetadata, 'optionalAccess',
|
|
10301
|
+
const anthropicMetadata = _optionalChain([providerMetadata, 'optionalAccess', _179 => _179.anthropic]);
|
|
9902
10302
|
if (anthropicMetadata) {
|
|
9903
10303
|
const cacheReadTokens = getNumberProperty(anthropicMetadata.usage, "cache_read_input_tokens") || 0;
|
|
9904
10304
|
const cacheCreationTokens = getNumberProperty(
|
|
@@ -9924,7 +10324,7 @@ function buildAssistantOutputWithToolCalls(result, toolCalls) {
|
|
|
9924
10324
|
{
|
|
9925
10325
|
index: 0,
|
|
9926
10326
|
logprobs: null,
|
|
9927
|
-
finish_reason: _nullishCoalesce(normalizeFinishReason(_optionalChain([result, 'optionalAccess',
|
|
10327
|
+
finish_reason: _nullishCoalesce(normalizeFinishReason(_optionalChain([result, 'optionalAccess', _180 => _180.finishReason])), () => ( (toolCalls.length ? "tool_calls" : void 0))),
|
|
9928
10328
|
message: {
|
|
9929
10329
|
role: "assistant",
|
|
9930
10330
|
tool_calls: toolCalls.length > 0 ? toolCalls : void 0
|
|
@@ -9937,7 +10337,7 @@ function extractToolCallsFromSteps(steps) {
|
|
|
9937
10337
|
if (!Array.isArray(steps)) return toolCalls;
|
|
9938
10338
|
let idx = 0;
|
|
9939
10339
|
for (const step of steps) {
|
|
9940
|
-
const blocks = _optionalChain([step, 'optionalAccess',
|
|
10340
|
+
const blocks = _optionalChain([step, 'optionalAccess', _181 => _181.content]);
|
|
9941
10341
|
if (!Array.isArray(blocks)) continue;
|
|
9942
10342
|
for (const block of blocks) {
|
|
9943
10343
|
if (block && typeof block === "object" && block.type === "tool-call") {
|
|
@@ -9960,7 +10360,7 @@ function extractToolCallsFromBlocks(blocks) {
|
|
|
9960
10360
|
return extractToolCallsFromSteps([{ content: blocks }]);
|
|
9961
10361
|
}
|
|
9962
10362
|
function extractInput(params) {
|
|
9963
|
-
return _nullishCoalesce(_nullishCoalesce(_optionalChain([params, 'optionalAccess',
|
|
10363
|
+
return _nullishCoalesce(_nullishCoalesce(_optionalChain([params, 'optionalAccess', _182 => _182.prompt]), () => ( _optionalChain([params, 'optionalAccess', _183 => _183.messages]))), () => ( _optionalChain([params, 'optionalAccess', _184 => _184.system])));
|
|
9964
10364
|
}
|
|
9965
10365
|
var V2_EXCLUDE_KEYS = /* @__PURE__ */ new Set([
|
|
9966
10366
|
"prompt",
|
|
@@ -9984,16 +10384,16 @@ function BraintrustMiddleware(config = {}) {
|
|
|
9984
10384
|
const rawInput = extractInput(params);
|
|
9985
10385
|
const processedInput = processInputAttachments(rawInput);
|
|
9986
10386
|
const spanArgs = {
|
|
9987
|
-
name: _optionalChain([config, 'access',
|
|
10387
|
+
name: _optionalChain([config, 'access', _185 => _185.spanInfo, 'optionalAccess', _186 => _186.name]) || "ai-sdk.doGenerate",
|
|
9988
10388
|
spanAttributes: {
|
|
9989
10389
|
type: "llm" /* LLM */,
|
|
9990
|
-
..._optionalChain([config, 'access',
|
|
10390
|
+
..._optionalChain([config, 'access', _187 => _187.spanInfo, 'optionalAccess', _188 => _188.spanAttributes]) || {}
|
|
9991
10391
|
},
|
|
9992
10392
|
event: {
|
|
9993
10393
|
input: processedInput,
|
|
9994
10394
|
metadata: {
|
|
9995
10395
|
...extractModelParameters(params, V2_EXCLUDE_KEYS),
|
|
9996
|
-
..._optionalChain([config, 'access',
|
|
10396
|
+
..._optionalChain([config, 'access', _189 => _189.spanInfo, 'optionalAccess', _190 => _190.metadata]) || {}
|
|
9997
10397
|
}
|
|
9998
10398
|
}
|
|
9999
10399
|
};
|
|
@@ -10019,12 +10419,12 @@ function BraintrustMiddleware(config = {}) {
|
|
|
10019
10419
|
metadata.model = modelId;
|
|
10020
10420
|
}
|
|
10021
10421
|
}
|
|
10022
|
-
let toolCalls = extractToolCallsFromSteps(_optionalChain([result, 'optionalAccess',
|
|
10422
|
+
let toolCalls = extractToolCallsFromSteps(_optionalChain([result, 'optionalAccess', _191 => _191.steps]));
|
|
10023
10423
|
if (!toolCalls || toolCalls.length === 0) {
|
|
10024
|
-
toolCalls = extractToolCallsFromBlocks(_optionalChain([result, 'optionalAccess',
|
|
10424
|
+
toolCalls = extractToolCallsFromBlocks(_optionalChain([result, 'optionalAccess', _192 => _192.content]));
|
|
10025
10425
|
}
|
|
10026
10426
|
span.log({
|
|
10027
|
-
output: toolCalls.length > 0 ? buildAssistantOutputWithToolCalls(result, toolCalls) : _optionalChain([result, 'optionalAccess',
|
|
10427
|
+
output: toolCalls.length > 0 ? buildAssistantOutputWithToolCalls(result, toolCalls) : _optionalChain([result, 'optionalAccess', _193 => _193.content]),
|
|
10028
10428
|
metadata,
|
|
10029
10429
|
metrics: normalizeUsageMetrics(
|
|
10030
10430
|
result.usage,
|
|
@@ -10046,16 +10446,16 @@ function BraintrustMiddleware(config = {}) {
|
|
|
10046
10446
|
const rawInput = extractInput(params);
|
|
10047
10447
|
const processedInput = processInputAttachments(rawInput);
|
|
10048
10448
|
const spanArgs = {
|
|
10049
|
-
name: _optionalChain([config, 'access',
|
|
10449
|
+
name: _optionalChain([config, 'access', _194 => _194.spanInfo, 'optionalAccess', _195 => _195.name]) || "ai-sdk.doStream",
|
|
10050
10450
|
spanAttributes: {
|
|
10051
10451
|
type: "llm" /* LLM */,
|
|
10052
|
-
..._optionalChain([config, 'access',
|
|
10452
|
+
..._optionalChain([config, 'access', _196 => _196.spanInfo, 'optionalAccess', _197 => _197.spanAttributes]) || {}
|
|
10053
10453
|
},
|
|
10054
10454
|
event: {
|
|
10055
10455
|
input: processedInput,
|
|
10056
10456
|
metadata: {
|
|
10057
10457
|
...extractModelParameters(params, V2_EXCLUDE_KEYS),
|
|
10058
|
-
..._optionalChain([config, 'access',
|
|
10458
|
+
..._optionalChain([config, 'access', _198 => _198.spanInfo, 'optionalAccess', _199 => _199.metadata]) || {}
|
|
10059
10459
|
}
|
|
10060
10460
|
}
|
|
10061
10461
|
};
|
|
@@ -10327,9 +10727,9 @@ function streamNextProxy(stream, sspan) {
|
|
|
10327
10727
|
return result;
|
|
10328
10728
|
}
|
|
10329
10729
|
const item = result.value;
|
|
10330
|
-
switch (_optionalChain([item, 'optionalAccess',
|
|
10730
|
+
switch (_optionalChain([item, 'optionalAccess', _200 => _200.type])) {
|
|
10331
10731
|
case "message_start":
|
|
10332
|
-
const msg = _optionalChain([item, 'optionalAccess',
|
|
10732
|
+
const msg = _optionalChain([item, 'optionalAccess', _201 => _201.message]);
|
|
10333
10733
|
if (msg) {
|
|
10334
10734
|
const event = parseEventFromMessage(msg);
|
|
10335
10735
|
totals = { ...totals, ...event.metrics };
|
|
@@ -10342,20 +10742,20 @@ function streamNextProxy(stream, sspan) {
|
|
|
10342
10742
|
}
|
|
10343
10743
|
break;
|
|
10344
10744
|
case "content_block_delta":
|
|
10345
|
-
if (_optionalChain([item, 'access',
|
|
10346
|
-
const text = _optionalChain([item, 'optionalAccess',
|
|
10745
|
+
if (_optionalChain([item, 'access', _202 => _202.delta, 'optionalAccess', _203 => _203.type]) === "text_delta") {
|
|
10746
|
+
const text = _optionalChain([item, 'optionalAccess', _204 => _204.delta, 'optionalAccess', _205 => _205.text]);
|
|
10347
10747
|
if (text) {
|
|
10348
10748
|
deltas.push(text);
|
|
10349
10749
|
}
|
|
10350
10750
|
}
|
|
10351
10751
|
break;
|
|
10352
10752
|
case "message_delta":
|
|
10353
|
-
const usage = _optionalChain([item, 'optionalAccess',
|
|
10753
|
+
const usage = _optionalChain([item, 'optionalAccess', _206 => _206.usage]);
|
|
10354
10754
|
if (usage) {
|
|
10355
10755
|
const metrics = parseMetricsFromUsage2(usage);
|
|
10356
10756
|
totals = { ...totals, ...metrics };
|
|
10357
10757
|
}
|
|
10358
|
-
const delta = _optionalChain([item, 'optionalAccess',
|
|
10758
|
+
const delta = _optionalChain([item, 'optionalAccess', _207 => _207.delta]);
|
|
10359
10759
|
if (delta) {
|
|
10360
10760
|
metadata = { ...metadata, ...delta };
|
|
10361
10761
|
}
|
|
@@ -10368,7 +10768,7 @@ function streamNextProxy(stream, sspan) {
|
|
|
10368
10768
|
}
|
|
10369
10769
|
function parseEventFromMessage(message) {
|
|
10370
10770
|
const output = message ? { role: message.role, content: message.content } : null;
|
|
10371
|
-
const metrics = parseMetricsFromUsage2(_optionalChain([message, 'optionalAccess',
|
|
10771
|
+
const metrics = parseMetricsFromUsage2(_optionalChain([message, 'optionalAccess', _208 => _208.usage]));
|
|
10372
10772
|
const metas = ["stop_reason", "stop_sequence"];
|
|
10373
10773
|
const metadata = {};
|
|
10374
10774
|
for (const m of metas) {
|
|
@@ -10515,7 +10915,7 @@ function wrapClaudeAgentQuery(queryFn, defaultThis) {
|
|
|
10515
10915
|
finalResults.push(finalMessageContent);
|
|
10516
10916
|
}
|
|
10517
10917
|
const lastMessage = currentMessages[currentMessages.length - 1];
|
|
10518
|
-
if (_optionalChain([lastMessage, 'optionalAccess',
|
|
10918
|
+
if (_optionalChain([lastMessage, 'optionalAccess', _209 => _209.message, 'optionalAccess', _210 => _210.usage])) {
|
|
10519
10919
|
const outputTokens = getNumberProperty2(lastMessage.message.usage, "output_tokens") || 0;
|
|
10520
10920
|
accumulatedOutputTokens += outputTokens;
|
|
10521
10921
|
}
|
|
@@ -10530,20 +10930,20 @@ function wrapClaudeAgentQuery(queryFn, defaultThis) {
|
|
|
10530
10930
|
);
|
|
10531
10931
|
for await (const message of generator) {
|
|
10532
10932
|
const currentTime = getCurrentUnixTimestamp();
|
|
10533
|
-
const messageId = _optionalChain([message, 'access',
|
|
10933
|
+
const messageId = _optionalChain([message, 'access', _211 => _211.message, 'optionalAccess', _212 => _212.id]);
|
|
10534
10934
|
if (messageId && messageId !== currentMessageId) {
|
|
10535
10935
|
await createLLMSpan();
|
|
10536
10936
|
currentMessageId = messageId;
|
|
10537
10937
|
currentMessageStartTime = currentTime;
|
|
10538
10938
|
}
|
|
10539
|
-
if (message.type === "assistant" && _optionalChain([message, 'access',
|
|
10939
|
+
if (message.type === "assistant" && _optionalChain([message, 'access', _213 => _213.message, 'optionalAccess', _214 => _214.usage])) {
|
|
10540
10940
|
currentMessages.push(message);
|
|
10541
10941
|
}
|
|
10542
10942
|
if (message.type === "result" && message.usage) {
|
|
10543
10943
|
finalUsageMetrics = _extractUsageFromMessage(message);
|
|
10544
10944
|
if (currentMessages.length > 0 && finalUsageMetrics.completion_tokens !== void 0) {
|
|
10545
10945
|
const lastMessage = currentMessages[currentMessages.length - 1];
|
|
10546
|
-
if (_optionalChain([lastMessage, 'optionalAccess',
|
|
10946
|
+
if (_optionalChain([lastMessage, 'optionalAccess', _215 => _215.message, 'optionalAccess', _216 => _216.usage])) {
|
|
10547
10947
|
const adjustedTokens = finalUsageMetrics.completion_tokens - accumulatedOutputTokens;
|
|
10548
10948
|
if (adjustedTokens >= 0) {
|
|
10549
10949
|
lastMessage.message.usage.output_tokens = adjustedTokens;
|
|
@@ -10624,7 +11024,7 @@ function _extractUsageFromMessage(message) {
|
|
|
10624
11024
|
const metrics = {};
|
|
10625
11025
|
let usage;
|
|
10626
11026
|
if (message.type === "assistant") {
|
|
10627
|
-
usage = _optionalChain([message, 'access',
|
|
11027
|
+
usage = _optionalChain([message, 'access', _217 => _217.message, 'optionalAccess', _218 => _218.usage]);
|
|
10628
11028
|
} else if (message.type === "result") {
|
|
10629
11029
|
usage = message.usage;
|
|
10630
11030
|
}
|
|
@@ -10656,14 +11056,14 @@ function _extractUsageFromMessage(message) {
|
|
|
10656
11056
|
async function _createLLMSpanForMessages(messages, prompt, conversationHistory, options, startTime, parentSpan) {
|
|
10657
11057
|
if (messages.length === 0) return void 0;
|
|
10658
11058
|
const lastMessage = messages[messages.length - 1];
|
|
10659
|
-
if (lastMessage.type !== "assistant" || !_optionalChain([lastMessage, 'access',
|
|
11059
|
+
if (lastMessage.type !== "assistant" || !_optionalChain([lastMessage, 'access', _219 => _219.message, 'optionalAccess', _220 => _220.usage])) {
|
|
10660
11060
|
return void 0;
|
|
10661
11061
|
}
|
|
10662
11062
|
const model = lastMessage.message.model || options.model;
|
|
10663
11063
|
const usage = _extractUsageFromMessage(lastMessage);
|
|
10664
11064
|
const input = _buildLLMInput(prompt, conversationHistory);
|
|
10665
11065
|
const outputs = messages.map(
|
|
10666
|
-
(m) => _optionalChain([m, 'access',
|
|
11066
|
+
(m) => _optionalChain([m, 'access', _221 => _221.message, 'optionalAccess', _222 => _222.content]) && _optionalChain([m, 'access', _223 => _223.message, 'optionalAccess', _224 => _224.role]) ? { content: m.message.content, role: m.message.role } : void 0
|
|
10667
11067
|
).filter((c) => c !== void 0);
|
|
10668
11068
|
await traced(
|
|
10669
11069
|
(llmSpan) => {
|
|
@@ -10683,7 +11083,7 @@ async function _createLLMSpanForMessages(messages, prompt, conversationHistory,
|
|
|
10683
11083
|
parent: parentSpan
|
|
10684
11084
|
}
|
|
10685
11085
|
);
|
|
10686
|
-
return _optionalChain([lastMessage, 'access',
|
|
11086
|
+
return _optionalChain([lastMessage, 'access', _225 => _225.message, 'optionalAccess', _226 => _226.content]) && _optionalChain([lastMessage, 'access', _227 => _227.message, 'optionalAccess', _228 => _228.role]) ? { content: lastMessage.message.content, role: lastMessage.message.role } : void 0;
|
|
10687
11087
|
}
|
|
10688
11088
|
function wrapClaudeAgentSDK(sdk) {
|
|
10689
11089
|
const cache = /* @__PURE__ */ new Map();
|
|
@@ -10973,7 +11373,7 @@ function serializePart(part) {
|
|
|
10973
11373
|
return part;
|
|
10974
11374
|
}
|
|
10975
11375
|
function serializeTools(params) {
|
|
10976
|
-
if (!_optionalChain([params, 'access',
|
|
11376
|
+
if (!_optionalChain([params, 'access', _229 => _229.config, 'optionalAccess', _230 => _230.tools])) {
|
|
10977
11377
|
return null;
|
|
10978
11378
|
}
|
|
10979
11379
|
try {
|
|
@@ -11056,7 +11456,7 @@ function aggregateGenerateContentChunks(chunks, start, firstTokenTime) {
|
|
|
11056
11456
|
}
|
|
11057
11457
|
if (chunk.candidates && Array.isArray(chunk.candidates)) {
|
|
11058
11458
|
for (const candidate of chunk.candidates) {
|
|
11059
|
-
if (_optionalChain([candidate, 'access',
|
|
11459
|
+
if (_optionalChain([candidate, 'access', _231 => _231.content, 'optionalAccess', _232 => _232.parts])) {
|
|
11060
11460
|
for (const part of candidate.content.parts) {
|
|
11061
11461
|
if (part.text !== void 0) {
|
|
11062
11462
|
if (part.thought) {
|
|
@@ -11087,7 +11487,7 @@ function aggregateGenerateContentChunks(chunks, start, firstTokenTime) {
|
|
|
11087
11487
|
parts.push({ text });
|
|
11088
11488
|
}
|
|
11089
11489
|
parts.push(...otherParts);
|
|
11090
|
-
if (parts.length > 0 && _optionalChain([lastResponse, 'optionalAccess',
|
|
11490
|
+
if (parts.length > 0 && _optionalChain([lastResponse, 'optionalAccess', _233 => _233.candidates])) {
|
|
11091
11491
|
const candidates = [];
|
|
11092
11492
|
for (const candidate of lastResponse.candidates) {
|
|
11093
11493
|
const candidateDict = {
|
|
@@ -11434,51 +11834,2272 @@ function unescapePath(path) {
|
|
|
11434
11834
|
}
|
|
11435
11835
|
var graph_framework_default = { createGraph };
|
|
11436
11836
|
|
|
11437
|
-
//
|
|
11438
|
-
|
|
11439
|
-
|
|
11440
|
-
|
|
11441
|
-
|
|
11442
|
-
|
|
11443
|
-
|
|
11444
|
-
|
|
11445
|
-
|
|
11446
|
-
|
|
11447
|
-
|
|
11448
|
-
|
|
11449
|
-
|
|
11450
|
-
|
|
11451
|
-
|
|
11452
|
-
|
|
11453
|
-
|
|
11454
|
-
|
|
11455
|
-
|
|
11456
|
-
|
|
11457
|
-
|
|
11458
|
-
|
|
11459
|
-
|
|
11460
|
-
|
|
11461
|
-
|
|
11462
|
-
|
|
11463
|
-
|
|
11464
|
-
|
|
11465
|
-
|
|
11466
|
-
|
|
11467
|
-
|
|
11468
|
-
|
|
11469
|
-
|
|
11470
|
-
|
|
11471
|
-
|
|
11472
|
-
|
|
11473
|
-
|
|
11474
|
-
|
|
11475
|
-
|
|
11476
|
-
|
|
11477
|
-
);
|
|
11478
|
-
|
|
11479
|
-
|
|
11480
|
-
|
|
11481
|
-
|
|
11837
|
+
// ../node_modules/async/dist/async.mjs
|
|
11838
|
+
function initialParams(fn) {
|
|
11839
|
+
return function(...args) {
|
|
11840
|
+
var callback = args.pop();
|
|
11841
|
+
return fn.call(this, args, callback);
|
|
11842
|
+
};
|
|
11843
|
+
}
|
|
11844
|
+
var hasQueueMicrotask = typeof queueMicrotask === "function" && queueMicrotask;
|
|
11845
|
+
var hasSetImmediate = typeof setImmediate === "function" && setImmediate;
|
|
11846
|
+
var hasNextTick = typeof process === "object" && typeof process.nextTick === "function";
|
|
11847
|
+
function fallback(fn) {
|
|
11848
|
+
setTimeout(fn, 0);
|
|
11849
|
+
}
|
|
11850
|
+
function wrap(defer) {
|
|
11851
|
+
return (fn, ...args) => defer(() => fn(...args));
|
|
11852
|
+
}
|
|
11853
|
+
var _defer$1;
|
|
11854
|
+
if (hasQueueMicrotask) {
|
|
11855
|
+
_defer$1 = queueMicrotask;
|
|
11856
|
+
} else if (hasSetImmediate) {
|
|
11857
|
+
_defer$1 = setImmediate;
|
|
11858
|
+
} else if (hasNextTick) {
|
|
11859
|
+
_defer$1 = process.nextTick;
|
|
11860
|
+
} else {
|
|
11861
|
+
_defer$1 = fallback;
|
|
11862
|
+
}
|
|
11863
|
+
var setImmediate$1 = wrap(_defer$1);
|
|
11864
|
+
function asyncify(func) {
|
|
11865
|
+
if (isAsync(func)) {
|
|
11866
|
+
return function(...args) {
|
|
11867
|
+
const callback = args.pop();
|
|
11868
|
+
const promise = func.apply(this, args);
|
|
11869
|
+
return handlePromise(promise, callback);
|
|
11870
|
+
};
|
|
11871
|
+
}
|
|
11872
|
+
return initialParams(function(args, callback) {
|
|
11873
|
+
var result;
|
|
11874
|
+
try {
|
|
11875
|
+
result = func.apply(this, args);
|
|
11876
|
+
} catch (e) {
|
|
11877
|
+
return callback(e);
|
|
11878
|
+
}
|
|
11879
|
+
if (result && typeof result.then === "function") {
|
|
11880
|
+
return handlePromise(result, callback);
|
|
11881
|
+
} else {
|
|
11882
|
+
callback(null, result);
|
|
11883
|
+
}
|
|
11884
|
+
});
|
|
11885
|
+
}
|
|
11886
|
+
function handlePromise(promise, callback) {
|
|
11887
|
+
return promise.then((value) => {
|
|
11888
|
+
invokeCallback(callback, null, value);
|
|
11889
|
+
}, (err) => {
|
|
11890
|
+
invokeCallback(callback, err && (err instanceof Error || err.message) ? err : new Error(err));
|
|
11891
|
+
});
|
|
11892
|
+
}
|
|
11893
|
+
function invokeCallback(callback, error, value) {
|
|
11894
|
+
try {
|
|
11895
|
+
callback(error, value);
|
|
11896
|
+
} catch (err) {
|
|
11897
|
+
setImmediate$1((e) => {
|
|
11898
|
+
throw e;
|
|
11899
|
+
}, err);
|
|
11900
|
+
}
|
|
11901
|
+
}
|
|
11902
|
+
function isAsync(fn) {
|
|
11903
|
+
return fn[Symbol.toStringTag] === "AsyncFunction";
|
|
11904
|
+
}
|
|
11905
|
+
function isAsyncGenerator(fn) {
|
|
11906
|
+
return fn[Symbol.toStringTag] === "AsyncGenerator";
|
|
11907
|
+
}
|
|
11908
|
+
function isAsyncIterable(obj) {
|
|
11909
|
+
return typeof obj[Symbol.asyncIterator] === "function";
|
|
11910
|
+
}
|
|
11911
|
+
function wrapAsync(asyncFn) {
|
|
11912
|
+
if (typeof asyncFn !== "function") throw new Error("expected a function");
|
|
11913
|
+
return isAsync(asyncFn) ? asyncify(asyncFn) : asyncFn;
|
|
11914
|
+
}
|
|
11915
|
+
function awaitify(asyncFn, arity) {
|
|
11916
|
+
if (!arity) arity = asyncFn.length;
|
|
11917
|
+
if (!arity) throw new Error("arity is undefined");
|
|
11918
|
+
function awaitable(...args) {
|
|
11919
|
+
if (typeof args[arity - 1] === "function") {
|
|
11920
|
+
return asyncFn.apply(this, args);
|
|
11921
|
+
}
|
|
11922
|
+
return new Promise((resolve, reject2) => {
|
|
11923
|
+
args[arity - 1] = (err, ...cbArgs) => {
|
|
11924
|
+
if (err) return reject2(err);
|
|
11925
|
+
resolve(cbArgs.length > 1 ? cbArgs : cbArgs[0]);
|
|
11926
|
+
};
|
|
11927
|
+
asyncFn.apply(this, args);
|
|
11928
|
+
});
|
|
11929
|
+
}
|
|
11930
|
+
return awaitable;
|
|
11931
|
+
}
|
|
11932
|
+
function applyEach$1(eachfn) {
|
|
11933
|
+
return function applyEach2(fns, ...callArgs) {
|
|
11934
|
+
const go = awaitify(function(callback) {
|
|
11935
|
+
var that = this;
|
|
11936
|
+
return eachfn(fns, (fn, cb) => {
|
|
11937
|
+
wrapAsync(fn).apply(that, callArgs.concat(cb));
|
|
11938
|
+
}, callback);
|
|
11939
|
+
});
|
|
11940
|
+
return go;
|
|
11941
|
+
};
|
|
11942
|
+
}
|
|
11943
|
+
function _asyncMap(eachfn, arr, iteratee, callback) {
|
|
11944
|
+
arr = arr || [];
|
|
11945
|
+
var results = [];
|
|
11946
|
+
var counter = 0;
|
|
11947
|
+
var _iteratee = wrapAsync(iteratee);
|
|
11948
|
+
return eachfn(arr, (value, _, iterCb) => {
|
|
11949
|
+
var index = counter++;
|
|
11950
|
+
_iteratee(value, (err, v) => {
|
|
11951
|
+
results[index] = v;
|
|
11952
|
+
iterCb(err);
|
|
11953
|
+
});
|
|
11954
|
+
}, (err) => {
|
|
11955
|
+
callback(err, results);
|
|
11956
|
+
});
|
|
11957
|
+
}
|
|
11958
|
+
function isArrayLike(value) {
|
|
11959
|
+
return value && typeof value.length === "number" && value.length >= 0 && value.length % 1 === 0;
|
|
11960
|
+
}
|
|
11961
|
+
var breakLoop = {};
|
|
11962
|
+
function once(fn) {
|
|
11963
|
+
function wrapper(...args) {
|
|
11964
|
+
if (fn === null) return;
|
|
11965
|
+
var callFn = fn;
|
|
11966
|
+
fn = null;
|
|
11967
|
+
callFn.apply(this, args);
|
|
11968
|
+
}
|
|
11969
|
+
Object.assign(wrapper, fn);
|
|
11970
|
+
return wrapper;
|
|
11971
|
+
}
|
|
11972
|
+
function getIterator(coll) {
|
|
11973
|
+
return coll[Symbol.iterator] && coll[Symbol.iterator]();
|
|
11974
|
+
}
|
|
11975
|
+
function createArrayIterator(coll) {
|
|
11976
|
+
var i = -1;
|
|
11977
|
+
var len = coll.length;
|
|
11978
|
+
return function next() {
|
|
11979
|
+
return ++i < len ? { value: coll[i], key: i } : null;
|
|
11980
|
+
};
|
|
11981
|
+
}
|
|
11982
|
+
function createES2015Iterator(iterator) {
|
|
11983
|
+
var i = -1;
|
|
11984
|
+
return function next() {
|
|
11985
|
+
var item = iterator.next();
|
|
11986
|
+
if (item.done)
|
|
11987
|
+
return null;
|
|
11988
|
+
i++;
|
|
11989
|
+
return { value: item.value, key: i };
|
|
11990
|
+
};
|
|
11991
|
+
}
|
|
11992
|
+
function createObjectIterator(obj) {
|
|
11993
|
+
var okeys = obj ? Object.keys(obj) : [];
|
|
11994
|
+
var i = -1;
|
|
11995
|
+
var len = okeys.length;
|
|
11996
|
+
return function next() {
|
|
11997
|
+
var key = okeys[++i];
|
|
11998
|
+
if (key === "__proto__") {
|
|
11999
|
+
return next();
|
|
12000
|
+
}
|
|
12001
|
+
return i < len ? { value: obj[key], key } : null;
|
|
12002
|
+
};
|
|
12003
|
+
}
|
|
12004
|
+
function createIterator(coll) {
|
|
12005
|
+
if (isArrayLike(coll)) {
|
|
12006
|
+
return createArrayIterator(coll);
|
|
12007
|
+
}
|
|
12008
|
+
var iterator = getIterator(coll);
|
|
12009
|
+
return iterator ? createES2015Iterator(iterator) : createObjectIterator(coll);
|
|
12010
|
+
}
|
|
12011
|
+
function onlyOnce(fn) {
|
|
12012
|
+
return function(...args) {
|
|
12013
|
+
if (fn === null) throw new Error("Callback was already called.");
|
|
12014
|
+
var callFn = fn;
|
|
12015
|
+
fn = null;
|
|
12016
|
+
callFn.apply(this, args);
|
|
12017
|
+
};
|
|
12018
|
+
}
|
|
12019
|
+
function asyncEachOfLimit(generator, limit, iteratee, callback) {
|
|
12020
|
+
let done = false;
|
|
12021
|
+
let canceled = false;
|
|
12022
|
+
let awaiting = false;
|
|
12023
|
+
let running = 0;
|
|
12024
|
+
let idx = 0;
|
|
12025
|
+
function replenish() {
|
|
12026
|
+
if (running >= limit || awaiting || done) return;
|
|
12027
|
+
awaiting = true;
|
|
12028
|
+
generator.next().then(({ value, done: iterDone }) => {
|
|
12029
|
+
if (canceled || done) return;
|
|
12030
|
+
awaiting = false;
|
|
12031
|
+
if (iterDone) {
|
|
12032
|
+
done = true;
|
|
12033
|
+
if (running <= 0) {
|
|
12034
|
+
callback(null);
|
|
12035
|
+
}
|
|
12036
|
+
return;
|
|
12037
|
+
}
|
|
12038
|
+
running++;
|
|
12039
|
+
iteratee(value, idx, iterateeCallback);
|
|
12040
|
+
idx++;
|
|
12041
|
+
replenish();
|
|
12042
|
+
}).catch(handleError);
|
|
12043
|
+
}
|
|
12044
|
+
function iterateeCallback(err, result) {
|
|
12045
|
+
running -= 1;
|
|
12046
|
+
if (canceled) return;
|
|
12047
|
+
if (err) return handleError(err);
|
|
12048
|
+
if (err === false) {
|
|
12049
|
+
done = true;
|
|
12050
|
+
canceled = true;
|
|
12051
|
+
return;
|
|
12052
|
+
}
|
|
12053
|
+
if (result === breakLoop || done && running <= 0) {
|
|
12054
|
+
done = true;
|
|
12055
|
+
return callback(null);
|
|
12056
|
+
}
|
|
12057
|
+
replenish();
|
|
12058
|
+
}
|
|
12059
|
+
function handleError(err) {
|
|
12060
|
+
if (canceled) return;
|
|
12061
|
+
awaiting = false;
|
|
12062
|
+
done = true;
|
|
12063
|
+
callback(err);
|
|
12064
|
+
}
|
|
12065
|
+
replenish();
|
|
12066
|
+
}
|
|
12067
|
+
var eachOfLimit$2 = (limit) => {
|
|
12068
|
+
return (obj, iteratee, callback) => {
|
|
12069
|
+
callback = once(callback);
|
|
12070
|
+
if (limit <= 0) {
|
|
12071
|
+
throw new RangeError("concurrency limit cannot be less than 1");
|
|
12072
|
+
}
|
|
12073
|
+
if (!obj) {
|
|
12074
|
+
return callback(null);
|
|
12075
|
+
}
|
|
12076
|
+
if (isAsyncGenerator(obj)) {
|
|
12077
|
+
return asyncEachOfLimit(obj, limit, iteratee, callback);
|
|
12078
|
+
}
|
|
12079
|
+
if (isAsyncIterable(obj)) {
|
|
12080
|
+
return asyncEachOfLimit(obj[Symbol.asyncIterator](), limit, iteratee, callback);
|
|
12081
|
+
}
|
|
12082
|
+
var nextElem = createIterator(obj);
|
|
12083
|
+
var done = false;
|
|
12084
|
+
var canceled = false;
|
|
12085
|
+
var running = 0;
|
|
12086
|
+
var looping = false;
|
|
12087
|
+
function iterateeCallback(err, value) {
|
|
12088
|
+
if (canceled) return;
|
|
12089
|
+
running -= 1;
|
|
12090
|
+
if (err) {
|
|
12091
|
+
done = true;
|
|
12092
|
+
callback(err);
|
|
12093
|
+
} else if (err === false) {
|
|
12094
|
+
done = true;
|
|
12095
|
+
canceled = true;
|
|
12096
|
+
} else if (value === breakLoop || done && running <= 0) {
|
|
12097
|
+
done = true;
|
|
12098
|
+
return callback(null);
|
|
12099
|
+
} else if (!looping) {
|
|
12100
|
+
replenish();
|
|
12101
|
+
}
|
|
12102
|
+
}
|
|
12103
|
+
function replenish() {
|
|
12104
|
+
looping = true;
|
|
12105
|
+
while (running < limit && !done) {
|
|
12106
|
+
var elem = nextElem();
|
|
12107
|
+
if (elem === null) {
|
|
12108
|
+
done = true;
|
|
12109
|
+
if (running <= 0) {
|
|
12110
|
+
callback(null);
|
|
12111
|
+
}
|
|
12112
|
+
return;
|
|
12113
|
+
}
|
|
12114
|
+
running += 1;
|
|
12115
|
+
iteratee(elem.value, elem.key, onlyOnce(iterateeCallback));
|
|
12116
|
+
}
|
|
12117
|
+
looping = false;
|
|
12118
|
+
}
|
|
12119
|
+
replenish();
|
|
12120
|
+
};
|
|
12121
|
+
};
|
|
12122
|
+
function eachOfLimit(coll, limit, iteratee, callback) {
|
|
12123
|
+
return eachOfLimit$2(limit)(coll, wrapAsync(iteratee), callback);
|
|
12124
|
+
}
|
|
12125
|
+
var eachOfLimit$1 = awaitify(eachOfLimit, 4);
|
|
12126
|
+
function eachOfArrayLike(coll, iteratee, callback) {
|
|
12127
|
+
callback = once(callback);
|
|
12128
|
+
var index = 0, completed = 0, { length } = coll, canceled = false;
|
|
12129
|
+
if (length === 0) {
|
|
12130
|
+
callback(null);
|
|
12131
|
+
}
|
|
12132
|
+
function iteratorCallback(err, value) {
|
|
12133
|
+
if (err === false) {
|
|
12134
|
+
canceled = true;
|
|
12135
|
+
}
|
|
12136
|
+
if (canceled === true) return;
|
|
12137
|
+
if (err) {
|
|
12138
|
+
callback(err);
|
|
12139
|
+
} else if (++completed === length || value === breakLoop) {
|
|
12140
|
+
callback(null);
|
|
12141
|
+
}
|
|
12142
|
+
}
|
|
12143
|
+
for (; index < length; index++) {
|
|
12144
|
+
iteratee(coll[index], index, onlyOnce(iteratorCallback));
|
|
12145
|
+
}
|
|
12146
|
+
}
|
|
12147
|
+
function eachOfGeneric(coll, iteratee, callback) {
|
|
12148
|
+
return eachOfLimit$1(coll, Infinity, iteratee, callback);
|
|
12149
|
+
}
|
|
12150
|
+
function eachOf(coll, iteratee, callback) {
|
|
12151
|
+
var eachOfImplementation = isArrayLike(coll) ? eachOfArrayLike : eachOfGeneric;
|
|
12152
|
+
return eachOfImplementation(coll, wrapAsync(iteratee), callback);
|
|
12153
|
+
}
|
|
12154
|
+
var eachOf$1 = awaitify(eachOf, 3);
|
|
12155
|
+
function map(coll, iteratee, callback) {
|
|
12156
|
+
return _asyncMap(eachOf$1, coll, iteratee, callback);
|
|
12157
|
+
}
|
|
12158
|
+
var map$1 = awaitify(map, 3);
|
|
12159
|
+
var applyEach = applyEach$1(map$1);
|
|
12160
|
+
function eachOfSeries(coll, iteratee, callback) {
|
|
12161
|
+
return eachOfLimit$1(coll, 1, iteratee, callback);
|
|
12162
|
+
}
|
|
12163
|
+
var eachOfSeries$1 = awaitify(eachOfSeries, 3);
|
|
12164
|
+
function mapSeries(coll, iteratee, callback) {
|
|
12165
|
+
return _asyncMap(eachOfSeries$1, coll, iteratee, callback);
|
|
12166
|
+
}
|
|
12167
|
+
var mapSeries$1 = awaitify(mapSeries, 3);
|
|
12168
|
+
var applyEachSeries = applyEach$1(mapSeries$1);
|
|
12169
|
+
var PROMISE_SYMBOL = Symbol("promiseCallback");
|
|
12170
|
+
var DLL = class {
|
|
12171
|
+
constructor() {
|
|
12172
|
+
this.head = this.tail = null;
|
|
12173
|
+
this.length = 0;
|
|
12174
|
+
}
|
|
12175
|
+
removeLink(node) {
|
|
12176
|
+
if (node.prev) node.prev.next = node.next;
|
|
12177
|
+
else this.head = node.next;
|
|
12178
|
+
if (node.next) node.next.prev = node.prev;
|
|
12179
|
+
else this.tail = node.prev;
|
|
12180
|
+
node.prev = node.next = null;
|
|
12181
|
+
this.length -= 1;
|
|
12182
|
+
return node;
|
|
12183
|
+
}
|
|
12184
|
+
empty() {
|
|
12185
|
+
while (this.head) this.shift();
|
|
12186
|
+
return this;
|
|
12187
|
+
}
|
|
12188
|
+
insertAfter(node, newNode) {
|
|
12189
|
+
newNode.prev = node;
|
|
12190
|
+
newNode.next = node.next;
|
|
12191
|
+
if (node.next) node.next.prev = newNode;
|
|
12192
|
+
else this.tail = newNode;
|
|
12193
|
+
node.next = newNode;
|
|
12194
|
+
this.length += 1;
|
|
12195
|
+
}
|
|
12196
|
+
insertBefore(node, newNode) {
|
|
12197
|
+
newNode.prev = node.prev;
|
|
12198
|
+
newNode.next = node;
|
|
12199
|
+
if (node.prev) node.prev.next = newNode;
|
|
12200
|
+
else this.head = newNode;
|
|
12201
|
+
node.prev = newNode;
|
|
12202
|
+
this.length += 1;
|
|
12203
|
+
}
|
|
12204
|
+
unshift(node) {
|
|
12205
|
+
if (this.head) this.insertBefore(this.head, node);
|
|
12206
|
+
else setInitial(this, node);
|
|
12207
|
+
}
|
|
12208
|
+
push(node) {
|
|
12209
|
+
if (this.tail) this.insertAfter(this.tail, node);
|
|
12210
|
+
else setInitial(this, node);
|
|
12211
|
+
}
|
|
12212
|
+
shift() {
|
|
12213
|
+
return this.head && this.removeLink(this.head);
|
|
12214
|
+
}
|
|
12215
|
+
pop() {
|
|
12216
|
+
return this.tail && this.removeLink(this.tail);
|
|
12217
|
+
}
|
|
12218
|
+
toArray() {
|
|
12219
|
+
return [...this];
|
|
12220
|
+
}
|
|
12221
|
+
*[Symbol.iterator]() {
|
|
12222
|
+
var cur = this.head;
|
|
12223
|
+
while (cur) {
|
|
12224
|
+
yield cur.data;
|
|
12225
|
+
cur = cur.next;
|
|
12226
|
+
}
|
|
12227
|
+
}
|
|
12228
|
+
remove(testFn) {
|
|
12229
|
+
var curr = this.head;
|
|
12230
|
+
while (curr) {
|
|
12231
|
+
var { next } = curr;
|
|
12232
|
+
if (testFn(curr)) {
|
|
12233
|
+
this.removeLink(curr);
|
|
12234
|
+
}
|
|
12235
|
+
curr = next;
|
|
12236
|
+
}
|
|
12237
|
+
return this;
|
|
12238
|
+
}
|
|
12239
|
+
};
|
|
12240
|
+
function setInitial(dll, node) {
|
|
12241
|
+
dll.length = 1;
|
|
12242
|
+
dll.head = dll.tail = node;
|
|
12243
|
+
}
|
|
12244
|
+
function queue$1(worker, concurrency, payload) {
|
|
12245
|
+
if (concurrency == null) {
|
|
12246
|
+
concurrency = 1;
|
|
12247
|
+
} else if (concurrency === 0) {
|
|
12248
|
+
throw new RangeError("Concurrency must not be zero");
|
|
12249
|
+
}
|
|
12250
|
+
var _worker = wrapAsync(worker);
|
|
12251
|
+
var numRunning = 0;
|
|
12252
|
+
var workersList = [];
|
|
12253
|
+
const events = {
|
|
12254
|
+
error: [],
|
|
12255
|
+
drain: [],
|
|
12256
|
+
saturated: [],
|
|
12257
|
+
unsaturated: [],
|
|
12258
|
+
empty: []
|
|
12259
|
+
};
|
|
12260
|
+
function on(event, handler) {
|
|
12261
|
+
events[event].push(handler);
|
|
12262
|
+
}
|
|
12263
|
+
function once2(event, handler) {
|
|
12264
|
+
const handleAndRemove = (...args) => {
|
|
12265
|
+
off(event, handleAndRemove);
|
|
12266
|
+
handler(...args);
|
|
12267
|
+
};
|
|
12268
|
+
events[event].push(handleAndRemove);
|
|
12269
|
+
}
|
|
12270
|
+
function off(event, handler) {
|
|
12271
|
+
if (!event) return Object.keys(events).forEach((ev) => events[ev] = []);
|
|
12272
|
+
if (!handler) return events[event] = [];
|
|
12273
|
+
events[event] = events[event].filter((ev) => ev !== handler);
|
|
12274
|
+
}
|
|
12275
|
+
function trigger(event, ...args) {
|
|
12276
|
+
events[event].forEach((handler) => handler(...args));
|
|
12277
|
+
}
|
|
12278
|
+
var processingScheduled = false;
|
|
12279
|
+
function _insert(data, insertAtFront, rejectOnError, callback) {
|
|
12280
|
+
if (callback != null && typeof callback !== "function") {
|
|
12281
|
+
throw new Error("task callback must be a function");
|
|
12282
|
+
}
|
|
12283
|
+
q.started = true;
|
|
12284
|
+
var res, rej;
|
|
12285
|
+
function promiseCallback(err, ...args) {
|
|
12286
|
+
if (err) return rejectOnError ? rej(err) : res();
|
|
12287
|
+
if (args.length <= 1) return res(args[0]);
|
|
12288
|
+
res(args);
|
|
12289
|
+
}
|
|
12290
|
+
var item = q._createTaskItem(
|
|
12291
|
+
data,
|
|
12292
|
+
rejectOnError ? promiseCallback : callback || promiseCallback
|
|
12293
|
+
);
|
|
12294
|
+
if (insertAtFront) {
|
|
12295
|
+
q._tasks.unshift(item);
|
|
12296
|
+
} else {
|
|
12297
|
+
q._tasks.push(item);
|
|
12298
|
+
}
|
|
12299
|
+
if (!processingScheduled) {
|
|
12300
|
+
processingScheduled = true;
|
|
12301
|
+
setImmediate$1(() => {
|
|
12302
|
+
processingScheduled = false;
|
|
12303
|
+
q.process();
|
|
12304
|
+
});
|
|
12305
|
+
}
|
|
12306
|
+
if (rejectOnError || !callback) {
|
|
12307
|
+
return new Promise((resolve, reject2) => {
|
|
12308
|
+
res = resolve;
|
|
12309
|
+
rej = reject2;
|
|
12310
|
+
});
|
|
12311
|
+
}
|
|
12312
|
+
}
|
|
12313
|
+
function _createCB(tasks) {
|
|
12314
|
+
return function(err, ...args) {
|
|
12315
|
+
numRunning -= 1;
|
|
12316
|
+
for (var i = 0, l = tasks.length; i < l; i++) {
|
|
12317
|
+
var task = tasks[i];
|
|
12318
|
+
var index = workersList.indexOf(task);
|
|
12319
|
+
if (index === 0) {
|
|
12320
|
+
workersList.shift();
|
|
12321
|
+
} else if (index > 0) {
|
|
12322
|
+
workersList.splice(index, 1);
|
|
12323
|
+
}
|
|
12324
|
+
task.callback(err, ...args);
|
|
12325
|
+
if (err != null) {
|
|
12326
|
+
trigger("error", err, task.data);
|
|
12327
|
+
}
|
|
12328
|
+
}
|
|
12329
|
+
if (numRunning <= q.concurrency - q.buffer) {
|
|
12330
|
+
trigger("unsaturated");
|
|
12331
|
+
}
|
|
12332
|
+
if (q.idle()) {
|
|
12333
|
+
trigger("drain");
|
|
12334
|
+
}
|
|
12335
|
+
q.process();
|
|
12336
|
+
};
|
|
12337
|
+
}
|
|
12338
|
+
function _maybeDrain(data) {
|
|
12339
|
+
if (data.length === 0 && q.idle()) {
|
|
12340
|
+
setImmediate$1(() => trigger("drain"));
|
|
12341
|
+
return true;
|
|
12342
|
+
}
|
|
12343
|
+
return false;
|
|
12344
|
+
}
|
|
12345
|
+
const eventMethod = (name) => (handler) => {
|
|
12346
|
+
if (!handler) {
|
|
12347
|
+
return new Promise((resolve, reject2) => {
|
|
12348
|
+
once2(name, (err, data) => {
|
|
12349
|
+
if (err) return reject2(err);
|
|
12350
|
+
resolve(data);
|
|
12351
|
+
});
|
|
12352
|
+
});
|
|
12353
|
+
}
|
|
12354
|
+
off(name);
|
|
12355
|
+
on(name, handler);
|
|
12356
|
+
};
|
|
12357
|
+
var isProcessing = false;
|
|
12358
|
+
var q = {
|
|
12359
|
+
_tasks: new DLL(),
|
|
12360
|
+
_createTaskItem(data, callback) {
|
|
12361
|
+
return {
|
|
12362
|
+
data,
|
|
12363
|
+
callback
|
|
12364
|
+
};
|
|
12365
|
+
},
|
|
12366
|
+
*[Symbol.iterator]() {
|
|
12367
|
+
yield* q._tasks[Symbol.iterator]();
|
|
12368
|
+
},
|
|
12369
|
+
concurrency,
|
|
12370
|
+
payload,
|
|
12371
|
+
buffer: concurrency / 4,
|
|
12372
|
+
started: false,
|
|
12373
|
+
paused: false,
|
|
12374
|
+
push(data, callback) {
|
|
12375
|
+
if (Array.isArray(data)) {
|
|
12376
|
+
if (_maybeDrain(data)) return;
|
|
12377
|
+
return data.map((datum) => _insert(datum, false, false, callback));
|
|
12378
|
+
}
|
|
12379
|
+
return _insert(data, false, false, callback);
|
|
12380
|
+
},
|
|
12381
|
+
pushAsync(data, callback) {
|
|
12382
|
+
if (Array.isArray(data)) {
|
|
12383
|
+
if (_maybeDrain(data)) return;
|
|
12384
|
+
return data.map((datum) => _insert(datum, false, true, callback));
|
|
12385
|
+
}
|
|
12386
|
+
return _insert(data, false, true, callback);
|
|
12387
|
+
},
|
|
12388
|
+
kill() {
|
|
12389
|
+
off();
|
|
12390
|
+
q._tasks.empty();
|
|
12391
|
+
},
|
|
12392
|
+
unshift(data, callback) {
|
|
12393
|
+
if (Array.isArray(data)) {
|
|
12394
|
+
if (_maybeDrain(data)) return;
|
|
12395
|
+
return data.map((datum) => _insert(datum, true, false, callback));
|
|
12396
|
+
}
|
|
12397
|
+
return _insert(data, true, false, callback);
|
|
12398
|
+
},
|
|
12399
|
+
unshiftAsync(data, callback) {
|
|
12400
|
+
if (Array.isArray(data)) {
|
|
12401
|
+
if (_maybeDrain(data)) return;
|
|
12402
|
+
return data.map((datum) => _insert(datum, true, true, callback));
|
|
12403
|
+
}
|
|
12404
|
+
return _insert(data, true, true, callback);
|
|
12405
|
+
},
|
|
12406
|
+
remove(testFn) {
|
|
12407
|
+
q._tasks.remove(testFn);
|
|
12408
|
+
},
|
|
12409
|
+
process() {
|
|
12410
|
+
if (isProcessing) {
|
|
12411
|
+
return;
|
|
12412
|
+
}
|
|
12413
|
+
isProcessing = true;
|
|
12414
|
+
while (!q.paused && numRunning < q.concurrency && q._tasks.length) {
|
|
12415
|
+
var tasks = [], data = [];
|
|
12416
|
+
var l = q._tasks.length;
|
|
12417
|
+
if (q.payload) l = Math.min(l, q.payload);
|
|
12418
|
+
for (var i = 0; i < l; i++) {
|
|
12419
|
+
var node = q._tasks.shift();
|
|
12420
|
+
tasks.push(node);
|
|
12421
|
+
workersList.push(node);
|
|
12422
|
+
data.push(node.data);
|
|
12423
|
+
}
|
|
12424
|
+
numRunning += 1;
|
|
12425
|
+
if (q._tasks.length === 0) {
|
|
12426
|
+
trigger("empty");
|
|
12427
|
+
}
|
|
12428
|
+
if (numRunning === q.concurrency) {
|
|
12429
|
+
trigger("saturated");
|
|
12430
|
+
}
|
|
12431
|
+
var cb = onlyOnce(_createCB(tasks));
|
|
12432
|
+
_worker(data, cb);
|
|
12433
|
+
}
|
|
12434
|
+
isProcessing = false;
|
|
12435
|
+
},
|
|
12436
|
+
length() {
|
|
12437
|
+
return q._tasks.length;
|
|
12438
|
+
},
|
|
12439
|
+
running() {
|
|
12440
|
+
return numRunning;
|
|
12441
|
+
},
|
|
12442
|
+
workersList() {
|
|
12443
|
+
return workersList;
|
|
12444
|
+
},
|
|
12445
|
+
idle() {
|
|
12446
|
+
return q._tasks.length + numRunning === 0;
|
|
12447
|
+
},
|
|
12448
|
+
pause() {
|
|
12449
|
+
q.paused = true;
|
|
12450
|
+
},
|
|
12451
|
+
resume() {
|
|
12452
|
+
if (q.paused === false) {
|
|
12453
|
+
return;
|
|
12454
|
+
}
|
|
12455
|
+
q.paused = false;
|
|
12456
|
+
setImmediate$1(q.process);
|
|
12457
|
+
}
|
|
12458
|
+
};
|
|
12459
|
+
Object.defineProperties(q, {
|
|
12460
|
+
saturated: {
|
|
12461
|
+
writable: false,
|
|
12462
|
+
value: eventMethod("saturated")
|
|
12463
|
+
},
|
|
12464
|
+
unsaturated: {
|
|
12465
|
+
writable: false,
|
|
12466
|
+
value: eventMethod("unsaturated")
|
|
12467
|
+
},
|
|
12468
|
+
empty: {
|
|
12469
|
+
writable: false,
|
|
12470
|
+
value: eventMethod("empty")
|
|
12471
|
+
},
|
|
12472
|
+
drain: {
|
|
12473
|
+
writable: false,
|
|
12474
|
+
value: eventMethod("drain")
|
|
12475
|
+
},
|
|
12476
|
+
error: {
|
|
12477
|
+
writable: false,
|
|
12478
|
+
value: eventMethod("error")
|
|
12479
|
+
}
|
|
12480
|
+
});
|
|
12481
|
+
return q;
|
|
12482
|
+
}
|
|
12483
|
+
function reduce(coll, memo, iteratee, callback) {
|
|
12484
|
+
callback = once(callback);
|
|
12485
|
+
var _iteratee = wrapAsync(iteratee);
|
|
12486
|
+
return eachOfSeries$1(coll, (x, i, iterCb) => {
|
|
12487
|
+
_iteratee(memo, x, (err, v) => {
|
|
12488
|
+
memo = v;
|
|
12489
|
+
iterCb(err);
|
|
12490
|
+
});
|
|
12491
|
+
}, (err) => callback(err, memo));
|
|
12492
|
+
}
|
|
12493
|
+
var reduce$1 = awaitify(reduce, 4);
|
|
12494
|
+
function mapLimit(coll, limit, iteratee, callback) {
|
|
12495
|
+
return _asyncMap(eachOfLimit$2(limit), coll, iteratee, callback);
|
|
12496
|
+
}
|
|
12497
|
+
var mapLimit$1 = awaitify(mapLimit, 4);
|
|
12498
|
+
function concatLimit(coll, limit, iteratee, callback) {
|
|
12499
|
+
var _iteratee = wrapAsync(iteratee);
|
|
12500
|
+
return mapLimit$1(coll, limit, (val, iterCb) => {
|
|
12501
|
+
_iteratee(val, (err, ...args) => {
|
|
12502
|
+
if (err) return iterCb(err);
|
|
12503
|
+
return iterCb(err, args);
|
|
12504
|
+
});
|
|
12505
|
+
}, (err, mapResults) => {
|
|
12506
|
+
var result = [];
|
|
12507
|
+
for (var i = 0; i < mapResults.length; i++) {
|
|
12508
|
+
if (mapResults[i]) {
|
|
12509
|
+
result = result.concat(...mapResults[i]);
|
|
12510
|
+
}
|
|
12511
|
+
}
|
|
12512
|
+
return callback(err, result);
|
|
12513
|
+
});
|
|
12514
|
+
}
|
|
12515
|
+
var concatLimit$1 = awaitify(concatLimit, 4);
|
|
12516
|
+
function concat(coll, iteratee, callback) {
|
|
12517
|
+
return concatLimit$1(coll, Infinity, iteratee, callback);
|
|
12518
|
+
}
|
|
12519
|
+
var concat$1 = awaitify(concat, 3);
|
|
12520
|
+
function concatSeries(coll, iteratee, callback) {
|
|
12521
|
+
return concatLimit$1(coll, 1, iteratee, callback);
|
|
12522
|
+
}
|
|
12523
|
+
var concatSeries$1 = awaitify(concatSeries, 3);
|
|
12524
|
+
function _createTester(check, getResult) {
|
|
12525
|
+
return (eachfn, arr, _iteratee, cb) => {
|
|
12526
|
+
var testPassed = false;
|
|
12527
|
+
var testResult;
|
|
12528
|
+
const iteratee = wrapAsync(_iteratee);
|
|
12529
|
+
eachfn(arr, (value, _, callback) => {
|
|
12530
|
+
iteratee(value, (err, result) => {
|
|
12531
|
+
if (err || err === false) return callback(err);
|
|
12532
|
+
if (check(result) && !testResult) {
|
|
12533
|
+
testPassed = true;
|
|
12534
|
+
testResult = getResult(true, value);
|
|
12535
|
+
return callback(null, breakLoop);
|
|
12536
|
+
}
|
|
12537
|
+
callback();
|
|
12538
|
+
});
|
|
12539
|
+
}, (err) => {
|
|
12540
|
+
if (err) return cb(err);
|
|
12541
|
+
cb(null, testPassed ? testResult : getResult(false));
|
|
12542
|
+
});
|
|
12543
|
+
};
|
|
12544
|
+
}
|
|
12545
|
+
function detect(coll, iteratee, callback) {
|
|
12546
|
+
return _createTester((bool) => bool, (res, item) => item)(eachOf$1, coll, iteratee, callback);
|
|
12547
|
+
}
|
|
12548
|
+
var detect$1 = awaitify(detect, 3);
|
|
12549
|
+
function detectLimit(coll, limit, iteratee, callback) {
|
|
12550
|
+
return _createTester((bool) => bool, (res, item) => item)(eachOfLimit$2(limit), coll, iteratee, callback);
|
|
12551
|
+
}
|
|
12552
|
+
var detectLimit$1 = awaitify(detectLimit, 4);
|
|
12553
|
+
function detectSeries(coll, iteratee, callback) {
|
|
12554
|
+
return _createTester((bool) => bool, (res, item) => item)(eachOfLimit$2(1), coll, iteratee, callback);
|
|
12555
|
+
}
|
|
12556
|
+
var detectSeries$1 = awaitify(detectSeries, 3);
|
|
12557
|
+
function consoleFunc(name) {
|
|
12558
|
+
return (fn, ...args) => wrapAsync(fn)(...args, (err, ...resultArgs) => {
|
|
12559
|
+
if (typeof console === "object") {
|
|
12560
|
+
if (err) {
|
|
12561
|
+
if (console.error) {
|
|
12562
|
+
console.error(err);
|
|
12563
|
+
}
|
|
12564
|
+
} else if (console[name]) {
|
|
12565
|
+
resultArgs.forEach((x) => console[name](x));
|
|
12566
|
+
}
|
|
12567
|
+
}
|
|
12568
|
+
});
|
|
12569
|
+
}
|
|
12570
|
+
var dir = consoleFunc("dir");
|
|
12571
|
+
function doWhilst(iteratee, test, callback) {
|
|
12572
|
+
callback = onlyOnce(callback);
|
|
12573
|
+
var _fn = wrapAsync(iteratee);
|
|
12574
|
+
var _test = wrapAsync(test);
|
|
12575
|
+
var results;
|
|
12576
|
+
function next(err, ...args) {
|
|
12577
|
+
if (err) return callback(err);
|
|
12578
|
+
if (err === false) return;
|
|
12579
|
+
results = args;
|
|
12580
|
+
_test(...args, check);
|
|
12581
|
+
}
|
|
12582
|
+
function check(err, truth) {
|
|
12583
|
+
if (err) return callback(err);
|
|
12584
|
+
if (err === false) return;
|
|
12585
|
+
if (!truth) return callback(null, ...results);
|
|
12586
|
+
_fn(next);
|
|
12587
|
+
}
|
|
12588
|
+
return check(null, true);
|
|
12589
|
+
}
|
|
12590
|
+
var doWhilst$1 = awaitify(doWhilst, 3);
|
|
12591
|
+
function _withoutIndex(iteratee) {
|
|
12592
|
+
return (value, index, callback) => iteratee(value, callback);
|
|
12593
|
+
}
|
|
12594
|
+
function eachLimit$2(coll, iteratee, callback) {
|
|
12595
|
+
return eachOf$1(coll, _withoutIndex(wrapAsync(iteratee)), callback);
|
|
12596
|
+
}
|
|
12597
|
+
var each = awaitify(eachLimit$2, 3);
|
|
12598
|
+
function eachLimit(coll, limit, iteratee, callback) {
|
|
12599
|
+
return eachOfLimit$2(limit)(coll, _withoutIndex(wrapAsync(iteratee)), callback);
|
|
12600
|
+
}
|
|
12601
|
+
var eachLimit$1 = awaitify(eachLimit, 4);
|
|
12602
|
+
function eachSeries(coll, iteratee, callback) {
|
|
12603
|
+
return eachLimit$1(coll, 1, iteratee, callback);
|
|
12604
|
+
}
|
|
12605
|
+
var eachSeries$1 = awaitify(eachSeries, 3);
|
|
12606
|
+
function ensureAsync(fn) {
|
|
12607
|
+
if (isAsync(fn)) return fn;
|
|
12608
|
+
return function(...args) {
|
|
12609
|
+
var callback = args.pop();
|
|
12610
|
+
var sync = true;
|
|
12611
|
+
args.push((...innerArgs) => {
|
|
12612
|
+
if (sync) {
|
|
12613
|
+
setImmediate$1(() => callback(...innerArgs));
|
|
12614
|
+
} else {
|
|
12615
|
+
callback(...innerArgs);
|
|
12616
|
+
}
|
|
12617
|
+
});
|
|
12618
|
+
fn.apply(this, args);
|
|
12619
|
+
sync = false;
|
|
12620
|
+
};
|
|
12621
|
+
}
|
|
12622
|
+
function every(coll, iteratee, callback) {
|
|
12623
|
+
return _createTester((bool) => !bool, (res) => !res)(eachOf$1, coll, iteratee, callback);
|
|
12624
|
+
}
|
|
12625
|
+
var every$1 = awaitify(every, 3);
|
|
12626
|
+
function everyLimit(coll, limit, iteratee, callback) {
|
|
12627
|
+
return _createTester((bool) => !bool, (res) => !res)(eachOfLimit$2(limit), coll, iteratee, callback);
|
|
12628
|
+
}
|
|
12629
|
+
var everyLimit$1 = awaitify(everyLimit, 4);
|
|
12630
|
+
function everySeries(coll, iteratee, callback) {
|
|
12631
|
+
return _createTester((bool) => !bool, (res) => !res)(eachOfSeries$1, coll, iteratee, callback);
|
|
12632
|
+
}
|
|
12633
|
+
var everySeries$1 = awaitify(everySeries, 3);
|
|
12634
|
+
function filterArray(eachfn, arr, iteratee, callback) {
|
|
12635
|
+
var truthValues = new Array(arr.length);
|
|
12636
|
+
eachfn(arr, (x, index, iterCb) => {
|
|
12637
|
+
iteratee(x, (err, v) => {
|
|
12638
|
+
truthValues[index] = !!v;
|
|
12639
|
+
iterCb(err);
|
|
12640
|
+
});
|
|
12641
|
+
}, (err) => {
|
|
12642
|
+
if (err) return callback(err);
|
|
12643
|
+
var results = [];
|
|
12644
|
+
for (var i = 0; i < arr.length; i++) {
|
|
12645
|
+
if (truthValues[i]) results.push(arr[i]);
|
|
12646
|
+
}
|
|
12647
|
+
callback(null, results);
|
|
12648
|
+
});
|
|
12649
|
+
}
|
|
12650
|
+
function filterGeneric(eachfn, coll, iteratee, callback) {
|
|
12651
|
+
var results = [];
|
|
12652
|
+
eachfn(coll, (x, index, iterCb) => {
|
|
12653
|
+
iteratee(x, (err, v) => {
|
|
12654
|
+
if (err) return iterCb(err);
|
|
12655
|
+
if (v) {
|
|
12656
|
+
results.push({ index, value: x });
|
|
12657
|
+
}
|
|
12658
|
+
iterCb(err);
|
|
12659
|
+
});
|
|
12660
|
+
}, (err) => {
|
|
12661
|
+
if (err) return callback(err);
|
|
12662
|
+
callback(null, results.sort((a, b) => a.index - b.index).map((v) => v.value));
|
|
12663
|
+
});
|
|
12664
|
+
}
|
|
12665
|
+
function _filter(eachfn, coll, iteratee, callback) {
|
|
12666
|
+
var filter2 = isArrayLike(coll) ? filterArray : filterGeneric;
|
|
12667
|
+
return filter2(eachfn, coll, wrapAsync(iteratee), callback);
|
|
12668
|
+
}
|
|
12669
|
+
function filter(coll, iteratee, callback) {
|
|
12670
|
+
return _filter(eachOf$1, coll, iteratee, callback);
|
|
12671
|
+
}
|
|
12672
|
+
var filter$1 = awaitify(filter, 3);
|
|
12673
|
+
function filterLimit(coll, limit, iteratee, callback) {
|
|
12674
|
+
return _filter(eachOfLimit$2(limit), coll, iteratee, callback);
|
|
12675
|
+
}
|
|
12676
|
+
var filterLimit$1 = awaitify(filterLimit, 4);
|
|
12677
|
+
function filterSeries(coll, iteratee, callback) {
|
|
12678
|
+
return _filter(eachOfSeries$1, coll, iteratee, callback);
|
|
12679
|
+
}
|
|
12680
|
+
var filterSeries$1 = awaitify(filterSeries, 3);
|
|
12681
|
+
function forever(fn, errback) {
|
|
12682
|
+
var done = onlyOnce(errback);
|
|
12683
|
+
var task = wrapAsync(ensureAsync(fn));
|
|
12684
|
+
function next(err) {
|
|
12685
|
+
if (err) return done(err);
|
|
12686
|
+
if (err === false) return;
|
|
12687
|
+
task(next);
|
|
12688
|
+
}
|
|
12689
|
+
return next();
|
|
12690
|
+
}
|
|
12691
|
+
var forever$1 = awaitify(forever, 2);
|
|
12692
|
+
function groupByLimit(coll, limit, iteratee, callback) {
|
|
12693
|
+
var _iteratee = wrapAsync(iteratee);
|
|
12694
|
+
return mapLimit$1(coll, limit, (val, iterCb) => {
|
|
12695
|
+
_iteratee(val, (err, key) => {
|
|
12696
|
+
if (err) return iterCb(err);
|
|
12697
|
+
return iterCb(err, { key, val });
|
|
12698
|
+
});
|
|
12699
|
+
}, (err, mapResults) => {
|
|
12700
|
+
var result = {};
|
|
12701
|
+
var { hasOwnProperty } = Object.prototype;
|
|
12702
|
+
for (var i = 0; i < mapResults.length; i++) {
|
|
12703
|
+
if (mapResults[i]) {
|
|
12704
|
+
var { key } = mapResults[i];
|
|
12705
|
+
var { val } = mapResults[i];
|
|
12706
|
+
if (hasOwnProperty.call(result, key)) {
|
|
12707
|
+
result[key].push(val);
|
|
12708
|
+
} else {
|
|
12709
|
+
result[key] = [val];
|
|
12710
|
+
}
|
|
12711
|
+
}
|
|
12712
|
+
}
|
|
12713
|
+
return callback(err, result);
|
|
12714
|
+
});
|
|
12715
|
+
}
|
|
12716
|
+
var groupByLimit$1 = awaitify(groupByLimit, 4);
|
|
12717
|
+
var log2 = consoleFunc("log");
|
|
12718
|
+
function mapValuesLimit(obj, limit, iteratee, callback) {
|
|
12719
|
+
callback = once(callback);
|
|
12720
|
+
var newObj = {};
|
|
12721
|
+
var _iteratee = wrapAsync(iteratee);
|
|
12722
|
+
return eachOfLimit$2(limit)(obj, (val, key, next) => {
|
|
12723
|
+
_iteratee(val, key, (err, result) => {
|
|
12724
|
+
if (err) return next(err);
|
|
12725
|
+
newObj[key] = result;
|
|
12726
|
+
next(err);
|
|
12727
|
+
});
|
|
12728
|
+
}, (err) => callback(err, newObj));
|
|
12729
|
+
}
|
|
12730
|
+
var mapValuesLimit$1 = awaitify(mapValuesLimit, 4);
|
|
12731
|
+
var _defer;
|
|
12732
|
+
if (hasNextTick) {
|
|
12733
|
+
_defer = process.nextTick;
|
|
12734
|
+
} else if (hasSetImmediate) {
|
|
12735
|
+
_defer = setImmediate;
|
|
12736
|
+
} else {
|
|
12737
|
+
_defer = fallback;
|
|
12738
|
+
}
|
|
12739
|
+
var nextTick = wrap(_defer);
|
|
12740
|
+
var _parallel = awaitify((eachfn, tasks, callback) => {
|
|
12741
|
+
var results = isArrayLike(tasks) ? [] : {};
|
|
12742
|
+
eachfn(tasks, (task, key, taskCb) => {
|
|
12743
|
+
wrapAsync(task)((err, ...result) => {
|
|
12744
|
+
if (result.length < 2) {
|
|
12745
|
+
[result] = result;
|
|
12746
|
+
}
|
|
12747
|
+
results[key] = result;
|
|
12748
|
+
taskCb(err);
|
|
12749
|
+
});
|
|
12750
|
+
}, (err) => callback(err, results));
|
|
12751
|
+
}, 3);
|
|
12752
|
+
function queue(worker, concurrency) {
|
|
12753
|
+
var _worker = wrapAsync(worker);
|
|
12754
|
+
return queue$1((items, cb) => {
|
|
12755
|
+
_worker(items[0], cb);
|
|
12756
|
+
}, concurrency, 1);
|
|
12757
|
+
}
|
|
12758
|
+
function race(tasks, callback) {
|
|
12759
|
+
callback = once(callback);
|
|
12760
|
+
if (!Array.isArray(tasks)) return callback(new TypeError("First argument to race must be an array of functions"));
|
|
12761
|
+
if (!tasks.length) return callback();
|
|
12762
|
+
for (var i = 0, l = tasks.length; i < l; i++) {
|
|
12763
|
+
wrapAsync(tasks[i])(callback);
|
|
12764
|
+
}
|
|
12765
|
+
}
|
|
12766
|
+
var race$1 = awaitify(race, 2);
|
|
12767
|
+
function reject$2(eachfn, arr, _iteratee, callback) {
|
|
12768
|
+
const iteratee = wrapAsync(_iteratee);
|
|
12769
|
+
return _filter(eachfn, arr, (value, cb) => {
|
|
12770
|
+
iteratee(value, (err, v) => {
|
|
12771
|
+
cb(err, !v);
|
|
12772
|
+
});
|
|
12773
|
+
}, callback);
|
|
12774
|
+
}
|
|
12775
|
+
function reject(coll, iteratee, callback) {
|
|
12776
|
+
return reject$2(eachOf$1, coll, iteratee, callback);
|
|
12777
|
+
}
|
|
12778
|
+
var reject$1 = awaitify(reject, 3);
|
|
12779
|
+
function rejectLimit(coll, limit, iteratee, callback) {
|
|
12780
|
+
return reject$2(eachOfLimit$2(limit), coll, iteratee, callback);
|
|
12781
|
+
}
|
|
12782
|
+
var rejectLimit$1 = awaitify(rejectLimit, 4);
|
|
12783
|
+
function rejectSeries(coll, iteratee, callback) {
|
|
12784
|
+
return reject$2(eachOfSeries$1, coll, iteratee, callback);
|
|
12785
|
+
}
|
|
12786
|
+
var rejectSeries$1 = awaitify(rejectSeries, 3);
|
|
12787
|
+
function some(coll, iteratee, callback) {
|
|
12788
|
+
return _createTester(Boolean, (res) => res)(eachOf$1, coll, iteratee, callback);
|
|
12789
|
+
}
|
|
12790
|
+
var some$1 = awaitify(some, 3);
|
|
12791
|
+
function someLimit(coll, limit, iteratee, callback) {
|
|
12792
|
+
return _createTester(Boolean, (res) => res)(eachOfLimit$2(limit), coll, iteratee, callback);
|
|
12793
|
+
}
|
|
12794
|
+
var someLimit$1 = awaitify(someLimit, 4);
|
|
12795
|
+
function someSeries(coll, iteratee, callback) {
|
|
12796
|
+
return _createTester(Boolean, (res) => res)(eachOfSeries$1, coll, iteratee, callback);
|
|
12797
|
+
}
|
|
12798
|
+
var someSeries$1 = awaitify(someSeries, 3);
|
|
12799
|
+
function sortBy(coll, iteratee, callback) {
|
|
12800
|
+
var _iteratee = wrapAsync(iteratee);
|
|
12801
|
+
return map$1(coll, (x, iterCb) => {
|
|
12802
|
+
_iteratee(x, (err, criteria) => {
|
|
12803
|
+
if (err) return iterCb(err);
|
|
12804
|
+
iterCb(err, { value: x, criteria });
|
|
12805
|
+
});
|
|
12806
|
+
}, (err, results) => {
|
|
12807
|
+
if (err) return callback(err);
|
|
12808
|
+
callback(null, results.sort(comparator).map((v) => v.value));
|
|
12809
|
+
});
|
|
12810
|
+
function comparator(left, right) {
|
|
12811
|
+
var a = left.criteria, b = right.criteria;
|
|
12812
|
+
return a < b ? -1 : a > b ? 1 : 0;
|
|
12813
|
+
}
|
|
12814
|
+
}
|
|
12815
|
+
var sortBy$1 = awaitify(sortBy, 3);
|
|
12816
|
+
function tryEach(tasks, callback) {
|
|
12817
|
+
var error = null;
|
|
12818
|
+
var result;
|
|
12819
|
+
return eachSeries$1(tasks, (task, taskCb) => {
|
|
12820
|
+
wrapAsync(task)((err, ...args) => {
|
|
12821
|
+
if (err === false) return taskCb(err);
|
|
12822
|
+
if (args.length < 2) {
|
|
12823
|
+
[result] = args;
|
|
12824
|
+
} else {
|
|
12825
|
+
result = args;
|
|
12826
|
+
}
|
|
12827
|
+
error = err;
|
|
12828
|
+
taskCb(err ? null : {});
|
|
12829
|
+
});
|
|
12830
|
+
}, () => callback(error, result));
|
|
12831
|
+
}
|
|
12832
|
+
var tryEach$1 = awaitify(tryEach);
|
|
12833
|
+
function whilst(test, iteratee, callback) {
|
|
12834
|
+
callback = onlyOnce(callback);
|
|
12835
|
+
var _fn = wrapAsync(iteratee);
|
|
12836
|
+
var _test = wrapAsync(test);
|
|
12837
|
+
var results = [];
|
|
12838
|
+
function next(err, ...rest) {
|
|
12839
|
+
if (err) return callback(err);
|
|
12840
|
+
results = rest;
|
|
12841
|
+
if (err === false) return;
|
|
12842
|
+
_test(check);
|
|
12843
|
+
}
|
|
12844
|
+
function check(err, truth) {
|
|
12845
|
+
if (err) return callback(err);
|
|
12846
|
+
if (err === false) return;
|
|
12847
|
+
if (!truth) return callback(null, ...results);
|
|
12848
|
+
_fn(next);
|
|
12849
|
+
}
|
|
12850
|
+
return _test(check);
|
|
12851
|
+
}
|
|
12852
|
+
var whilst$1 = awaitify(whilst, 3);
|
|
12853
|
+
function waterfall(tasks, callback) {
|
|
12854
|
+
callback = once(callback);
|
|
12855
|
+
if (!Array.isArray(tasks)) return callback(new Error("First argument to waterfall must be an array of functions"));
|
|
12856
|
+
if (!tasks.length) return callback();
|
|
12857
|
+
var taskIndex = 0;
|
|
12858
|
+
function nextTask(args) {
|
|
12859
|
+
var task = wrapAsync(tasks[taskIndex++]);
|
|
12860
|
+
task(...args, onlyOnce(next));
|
|
12861
|
+
}
|
|
12862
|
+
function next(err, ...args) {
|
|
12863
|
+
if (err === false) return;
|
|
12864
|
+
if (err || taskIndex === tasks.length) {
|
|
12865
|
+
return callback(err, ...args);
|
|
12866
|
+
}
|
|
12867
|
+
nextTask(args);
|
|
12868
|
+
}
|
|
12869
|
+
nextTask([]);
|
|
12870
|
+
}
|
|
12871
|
+
var waterfall$1 = awaitify(waterfall);
|
|
12872
|
+
|
|
12873
|
+
// src/reporters/progress.ts
|
|
12874
|
+
var SimpleProgressReporter = class {
|
|
12875
|
+
start(name, _total) {
|
|
12876
|
+
console.log(`Running evaluator ${name}`);
|
|
12877
|
+
}
|
|
12878
|
+
stop() {
|
|
12879
|
+
}
|
|
12880
|
+
increment(_name) {
|
|
12881
|
+
}
|
|
12882
|
+
setTotal(_name, _total) {
|
|
12883
|
+
}
|
|
12884
|
+
};
|
|
12885
|
+
|
|
12886
|
+
// src/eval-parameters.ts
|
|
12887
|
+
|
|
12888
|
+
|
|
12889
|
+
// src/framework2.ts
|
|
12890
|
+
|
|
12891
|
+
var currentFilename = typeof __filename !== "undefined" ? __filename : "unknown";
|
|
12892
|
+
var ProjectBuilder = class {
|
|
12893
|
+
create(opts) {
|
|
12894
|
+
return new Project2(opts);
|
|
12895
|
+
}
|
|
12896
|
+
};
|
|
12897
|
+
var projects = new ProjectBuilder();
|
|
12898
|
+
var Project2 = (_class16 = class {
|
|
12899
|
+
|
|
12900
|
+
|
|
12901
|
+
|
|
12902
|
+
|
|
12903
|
+
|
|
12904
|
+
__init52() {this._publishableCodeFunctions = []}
|
|
12905
|
+
__init53() {this._publishablePrompts = []}
|
|
12906
|
+
constructor(args) {;_class16.prototype.__init52.call(this);_class16.prototype.__init53.call(this);
|
|
12907
|
+
_initializeSpanContext();
|
|
12908
|
+
this.name = "name" in args ? args.name : void 0;
|
|
12909
|
+
this.id = "id" in args ? args.id : void 0;
|
|
12910
|
+
this.tools = new ToolBuilder(this);
|
|
12911
|
+
this.prompts = new PromptBuilder(this);
|
|
12912
|
+
this.scorers = new ScorerBuilder(this);
|
|
12913
|
+
}
|
|
12914
|
+
addPrompt(prompt) {
|
|
12915
|
+
this._publishablePrompts.push(prompt);
|
|
12916
|
+
if (globalThis._lazy_load) {
|
|
12917
|
+
globalThis._evals.prompts.push(prompt);
|
|
12918
|
+
}
|
|
12919
|
+
}
|
|
12920
|
+
addCodeFunction(fn) {
|
|
12921
|
+
this._publishableCodeFunctions.push(fn);
|
|
12922
|
+
if (globalThis._lazy_load) {
|
|
12923
|
+
globalThis._evals.functions.push(fn);
|
|
12924
|
+
}
|
|
12925
|
+
}
|
|
12926
|
+
async publish() {
|
|
12927
|
+
if (globalThis._lazy_load) {
|
|
12928
|
+
console.warn("publish() is a no-op when running `braintrust push`.");
|
|
12929
|
+
return;
|
|
12930
|
+
}
|
|
12931
|
+
await login();
|
|
12932
|
+
const projectMap = new ProjectNameIdMap();
|
|
12933
|
+
const functionDefinitions = [];
|
|
12934
|
+
if (this._publishableCodeFunctions.length > 0) {
|
|
12935
|
+
console.warn(
|
|
12936
|
+
"Code functions cannot be published directly. Use `braintrust push` instead."
|
|
12937
|
+
);
|
|
12938
|
+
}
|
|
12939
|
+
if (this._publishablePrompts.length > 0) {
|
|
12940
|
+
for (const prompt of this._publishablePrompts) {
|
|
12941
|
+
const functionDefinition = await prompt.toFunctionDefinition(projectMap);
|
|
12942
|
+
functionDefinitions.push(functionDefinition);
|
|
12943
|
+
}
|
|
12944
|
+
}
|
|
12945
|
+
await _internalGetGlobalState().apiConn().post_json("insert-functions", {
|
|
12946
|
+
functions: functionDefinitions
|
|
12947
|
+
});
|
|
12948
|
+
}
|
|
12949
|
+
}, _class16);
|
|
12950
|
+
var ToolBuilder = (_class17 = class {
|
|
12951
|
+
constructor(project) {;_class17.prototype.__init54.call(this);
|
|
12952
|
+
this.project = project;
|
|
12953
|
+
}
|
|
12954
|
+
__init54() {this.taskCounter = 0}
|
|
12955
|
+
// This type definition is just a catch all so that the implementation can be
|
|
12956
|
+
// less specific than the two more specific declarations above.
|
|
12957
|
+
create(opts) {
|
|
12958
|
+
this.taskCounter++;
|
|
12959
|
+
opts = _nullishCoalesce(opts, () => ( {}));
|
|
12960
|
+
const { handler, name, slug, parameters, returns, ...rest } = opts;
|
|
12961
|
+
let resolvedName = _nullishCoalesce(name, () => ( handler.name));
|
|
12962
|
+
if (resolvedName.trim().length === 0) {
|
|
12963
|
+
resolvedName = `Tool ${isomorph_default.basename(currentFilename)} ${this.taskCounter}`;
|
|
12964
|
+
}
|
|
12965
|
+
const tool = new CodeFunction(this.project, {
|
|
12966
|
+
handler,
|
|
12967
|
+
name: resolvedName,
|
|
12968
|
+
slug: _nullishCoalesce(slug, () => ( slugify(resolvedName, { lower: true, strict: true }))),
|
|
12969
|
+
type: "tool",
|
|
12970
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/consistent-type-assertions
|
|
12971
|
+
parameters,
|
|
12972
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/consistent-type-assertions
|
|
12973
|
+
returns,
|
|
12974
|
+
...rest
|
|
12975
|
+
});
|
|
12976
|
+
this.project.addCodeFunction(tool);
|
|
12977
|
+
return tool;
|
|
12978
|
+
}
|
|
12979
|
+
}, _class17);
|
|
12980
|
+
var ScorerBuilder = (_class18 = class {
|
|
12981
|
+
constructor(project) {;_class18.prototype.__init55.call(this);
|
|
12982
|
+
this.project = project;
|
|
12983
|
+
}
|
|
12984
|
+
__init55() {this.taskCounter = 0}
|
|
12985
|
+
create(opts) {
|
|
12986
|
+
this.taskCounter++;
|
|
12987
|
+
let resolvedName = opts.name;
|
|
12988
|
+
if (!resolvedName && "handler" in opts) {
|
|
12989
|
+
resolvedName = opts.handler.name;
|
|
12990
|
+
}
|
|
12991
|
+
if (!resolvedName || resolvedName.trim().length === 0) {
|
|
12992
|
+
resolvedName = `Scorer ${isomorph_default.basename(currentFilename)} ${this.taskCounter}`;
|
|
12993
|
+
}
|
|
12994
|
+
const slug = _nullishCoalesce(opts.slug, () => ( slugify(resolvedName, { lower: true, strict: true })));
|
|
12995
|
+
if ("handler" in opts) {
|
|
12996
|
+
const scorer = new CodeFunction(this.project, {
|
|
12997
|
+
...opts,
|
|
12998
|
+
name: resolvedName,
|
|
12999
|
+
slug,
|
|
13000
|
+
type: "scorer"
|
|
13001
|
+
});
|
|
13002
|
+
this.project.addCodeFunction(scorer);
|
|
13003
|
+
} else {
|
|
13004
|
+
const promptBlock = "messages" in opts ? {
|
|
13005
|
+
type: "chat",
|
|
13006
|
+
messages: opts.messages
|
|
13007
|
+
} : {
|
|
13008
|
+
type: "completion",
|
|
13009
|
+
content: opts.prompt
|
|
13010
|
+
};
|
|
13011
|
+
const promptData = {
|
|
13012
|
+
prompt: promptBlock,
|
|
13013
|
+
options: {
|
|
13014
|
+
model: opts.model,
|
|
13015
|
+
params: opts.params
|
|
13016
|
+
},
|
|
13017
|
+
parser: {
|
|
13018
|
+
type: "llm_classifier",
|
|
13019
|
+
use_cot: opts.useCot,
|
|
13020
|
+
choice_scores: opts.choiceScores
|
|
13021
|
+
}
|
|
13022
|
+
};
|
|
13023
|
+
const codePrompt = new CodePrompt(
|
|
13024
|
+
this.project,
|
|
13025
|
+
promptData,
|
|
13026
|
+
[],
|
|
13027
|
+
{
|
|
13028
|
+
...opts,
|
|
13029
|
+
name: resolvedName,
|
|
13030
|
+
slug
|
|
13031
|
+
},
|
|
13032
|
+
"scorer"
|
|
13033
|
+
);
|
|
13034
|
+
this.project.addPrompt(codePrompt);
|
|
13035
|
+
}
|
|
13036
|
+
}
|
|
13037
|
+
}, _class18);
|
|
13038
|
+
var CodeFunction = class {
|
|
13039
|
+
constructor(project, opts) {
|
|
13040
|
+
this.project = project;
|
|
13041
|
+
this.handler = opts.handler;
|
|
13042
|
+
this.name = opts.name;
|
|
13043
|
+
this.slug = opts.slug;
|
|
13044
|
+
this.description = opts.description;
|
|
13045
|
+
this.type = opts.type;
|
|
13046
|
+
this.ifExists = opts.ifExists;
|
|
13047
|
+
this.metadata = opts.metadata;
|
|
13048
|
+
this.parameters = opts.parameters;
|
|
13049
|
+
this.returns = opts.returns;
|
|
13050
|
+
if (this.returns && !this.parameters) {
|
|
13051
|
+
throw new Error("parameters are required if return type is defined");
|
|
13052
|
+
}
|
|
13053
|
+
}
|
|
13054
|
+
|
|
13055
|
+
|
|
13056
|
+
|
|
13057
|
+
|
|
13058
|
+
|
|
13059
|
+
|
|
13060
|
+
|
|
13061
|
+
|
|
13062
|
+
|
|
13063
|
+
key() {
|
|
13064
|
+
return JSON.stringify([
|
|
13065
|
+
_nullishCoalesce(this.project.id, () => ( "")),
|
|
13066
|
+
_nullishCoalesce(this.project.name, () => ( "")),
|
|
13067
|
+
this.slug
|
|
13068
|
+
]);
|
|
13069
|
+
}
|
|
13070
|
+
};
|
|
13071
|
+
var CodePrompt = class {
|
|
13072
|
+
|
|
13073
|
+
|
|
13074
|
+
|
|
13075
|
+
|
|
13076
|
+
|
|
13077
|
+
|
|
13078
|
+
|
|
13079
|
+
|
|
13080
|
+
|
|
13081
|
+
|
|
13082
|
+
constructor(project, prompt, toolFunctions, opts, functionType) {
|
|
13083
|
+
this.project = project;
|
|
13084
|
+
this.name = opts.name;
|
|
13085
|
+
this.slug = opts.slug;
|
|
13086
|
+
this.prompt = prompt;
|
|
13087
|
+
this.toolFunctions = toolFunctions;
|
|
13088
|
+
this.ifExists = opts.ifExists;
|
|
13089
|
+
this.description = opts.description;
|
|
13090
|
+
this.id = opts.id;
|
|
13091
|
+
this.functionType = functionType;
|
|
13092
|
+
this.metadata = opts.metadata;
|
|
13093
|
+
}
|
|
13094
|
+
async toFunctionDefinition(projectNameToId) {
|
|
13095
|
+
const prompt_data = {
|
|
13096
|
+
...this.prompt
|
|
13097
|
+
};
|
|
13098
|
+
if (this.toolFunctions.length > 0) {
|
|
13099
|
+
const resolvableToolFunctions = await Promise.all(
|
|
13100
|
+
this.toolFunctions.map(async (fn) => {
|
|
13101
|
+
if ("slug" in fn) {
|
|
13102
|
+
return {
|
|
13103
|
+
type: "slug",
|
|
13104
|
+
project_id: await projectNameToId.resolve(fn.project),
|
|
13105
|
+
slug: fn.slug
|
|
13106
|
+
};
|
|
13107
|
+
} else {
|
|
13108
|
+
return fn;
|
|
13109
|
+
}
|
|
13110
|
+
})
|
|
13111
|
+
);
|
|
13112
|
+
prompt_data.tool_functions = // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
|
|
13113
|
+
resolvableToolFunctions;
|
|
13114
|
+
}
|
|
13115
|
+
return {
|
|
13116
|
+
project_id: await projectNameToId.resolve(this.project),
|
|
13117
|
+
name: this.name,
|
|
13118
|
+
slug: this.slug,
|
|
13119
|
+
description: _nullishCoalesce(this.description, () => ( "")),
|
|
13120
|
+
function_data: {
|
|
13121
|
+
type: "prompt"
|
|
13122
|
+
},
|
|
13123
|
+
function_type: this.functionType,
|
|
13124
|
+
prompt_data,
|
|
13125
|
+
if_exists: this.ifExists,
|
|
13126
|
+
metadata: this.metadata
|
|
13127
|
+
};
|
|
13128
|
+
}
|
|
13129
|
+
};
|
|
13130
|
+
var promptContentsSchema = _v3.z.union([
|
|
13131
|
+
_v3.z.object({
|
|
13132
|
+
prompt: _v3.z.string()
|
|
13133
|
+
}),
|
|
13134
|
+
_v3.z.object({
|
|
13135
|
+
messages: _v3.z.array(ChatCompletionMessageParam)
|
|
13136
|
+
})
|
|
13137
|
+
]);
|
|
13138
|
+
var promptDefinitionSchema = promptContentsSchema.and(
|
|
13139
|
+
_v3.z.object({
|
|
13140
|
+
model: _v3.z.string(),
|
|
13141
|
+
params: ModelParams.optional()
|
|
13142
|
+
})
|
|
13143
|
+
);
|
|
13144
|
+
var promptDefinitionWithToolsSchema = promptDefinitionSchema.and(
|
|
13145
|
+
_v3.z.object({
|
|
13146
|
+
tools: _v3.z.array(ToolFunctionDefinition).optional()
|
|
13147
|
+
})
|
|
13148
|
+
);
|
|
13149
|
+
var PromptBuilder = class {
|
|
13150
|
+
constructor(project) {
|
|
13151
|
+
this.project = project;
|
|
13152
|
+
}
|
|
13153
|
+
create(opts) {
|
|
13154
|
+
const toolFunctions = [];
|
|
13155
|
+
const rawTools = [];
|
|
13156
|
+
for (const tool of _nullishCoalesce(opts.tools, () => ( []))) {
|
|
13157
|
+
if (tool instanceof CodeFunction) {
|
|
13158
|
+
toolFunctions.push(tool);
|
|
13159
|
+
} else if ("type" in tool && !("function" in tool)) {
|
|
13160
|
+
toolFunctions.push(tool);
|
|
13161
|
+
} else {
|
|
13162
|
+
rawTools.push(tool);
|
|
13163
|
+
}
|
|
13164
|
+
}
|
|
13165
|
+
const slug = _nullishCoalesce(opts.slug, () => ( slugify(opts.name, { lower: true, strict: true })));
|
|
13166
|
+
const promptData = promptDefinitionToPromptData(opts, rawTools);
|
|
13167
|
+
const promptRow = {
|
|
13168
|
+
id: opts.id,
|
|
13169
|
+
_xact_id: opts.version ? loadPrettyXact(opts.version) : void 0,
|
|
13170
|
+
name: opts.name,
|
|
13171
|
+
slug,
|
|
13172
|
+
prompt_data: promptData,
|
|
13173
|
+
...this.project.id !== void 0 ? { project_id: this.project.id } : {}
|
|
13174
|
+
};
|
|
13175
|
+
const prompt = new Prompt2(
|
|
13176
|
+
promptRow,
|
|
13177
|
+
{},
|
|
13178
|
+
// It doesn't make sense to specify defaults here.
|
|
13179
|
+
_nullishCoalesce(opts.noTrace, () => ( false))
|
|
13180
|
+
);
|
|
13181
|
+
const codePrompt = new CodePrompt(this.project, promptData, toolFunctions, {
|
|
13182
|
+
...opts,
|
|
13183
|
+
slug
|
|
13184
|
+
});
|
|
13185
|
+
this.project.addPrompt(codePrompt);
|
|
13186
|
+
return prompt;
|
|
13187
|
+
}
|
|
13188
|
+
};
|
|
13189
|
+
function promptDefinitionToPromptData(promptDefinition, rawTools) {
|
|
13190
|
+
const promptBlock = "messages" in promptDefinition ? {
|
|
13191
|
+
type: "chat",
|
|
13192
|
+
messages: promptDefinition.messages,
|
|
13193
|
+
tools: rawTools && rawTools.length > 0 ? JSON.stringify(rawTools) : void 0
|
|
13194
|
+
} : {
|
|
13195
|
+
type: "completion",
|
|
13196
|
+
content: promptDefinition.prompt
|
|
13197
|
+
};
|
|
13198
|
+
return {
|
|
13199
|
+
prompt: promptBlock,
|
|
13200
|
+
options: {
|
|
13201
|
+
model: promptDefinition.model,
|
|
13202
|
+
params: promptDefinition.params
|
|
13203
|
+
}
|
|
13204
|
+
};
|
|
13205
|
+
}
|
|
13206
|
+
var ProjectNameIdMap = (_class19 = class {constructor() { _class19.prototype.__init56.call(this);_class19.prototype.__init57.call(this); }
|
|
13207
|
+
__init56() {this.nameToId = {}}
|
|
13208
|
+
__init57() {this.idToName = {}}
|
|
13209
|
+
async getId(projectName) {
|
|
13210
|
+
if (!(projectName in this.nameToId)) {
|
|
13211
|
+
const response = await _internalGetGlobalState().appConn().post_json("api/project/register", {
|
|
13212
|
+
project_name: projectName
|
|
13213
|
+
});
|
|
13214
|
+
const result = _v3.z.object({
|
|
13215
|
+
project: Project
|
|
13216
|
+
}).parse(response);
|
|
13217
|
+
const projectId = result.project.id;
|
|
13218
|
+
this.nameToId[projectName] = projectId;
|
|
13219
|
+
this.idToName[projectId] = projectName;
|
|
13220
|
+
}
|
|
13221
|
+
return this.nameToId[projectName];
|
|
13222
|
+
}
|
|
13223
|
+
async getName(projectId) {
|
|
13224
|
+
if (!(projectId in this.idToName)) {
|
|
13225
|
+
const response = await _internalGetGlobalState().appConn().post_json("api/project/get", {
|
|
13226
|
+
id: projectId
|
|
13227
|
+
});
|
|
13228
|
+
const result = _v3.z.array(Project).nonempty().parse(response);
|
|
13229
|
+
const projectName = result[0].name;
|
|
13230
|
+
this.idToName[projectId] = projectName;
|
|
13231
|
+
this.nameToId[projectName] = projectId;
|
|
13232
|
+
}
|
|
13233
|
+
return this.idToName[projectId];
|
|
13234
|
+
}
|
|
13235
|
+
async resolve(project) {
|
|
13236
|
+
if (project.id) {
|
|
13237
|
+
return project.id;
|
|
13238
|
+
}
|
|
13239
|
+
return this.getId(project.name);
|
|
13240
|
+
}
|
|
13241
|
+
}, _class19);
|
|
13242
|
+
|
|
13243
|
+
// src/eval-parameters.ts
|
|
13244
|
+
var evalParametersSchema = _v3.z.record(
|
|
13245
|
+
_v3.z.string(),
|
|
13246
|
+
_v3.z.union([
|
|
13247
|
+
_v3.z.object({
|
|
13248
|
+
type: _v3.z.literal("prompt"),
|
|
13249
|
+
default: promptDefinitionWithToolsSchema.optional(),
|
|
13250
|
+
description: _v3.z.string().optional()
|
|
13251
|
+
}),
|
|
13252
|
+
_v3.z.instanceof(_v3.z.ZodType)
|
|
13253
|
+
// For Zod schemas
|
|
13254
|
+
])
|
|
13255
|
+
);
|
|
13256
|
+
function validateParameters(parameters, parameterSchema) {
|
|
13257
|
+
return Object.fromEntries(
|
|
13258
|
+
Object.entries(parameterSchema).map(([name, schema]) => {
|
|
13259
|
+
const value = parameters[name];
|
|
13260
|
+
try {
|
|
13261
|
+
if ("type" in schema && schema.type === "prompt") {
|
|
13262
|
+
const promptData = value ? PromptData.parse(value) : schema.default ? promptDefinitionToPromptData(
|
|
13263
|
+
schema.default,
|
|
13264
|
+
schema.default.tools
|
|
13265
|
+
) : void 0;
|
|
13266
|
+
if (!promptData) {
|
|
13267
|
+
throw new Error(`Parameter '${name}' is required`);
|
|
13268
|
+
}
|
|
13269
|
+
return [name, Prompt2.fromPromptData(name, promptData)];
|
|
13270
|
+
} else {
|
|
13271
|
+
const schemaCasted = schema;
|
|
13272
|
+
return [name, schemaCasted.parse(value)];
|
|
13273
|
+
}
|
|
13274
|
+
} catch (e) {
|
|
13275
|
+
console.error("Error validating parameter", name, e);
|
|
13276
|
+
throw Error(
|
|
13277
|
+
`Invalid parameter '${name}': ${e instanceof Error ? e.message : String(e)}`
|
|
13278
|
+
);
|
|
13279
|
+
}
|
|
13280
|
+
})
|
|
13281
|
+
);
|
|
13282
|
+
}
|
|
13283
|
+
|
|
13284
|
+
// src/framework.ts
|
|
13285
|
+
function BaseExperiment(options = {}) {
|
|
13286
|
+
return { _type: "BaseExperiment", ...options };
|
|
13287
|
+
}
|
|
13288
|
+
var EvalResultWithSummary = class {
|
|
13289
|
+
constructor(summary, results) {
|
|
13290
|
+
this.summary = summary;
|
|
13291
|
+
this.results = results;
|
|
13292
|
+
}
|
|
13293
|
+
/**
|
|
13294
|
+
* @deprecated Use `summary` instead.
|
|
13295
|
+
*/
|
|
13296
|
+
toString() {
|
|
13297
|
+
return JSON.stringify(this.summary);
|
|
13298
|
+
}
|
|
13299
|
+
[Symbol.for("nodejs.util.inspect.custom")]() {
|
|
13300
|
+
return `EvalResultWithSummary(summary="...", results=[...])`;
|
|
13301
|
+
}
|
|
13302
|
+
toJSON() {
|
|
13303
|
+
return {
|
|
13304
|
+
summary: this.summary,
|
|
13305
|
+
results: this.results
|
|
13306
|
+
};
|
|
13307
|
+
}
|
|
13308
|
+
};
|
|
13309
|
+
function makeEvalName(projectName, experimentName) {
|
|
13310
|
+
let out = projectName;
|
|
13311
|
+
if (experimentName) {
|
|
13312
|
+
out += ` [experimentName=${experimentName}]`;
|
|
13313
|
+
}
|
|
13314
|
+
return out;
|
|
13315
|
+
}
|
|
13316
|
+
function initExperiment2(state, options = {}) {
|
|
13317
|
+
return init({
|
|
13318
|
+
state,
|
|
13319
|
+
...options,
|
|
13320
|
+
setCurrent: false
|
|
13321
|
+
});
|
|
13322
|
+
}
|
|
13323
|
+
function callEvaluatorData(data) {
|
|
13324
|
+
const dataResult = typeof data === "function" ? data() : data;
|
|
13325
|
+
let baseExperiment = void 0;
|
|
13326
|
+
if ("_type" in dataResult && dataResult._type === "BaseExperiment") {
|
|
13327
|
+
baseExperiment = dataResult.name;
|
|
13328
|
+
}
|
|
13329
|
+
return {
|
|
13330
|
+
data: dataResult,
|
|
13331
|
+
baseExperiment
|
|
13332
|
+
};
|
|
13333
|
+
}
|
|
13334
|
+
function isAsyncIterable2(value) {
|
|
13335
|
+
return typeof value === "object" && value !== null && typeof value[Symbol.asyncIterator] === "function";
|
|
13336
|
+
}
|
|
13337
|
+
function isIterable(value) {
|
|
13338
|
+
return typeof value === "object" && value !== null && typeof value[Symbol.iterator] === "function";
|
|
13339
|
+
}
|
|
13340
|
+
globalThis._evals = {
|
|
13341
|
+
functions: [],
|
|
13342
|
+
prompts: [],
|
|
13343
|
+
evaluators: {},
|
|
13344
|
+
reporters: {}
|
|
13345
|
+
};
|
|
13346
|
+
function _initializeSpanContext() {
|
|
13347
|
+
globalThis._spanContext = { currentSpan, withCurrent, startSpan, NOOP_SPAN };
|
|
13348
|
+
}
|
|
13349
|
+
async function Eval(name, evaluator, reporterOrOpts) {
|
|
13350
|
+
const options = isEmpty2(reporterOrOpts) ? {} : typeof reporterOrOpts === "string" ? { reporter: reporterOrOpts } : "name" in reporterOrOpts ? { reporter: reporterOrOpts } : reporterOrOpts;
|
|
13351
|
+
let evalName = makeEvalName(name, evaluator.experimentName);
|
|
13352
|
+
if (globalThis._evals.evaluators[evalName]) {
|
|
13353
|
+
evalName = `${evalName}_${Object.keys(_evals).length}`;
|
|
13354
|
+
}
|
|
13355
|
+
if (globalThis._lazy_load) {
|
|
13356
|
+
globalThis._evals.evaluators[evalName] = {
|
|
13357
|
+
// eslint-disable-next-line @typescript-eslint/consistent-type-assertions
|
|
13358
|
+
evaluator: {
|
|
13359
|
+
evalName,
|
|
13360
|
+
projectName: name,
|
|
13361
|
+
...evaluator
|
|
13362
|
+
},
|
|
13363
|
+
reporter: options.reporter
|
|
13364
|
+
};
|
|
13365
|
+
_initializeSpanContext();
|
|
13366
|
+
return new EvalResultWithSummary(
|
|
13367
|
+
{
|
|
13368
|
+
scores: {},
|
|
13369
|
+
metrics: {},
|
|
13370
|
+
projectName: "",
|
|
13371
|
+
experimentName: ""
|
|
13372
|
+
},
|
|
13373
|
+
[]
|
|
13374
|
+
);
|
|
13375
|
+
}
|
|
13376
|
+
const progressReporter = _nullishCoalesce(options.progress, () => ( new SimpleProgressReporter()));
|
|
13377
|
+
const shouldCollectResults = _nullishCoalesce(options.returnResults, () => ( true));
|
|
13378
|
+
if (typeof options.reporter === "string") {
|
|
13379
|
+
throw new Error(
|
|
13380
|
+
"Must specify a reporter object, not a name. Can only specify reporter names when running 'braintrust eval'"
|
|
13381
|
+
);
|
|
13382
|
+
}
|
|
13383
|
+
const resolvedReporter = options.reporter || defaultReporter;
|
|
13384
|
+
try {
|
|
13385
|
+
const { data, baseExperiment: defaultBaseExperiment } = callEvaluatorData(
|
|
13386
|
+
evaluator.data
|
|
13387
|
+
);
|
|
13388
|
+
const experiment = options.parent || options.noSendLogs ? null : initExperiment2(evaluator.state, {
|
|
13389
|
+
...evaluator.projectId ? { projectId: evaluator.projectId } : { project: name },
|
|
13390
|
+
experiment: evaluator.experimentName,
|
|
13391
|
+
description: evaluator.description,
|
|
13392
|
+
metadata: evaluator.metadata,
|
|
13393
|
+
isPublic: evaluator.isPublic,
|
|
13394
|
+
update: evaluator.update,
|
|
13395
|
+
baseExperiment: _nullishCoalesce(evaluator.baseExperimentName, () => ( defaultBaseExperiment)),
|
|
13396
|
+
baseExperimentId: evaluator.baseExperimentId,
|
|
13397
|
+
gitMetadataSettings: evaluator.gitMetadataSettings,
|
|
13398
|
+
repoInfo: evaluator.repoInfo,
|
|
13399
|
+
dataset: Dataset2.isDataset(data) ? data : void 0
|
|
13400
|
+
});
|
|
13401
|
+
if (experiment && typeof process !== "undefined" && globalThis.BRAINTRUST_CONTEXT_MANAGER !== void 0) {
|
|
13402
|
+
await experiment._waitForId();
|
|
13403
|
+
}
|
|
13404
|
+
if (experiment && options.onStart) {
|
|
13405
|
+
const summary = await experiment.summarize({ summarizeScores: false });
|
|
13406
|
+
options.onStart(summary);
|
|
13407
|
+
}
|
|
13408
|
+
try {
|
|
13409
|
+
const evalDef = {
|
|
13410
|
+
evalName,
|
|
13411
|
+
projectName: name,
|
|
13412
|
+
...evaluator,
|
|
13413
|
+
data
|
|
13414
|
+
};
|
|
13415
|
+
let ret;
|
|
13416
|
+
if (options.parent) {
|
|
13417
|
+
ret = await withParent(
|
|
13418
|
+
options.parent,
|
|
13419
|
+
() => runEvaluator(
|
|
13420
|
+
null,
|
|
13421
|
+
evalDef,
|
|
13422
|
+
progressReporter,
|
|
13423
|
+
[],
|
|
13424
|
+
options.stream,
|
|
13425
|
+
options.parameters,
|
|
13426
|
+
shouldCollectResults
|
|
13427
|
+
),
|
|
13428
|
+
evaluator.state
|
|
13429
|
+
);
|
|
13430
|
+
} else {
|
|
13431
|
+
ret = await runEvaluator(
|
|
13432
|
+
experiment,
|
|
13433
|
+
evalDef,
|
|
13434
|
+
progressReporter,
|
|
13435
|
+
[],
|
|
13436
|
+
options.stream,
|
|
13437
|
+
options.parameters,
|
|
13438
|
+
shouldCollectResults
|
|
13439
|
+
);
|
|
13440
|
+
}
|
|
13441
|
+
progressReporter.stop();
|
|
13442
|
+
resolvedReporter.reportEval(evalDef, ret, {
|
|
13443
|
+
verbose: true,
|
|
13444
|
+
jsonl: false
|
|
13445
|
+
});
|
|
13446
|
+
return ret;
|
|
13447
|
+
} finally {
|
|
13448
|
+
if (experiment) {
|
|
13449
|
+
await experiment.flush().catch(console.error);
|
|
13450
|
+
} else if (options.parent) {
|
|
13451
|
+
await flush().catch(console.error);
|
|
13452
|
+
}
|
|
13453
|
+
}
|
|
13454
|
+
} finally {
|
|
13455
|
+
progressReporter.stop();
|
|
13456
|
+
}
|
|
13457
|
+
}
|
|
13458
|
+
function Reporter(name, reporter) {
|
|
13459
|
+
const ret = { name, ...reporter };
|
|
13460
|
+
if (_evals.reporters[name]) {
|
|
13461
|
+
throw new Error(`Reporter ${name} already exists`);
|
|
13462
|
+
}
|
|
13463
|
+
if (globalThis._lazy_load) {
|
|
13464
|
+
_evals.reporters[name] = ret;
|
|
13465
|
+
}
|
|
13466
|
+
return ret;
|
|
13467
|
+
}
|
|
13468
|
+
function serializeJSONWithPlainString(v) {
|
|
13469
|
+
if (typeof v === "string") {
|
|
13470
|
+
return v;
|
|
13471
|
+
} else {
|
|
13472
|
+
return JSON.stringify(v);
|
|
13473
|
+
}
|
|
13474
|
+
}
|
|
13475
|
+
function evaluateFilter(object, filter2) {
|
|
13476
|
+
const { path, pattern } = filter2;
|
|
13477
|
+
const key = path.reduce(
|
|
13478
|
+
(acc, p) => typeof acc === "object" && acc !== null ? (
|
|
13479
|
+
// eslint-disable-next-line @typescript-eslint/consistent-type-assertions
|
|
13480
|
+
acc[p]
|
|
13481
|
+
) : void 0,
|
|
13482
|
+
object
|
|
13483
|
+
);
|
|
13484
|
+
if (key === void 0) {
|
|
13485
|
+
return false;
|
|
13486
|
+
}
|
|
13487
|
+
return pattern.test(serializeJSONWithPlainString(key));
|
|
13488
|
+
}
|
|
13489
|
+
function scorerName(scorer, scorer_idx) {
|
|
13490
|
+
return scorer.name || `scorer_${scorer_idx}`;
|
|
13491
|
+
}
|
|
13492
|
+
async function runEvaluator(experiment, evaluator, progressReporter, filters, stream, parameters, collectResults = true) {
|
|
13493
|
+
return await runEvaluatorInternal(
|
|
13494
|
+
experiment,
|
|
13495
|
+
evaluator,
|
|
13496
|
+
progressReporter,
|
|
13497
|
+
filters,
|
|
13498
|
+
stream,
|
|
13499
|
+
parameters,
|
|
13500
|
+
collectResults
|
|
13501
|
+
);
|
|
13502
|
+
}
|
|
13503
|
+
var defaultErrorScoreHandler = ({
|
|
13504
|
+
rootSpan,
|
|
13505
|
+
data: _,
|
|
13506
|
+
unhandledScores
|
|
13507
|
+
}) => {
|
|
13508
|
+
const scores = Object.fromEntries(unhandledScores.map((s) => [s, 0]));
|
|
13509
|
+
rootSpan.log({ scores });
|
|
13510
|
+
return scores;
|
|
13511
|
+
};
|
|
13512
|
+
async function runEvaluatorInternal(experiment, evaluator, progressReporter, filters, stream, parameters, collectResults) {
|
|
13513
|
+
if (typeof evaluator.data === "string") {
|
|
13514
|
+
throw new Error("Unimplemented: string data paths");
|
|
13515
|
+
}
|
|
13516
|
+
let dataResult = typeof evaluator.data === "function" ? evaluator.data() : evaluator.data;
|
|
13517
|
+
parameters = validateParameters(_nullishCoalesce(parameters, () => ( {})), _nullishCoalesce(evaluator.parameters, () => ( {})));
|
|
13518
|
+
if ("_type" in dataResult) {
|
|
13519
|
+
if (dataResult._type !== "BaseExperiment") {
|
|
13520
|
+
throw new Error("Invalid _type");
|
|
13521
|
+
}
|
|
13522
|
+
if (!experiment) {
|
|
13523
|
+
throw new Error(
|
|
13524
|
+
"Cannot use BaseExperiment() without connecting to Braintrust (you most likely set --no-send-logs)"
|
|
13525
|
+
);
|
|
13526
|
+
}
|
|
13527
|
+
let name = dataResult.name;
|
|
13528
|
+
if (isEmpty2(name)) {
|
|
13529
|
+
const baseExperiment = await experiment.fetchBaseExperiment();
|
|
13530
|
+
if (!baseExperiment) {
|
|
13531
|
+
throw new Error("BaseExperiment() failed to fetch base experiment");
|
|
13532
|
+
}
|
|
13533
|
+
name = baseExperiment.name;
|
|
13534
|
+
}
|
|
13535
|
+
dataResult = initExperiment2(evaluator.state, {
|
|
13536
|
+
...evaluator.projectId ? { projectId: evaluator.projectId } : { project: evaluator.projectName },
|
|
13537
|
+
experiment: name,
|
|
13538
|
+
open: true
|
|
13539
|
+
}).asDataset();
|
|
13540
|
+
}
|
|
13541
|
+
const resolvedDataResult = dataResult instanceof Promise ? await dataResult : dataResult;
|
|
13542
|
+
const dataIterable = (() => {
|
|
13543
|
+
if (isAsyncIterable2(resolvedDataResult)) {
|
|
13544
|
+
return resolvedDataResult;
|
|
13545
|
+
}
|
|
13546
|
+
if (Array.isArray(resolvedDataResult) || isIterable(resolvedDataResult)) {
|
|
13547
|
+
const iterable = resolvedDataResult;
|
|
13548
|
+
return (async function* () {
|
|
13549
|
+
for (const datum of iterable) {
|
|
13550
|
+
yield datum;
|
|
13551
|
+
}
|
|
13552
|
+
})();
|
|
13553
|
+
}
|
|
13554
|
+
throw new Error(
|
|
13555
|
+
"Evaluator data must be an array, iterable, or async iterable"
|
|
13556
|
+
);
|
|
13557
|
+
})();
|
|
13558
|
+
progressReporter.start(evaluator.evalName, 0);
|
|
13559
|
+
const collectedResults = [];
|
|
13560
|
+
const localScoreAccumulator = experiment ? null : {};
|
|
13561
|
+
let cancelled = false;
|
|
13562
|
+
let scheduledTrials = 0;
|
|
13563
|
+
const q = queue(
|
|
13564
|
+
async ({
|
|
13565
|
+
datum,
|
|
13566
|
+
trialIndex
|
|
13567
|
+
}) => {
|
|
13568
|
+
if (cancelled) {
|
|
13569
|
+
return;
|
|
13570
|
+
}
|
|
13571
|
+
const eventDataset = experiment ? experiment.dataset : Dataset2.isDataset(evaluator.data) ? evaluator.data : void 0;
|
|
13572
|
+
const baseEvent = {
|
|
13573
|
+
name: "eval",
|
|
13574
|
+
spanAttributes: {
|
|
13575
|
+
type: "eval" /* EVAL */
|
|
13576
|
+
},
|
|
13577
|
+
event: {
|
|
13578
|
+
input: datum.input,
|
|
13579
|
+
expected: "expected" in datum ? datum.expected : void 0,
|
|
13580
|
+
tags: datum.tags,
|
|
13581
|
+
origin: eventDataset && datum.id && datum._xact_id ? {
|
|
13582
|
+
object_type: "dataset",
|
|
13583
|
+
object_id: await eventDataset.id,
|
|
13584
|
+
id: datum.id,
|
|
13585
|
+
created: datum.created,
|
|
13586
|
+
_xact_id: datum._xact_id
|
|
13587
|
+
} : void 0,
|
|
13588
|
+
...datum.upsert_id ? { id: datum.upsert_id } : {}
|
|
13589
|
+
}
|
|
13590
|
+
};
|
|
13591
|
+
const callback = async (rootSpan) => {
|
|
13592
|
+
let metadata = {
|
|
13593
|
+
..."metadata" in datum ? datum.metadata : {}
|
|
13594
|
+
};
|
|
13595
|
+
const expected = "expected" in datum ? datum.expected : void 0;
|
|
13596
|
+
let output = void 0;
|
|
13597
|
+
let error = void 0;
|
|
13598
|
+
let tags = [..._nullishCoalesce(datum.tags, () => ( []))];
|
|
13599
|
+
const scores = {};
|
|
13600
|
+
const scorerNames = evaluator.scores.map(scorerName);
|
|
13601
|
+
let unhandledScores = scorerNames;
|
|
13602
|
+
try {
|
|
13603
|
+
const meta = (o) => metadata = { ...metadata, ...o };
|
|
13604
|
+
await rootSpan.traced(
|
|
13605
|
+
async (span) => {
|
|
13606
|
+
const hooksForTask = {
|
|
13607
|
+
meta,
|
|
13608
|
+
metadata,
|
|
13609
|
+
expected,
|
|
13610
|
+
span,
|
|
13611
|
+
parameters: _nullishCoalesce(parameters, () => ( {})),
|
|
13612
|
+
reportProgress: (event) => {
|
|
13613
|
+
_optionalChain([stream, 'optionalCall', _234 => _234({
|
|
13614
|
+
...event,
|
|
13615
|
+
id: rootSpan.id,
|
|
13616
|
+
origin: _optionalChain([baseEvent, 'access', _235 => _235.event, 'optionalAccess', _236 => _236.origin]),
|
|
13617
|
+
name: evaluator.evalName,
|
|
13618
|
+
object_type: "task"
|
|
13619
|
+
})]);
|
|
13620
|
+
},
|
|
13621
|
+
trialIndex,
|
|
13622
|
+
tags
|
|
13623
|
+
};
|
|
13624
|
+
const outputResult = evaluator.task(datum.input, hooksForTask);
|
|
13625
|
+
if (outputResult instanceof Promise) {
|
|
13626
|
+
output = await outputResult;
|
|
13627
|
+
} else {
|
|
13628
|
+
output = outputResult;
|
|
13629
|
+
}
|
|
13630
|
+
tags = _nullishCoalesce(hooksForTask.tags, () => ( []));
|
|
13631
|
+
span.log({ output });
|
|
13632
|
+
},
|
|
13633
|
+
{
|
|
13634
|
+
name: "task",
|
|
13635
|
+
spanAttributes: { type: "task" /* TASK */ },
|
|
13636
|
+
event: { input: datum.input }
|
|
13637
|
+
}
|
|
13638
|
+
);
|
|
13639
|
+
if (tags.length) {
|
|
13640
|
+
rootSpan.log({ output, metadata, expected, tags });
|
|
13641
|
+
} else {
|
|
13642
|
+
rootSpan.log({ output, metadata, expected });
|
|
13643
|
+
}
|
|
13644
|
+
const scoringArgs = {
|
|
13645
|
+
input: datum.input,
|
|
13646
|
+
expected: "expected" in datum ? datum.expected : void 0,
|
|
13647
|
+
metadata,
|
|
13648
|
+
output
|
|
13649
|
+
};
|
|
13650
|
+
const scoreResults = await Promise.all(
|
|
13651
|
+
evaluator.scores.map(async (score, score_idx) => {
|
|
13652
|
+
try {
|
|
13653
|
+
const runScorer = async (span) => {
|
|
13654
|
+
const scoreResult = score(scoringArgs);
|
|
13655
|
+
const scoreValue = scoreResult instanceof Promise ? await scoreResult : scoreResult;
|
|
13656
|
+
if (scoreValue === null) {
|
|
13657
|
+
return null;
|
|
13658
|
+
}
|
|
13659
|
+
if (Array.isArray(scoreValue)) {
|
|
13660
|
+
for (const s of scoreValue) {
|
|
13661
|
+
if (!(typeof s === "object" && !isEmpty2(s))) {
|
|
13662
|
+
throw new Error(
|
|
13663
|
+
`When returning an array of scores, each score must be a non-empty object. Got: ${JSON.stringify(
|
|
13664
|
+
s
|
|
13665
|
+
)}`
|
|
13666
|
+
);
|
|
13667
|
+
}
|
|
13668
|
+
}
|
|
13669
|
+
}
|
|
13670
|
+
const results2 = Array.isArray(scoreValue) ? scoreValue : typeof scoreValue === "object" && !isEmpty2(scoreValue) ? [scoreValue] : [
|
|
13671
|
+
{
|
|
13672
|
+
name: scorerNames[score_idx],
|
|
13673
|
+
score: scoreValue
|
|
13674
|
+
}
|
|
13675
|
+
];
|
|
13676
|
+
const getOtherFields = (s) => {
|
|
13677
|
+
const { metadata: _metadata, name: _name, ...rest } = s;
|
|
13678
|
+
return rest;
|
|
13679
|
+
};
|
|
13680
|
+
const resultMetadata = results2.length === 1 ? results2[0].metadata : results2.reduce(
|
|
13681
|
+
(prev, s) => mergeDicts(prev, {
|
|
13682
|
+
[s.name]: s.metadata
|
|
13683
|
+
}),
|
|
13684
|
+
{}
|
|
13685
|
+
);
|
|
13686
|
+
const resultOutput = results2.length === 1 ? getOtherFields(results2[0]) : results2.reduce(
|
|
13687
|
+
(prev, s) => mergeDicts(prev, { [s.name]: getOtherFields(s) }),
|
|
13688
|
+
{}
|
|
13689
|
+
);
|
|
13690
|
+
const scores2 = results2.reduce(
|
|
13691
|
+
(prev, s) => mergeDicts(prev, { [s.name]: s.score }),
|
|
13692
|
+
{}
|
|
13693
|
+
);
|
|
13694
|
+
span.log({
|
|
13695
|
+
output: resultOutput,
|
|
13696
|
+
metadata: resultMetadata,
|
|
13697
|
+
scores: scores2
|
|
13698
|
+
});
|
|
13699
|
+
return results2;
|
|
13700
|
+
};
|
|
13701
|
+
const results = await rootSpan.traced(runScorer, {
|
|
13702
|
+
name: scorerNames[score_idx],
|
|
13703
|
+
spanAttributes: {
|
|
13704
|
+
type: "score" /* SCORE */
|
|
13705
|
+
},
|
|
13706
|
+
event: { input: scoringArgs }
|
|
13707
|
+
});
|
|
13708
|
+
return { kind: "score", value: results };
|
|
13709
|
+
} catch (e) {
|
|
13710
|
+
return { kind: "error", value: e };
|
|
13711
|
+
}
|
|
13712
|
+
})
|
|
13713
|
+
);
|
|
13714
|
+
const failingScorersAndResults = [];
|
|
13715
|
+
scoreResults.forEach((results, i) => {
|
|
13716
|
+
const name = scorerNames[i];
|
|
13717
|
+
if (results.kind === "score") {
|
|
13718
|
+
(results.value || []).forEach((result) => {
|
|
13719
|
+
scores[result.name] = result.score;
|
|
13720
|
+
});
|
|
13721
|
+
} else {
|
|
13722
|
+
failingScorersAndResults.push({ name, error: results.value });
|
|
13723
|
+
}
|
|
13724
|
+
});
|
|
13725
|
+
unhandledScores = null;
|
|
13726
|
+
if (failingScorersAndResults.length) {
|
|
13727
|
+
const scorerErrors = Object.fromEntries(
|
|
13728
|
+
failingScorersAndResults.map(({ name, error: error2 }) => [
|
|
13729
|
+
name,
|
|
13730
|
+
error2 instanceof Error ? error2.stack : `${error2}`
|
|
13731
|
+
])
|
|
13732
|
+
);
|
|
13733
|
+
metadata["scorer_errors"] = scorerErrors;
|
|
13734
|
+
rootSpan.log({
|
|
13735
|
+
metadata: { scorer_errors: scorerErrors }
|
|
13736
|
+
});
|
|
13737
|
+
const names = Object.keys(scorerErrors).join(", ");
|
|
13738
|
+
const errors = failingScorersAndResults.map((item) => item.error);
|
|
13739
|
+
unhandledScores = Object.keys(scorerErrors);
|
|
13740
|
+
console.warn(
|
|
13741
|
+
`Found exceptions for the following scorers: ${names}`,
|
|
13742
|
+
errors
|
|
13743
|
+
);
|
|
13744
|
+
}
|
|
13745
|
+
} catch (e) {
|
|
13746
|
+
logError(rootSpan, e);
|
|
13747
|
+
error = e;
|
|
13748
|
+
} finally {
|
|
13749
|
+
progressReporter.increment(evaluator.evalName);
|
|
13750
|
+
}
|
|
13751
|
+
const mergedScores = {
|
|
13752
|
+
...evaluator.errorScoreHandler && unhandledScores ? evaluator.errorScoreHandler({
|
|
13753
|
+
rootSpan,
|
|
13754
|
+
data: datum,
|
|
13755
|
+
unhandledScores
|
|
13756
|
+
}) : void 0,
|
|
13757
|
+
...scores
|
|
13758
|
+
};
|
|
13759
|
+
if (localScoreAccumulator) {
|
|
13760
|
+
accumulateScores(localScoreAccumulator, mergedScores);
|
|
13761
|
+
}
|
|
13762
|
+
if (collectResults) {
|
|
13763
|
+
collectedResults.push({
|
|
13764
|
+
input: datum.input,
|
|
13765
|
+
..."expected" in datum ? { expected: datum.expected } : {},
|
|
13766
|
+
output,
|
|
13767
|
+
tags: tags.length ? tags : void 0,
|
|
13768
|
+
metadata,
|
|
13769
|
+
scores: mergedScores,
|
|
13770
|
+
error,
|
|
13771
|
+
origin: _optionalChain([baseEvent, 'access', _237 => _237.event, 'optionalAccess', _238 => _238.origin])
|
|
13772
|
+
});
|
|
13773
|
+
}
|
|
13774
|
+
};
|
|
13775
|
+
if (!experiment) {
|
|
13776
|
+
return await traced(callback, {
|
|
13777
|
+
...baseEvent,
|
|
13778
|
+
state: evaluator.state
|
|
13779
|
+
});
|
|
13780
|
+
} else {
|
|
13781
|
+
const result = await experiment.traced(callback, baseEvent);
|
|
13782
|
+
if (evaluator.maxConcurrency !== void 0) {
|
|
13783
|
+
await experiment.flush();
|
|
13784
|
+
}
|
|
13785
|
+
return result;
|
|
13786
|
+
}
|
|
13787
|
+
},
|
|
13788
|
+
Math.max(_nullishCoalesce(evaluator.maxConcurrency, () => ( Number.MAX_SAFE_INTEGER)), 1)
|
|
13789
|
+
);
|
|
13790
|
+
const enqueuePromise = (async () => {
|
|
13791
|
+
for await (const datum of dataIterable) {
|
|
13792
|
+
if (cancelled) {
|
|
13793
|
+
break;
|
|
13794
|
+
}
|
|
13795
|
+
if (!filters.every((f) => evaluateFilter(datum, f))) {
|
|
13796
|
+
continue;
|
|
13797
|
+
}
|
|
13798
|
+
const trialCount = _nullishCoalesce(evaluator.trialCount, () => ( 1));
|
|
13799
|
+
for (let trialIndex = 0; trialIndex < trialCount; trialIndex++) {
|
|
13800
|
+
if (cancelled) {
|
|
13801
|
+
break;
|
|
13802
|
+
}
|
|
13803
|
+
scheduledTrials++;
|
|
13804
|
+
_optionalChain([progressReporter, 'access', _239 => _239.setTotal, 'optionalCall', _240 => _240(evaluator.evalName, scheduledTrials)]);
|
|
13805
|
+
q.push({ datum, trialIndex });
|
|
13806
|
+
}
|
|
13807
|
+
}
|
|
13808
|
+
})();
|
|
13809
|
+
const cancel = async () => {
|
|
13810
|
+
await new Promise((_, reject2) => {
|
|
13811
|
+
if (cancelled) {
|
|
13812
|
+
reject2(new InternalAbortError("Evaluator already cancelled"));
|
|
13813
|
+
return;
|
|
13814
|
+
}
|
|
13815
|
+
let timeoutId;
|
|
13816
|
+
let abortHandler;
|
|
13817
|
+
const rejectOnce = (error) => {
|
|
13818
|
+
if (cancelled) {
|
|
13819
|
+
return;
|
|
13820
|
+
}
|
|
13821
|
+
cancelled = true;
|
|
13822
|
+
if (timeoutId) {
|
|
13823
|
+
clearTimeout(timeoutId);
|
|
13824
|
+
timeoutId = void 0;
|
|
13825
|
+
}
|
|
13826
|
+
if (abortHandler && evaluator.signal) {
|
|
13827
|
+
evaluator.signal.removeEventListener("abort", abortHandler);
|
|
13828
|
+
}
|
|
13829
|
+
reject2(error);
|
|
13830
|
+
};
|
|
13831
|
+
if (evaluator.timeout) {
|
|
13832
|
+
timeoutId = setTimeout(() => {
|
|
13833
|
+
rejectOnce(new InternalAbortError("Evaluator timed out"));
|
|
13834
|
+
}, evaluator.timeout);
|
|
13835
|
+
}
|
|
13836
|
+
if (evaluator.signal) {
|
|
13837
|
+
abortHandler = () => {
|
|
13838
|
+
rejectOnce(new InternalAbortError("Evaluator aborted"));
|
|
13839
|
+
};
|
|
13840
|
+
evaluator.signal.addEventListener("abort", abortHandler);
|
|
13841
|
+
}
|
|
13842
|
+
});
|
|
13843
|
+
};
|
|
13844
|
+
const waitForQueue = (async () => {
|
|
13845
|
+
await enqueuePromise;
|
|
13846
|
+
if (q.idle()) {
|
|
13847
|
+
return;
|
|
13848
|
+
}
|
|
13849
|
+
await q.drain();
|
|
13850
|
+
})();
|
|
13851
|
+
try {
|
|
13852
|
+
await Promise.race([waitForQueue, cancel()]);
|
|
13853
|
+
} catch (e) {
|
|
13854
|
+
q.kill();
|
|
13855
|
+
if (e instanceof InternalAbortError) {
|
|
13856
|
+
if (isomorph_default.getEnv("BRAINTRUST_VERBOSE")) {
|
|
13857
|
+
console.warn("Evaluator cancelled:", e.message);
|
|
13858
|
+
}
|
|
13859
|
+
}
|
|
13860
|
+
throw e;
|
|
13861
|
+
} finally {
|
|
13862
|
+
if (!collectResults) {
|
|
13863
|
+
collectedResults.length = 0;
|
|
13864
|
+
}
|
|
13865
|
+
}
|
|
13866
|
+
const summary = experiment ? await experiment.summarize({ summarizeScores: evaluator.summarizeScores }) : buildLocalSummary(
|
|
13867
|
+
evaluator,
|
|
13868
|
+
collectResults ? collectedResults : [],
|
|
13869
|
+
_nullishCoalesce(localScoreAccumulator, () => ( void 0))
|
|
13870
|
+
);
|
|
13871
|
+
return new EvalResultWithSummary(
|
|
13872
|
+
summary,
|
|
13873
|
+
collectResults ? collectedResults : []
|
|
13874
|
+
);
|
|
13875
|
+
}
|
|
13876
|
+
var warning = (text) => `Warning: ${text}`;
|
|
13877
|
+
function logError2(e, verbose) {
|
|
13878
|
+
if (!verbose) {
|
|
13879
|
+
console.error(`${e}`);
|
|
13880
|
+
} else {
|
|
13881
|
+
console.error(e);
|
|
13882
|
+
}
|
|
13883
|
+
}
|
|
13884
|
+
function accumulateScores(accumulator, scores) {
|
|
13885
|
+
for (const [name, score] of Object.entries(scores)) {
|
|
13886
|
+
if (score === null || score === void 0) {
|
|
13887
|
+
continue;
|
|
13888
|
+
}
|
|
13889
|
+
const existing = _nullishCoalesce(accumulator[name], () => ( { total: 0, count: 0 }));
|
|
13890
|
+
accumulator[name] = {
|
|
13891
|
+
total: existing.total + score,
|
|
13892
|
+
count: existing.count + 1
|
|
13893
|
+
};
|
|
13894
|
+
}
|
|
13895
|
+
}
|
|
13896
|
+
function ensureScoreAccumulator(results) {
|
|
13897
|
+
const accumulator = {};
|
|
13898
|
+
for (const result of results) {
|
|
13899
|
+
accumulateScores(accumulator, result.scores);
|
|
13900
|
+
}
|
|
13901
|
+
return accumulator;
|
|
13902
|
+
}
|
|
13903
|
+
function buildLocalSummary(evaluator, results, precomputedScores) {
|
|
13904
|
+
const scoresByName = _nullishCoalesce(precomputedScores, () => ( ensureScoreAccumulator(results)));
|
|
13905
|
+
return {
|
|
13906
|
+
projectName: evaluator.projectName,
|
|
13907
|
+
experimentName: evaluator.evalName,
|
|
13908
|
+
scores: Object.fromEntries(
|
|
13909
|
+
Object.entries(scoresByName).map(([name, { total, count }]) => [
|
|
13910
|
+
name,
|
|
13911
|
+
{
|
|
13912
|
+
name,
|
|
13913
|
+
score: count === 0 ? 0 : total / count,
|
|
13914
|
+
improvements: 0,
|
|
13915
|
+
regressions: 0
|
|
13916
|
+
}
|
|
13917
|
+
])
|
|
13918
|
+
)
|
|
13919
|
+
};
|
|
13920
|
+
}
|
|
13921
|
+
function reportFailures(evaluator, failingResults, { verbose, jsonl }) {
|
|
13922
|
+
if (failingResults.length > 0) {
|
|
13923
|
+
console.error(
|
|
13924
|
+
warning(
|
|
13925
|
+
`Evaluator ${evaluator.evalName} failed with ${failingResults.length} error${failingResults.length === 1 ? "" : "s"}. This evaluation ("${evaluator.evalName}") will not be fully logged.`
|
|
13926
|
+
)
|
|
13927
|
+
);
|
|
13928
|
+
if (jsonl) {
|
|
13929
|
+
console.log(
|
|
13930
|
+
JSON.stringify({
|
|
13931
|
+
evaluatorName: evaluator.evalName,
|
|
13932
|
+
errors: failingResults.map(
|
|
13933
|
+
(r) => `${r.error instanceof Error ? r.error.stack : r.error}`
|
|
13934
|
+
)
|
|
13935
|
+
})
|
|
13936
|
+
);
|
|
13937
|
+
} else {
|
|
13938
|
+
for (const result of failingResults) {
|
|
13939
|
+
logError2(result.error, verbose);
|
|
13940
|
+
}
|
|
13941
|
+
}
|
|
13942
|
+
if (!verbose && !jsonl) {
|
|
13943
|
+
console.error(warning("Add --verbose to see full stack traces."));
|
|
13944
|
+
}
|
|
13945
|
+
}
|
|
13946
|
+
}
|
|
13947
|
+
var defaultReporter = {
|
|
13948
|
+
name: "Braintrust default reporter",
|
|
13949
|
+
async reportEval(evaluator, result, { verbose, jsonl }) {
|
|
13950
|
+
const { results, summary } = result;
|
|
13951
|
+
const failingResults = results.filter(
|
|
13952
|
+
(r) => r.error !== void 0
|
|
13953
|
+
);
|
|
13954
|
+
if (failingResults.length > 0) {
|
|
13955
|
+
reportFailures(evaluator, failingResults, { verbose, jsonl });
|
|
13956
|
+
}
|
|
13957
|
+
if (jsonl) {
|
|
13958
|
+
isomorph_default.writeln(JSON.stringify(summary));
|
|
13959
|
+
} else {
|
|
13960
|
+
isomorph_default.writeln("Experiment summary");
|
|
13961
|
+
isomorph_default.writeln("==================");
|
|
13962
|
+
if (summary.comparisonExperimentName) {
|
|
13963
|
+
isomorph_default.writeln(
|
|
13964
|
+
`${summary.comparisonExperimentName} (baseline) <- ${summary.experimentName} (comparison)`
|
|
13965
|
+
);
|
|
13966
|
+
isomorph_default.writeln("");
|
|
13967
|
+
}
|
|
13968
|
+
const hasScores = Object.keys(summary.scores).length > 0;
|
|
13969
|
+
const hasMetrics = Object.keys(_nullishCoalesce(summary.metrics, () => ( {}))).length > 0;
|
|
13970
|
+
const hasComparison = !!summary.comparisonExperimentName;
|
|
13971
|
+
if (hasScores || hasMetrics) {
|
|
13972
|
+
if (hasComparison) {
|
|
13973
|
+
isomorph_default.writeln(
|
|
13974
|
+
"Name Value Change Improvements Regressions"
|
|
13975
|
+
);
|
|
13976
|
+
isomorph_default.writeln(
|
|
13977
|
+
"----------------------------------------------------------------"
|
|
13978
|
+
);
|
|
13979
|
+
}
|
|
13980
|
+
for (const score of Object.values(summary.scores)) {
|
|
13981
|
+
const scorePercent = (score.score * 100).toFixed(2);
|
|
13982
|
+
const scoreValue = `${scorePercent}%`;
|
|
13983
|
+
if (hasComparison) {
|
|
13984
|
+
let diffString = "-";
|
|
13985
|
+
if (!isEmpty2(score.diff)) {
|
|
13986
|
+
const diffPercent = (score.diff * 100).toFixed(2);
|
|
13987
|
+
const diffSign = score.diff > 0 ? "+" : "";
|
|
13988
|
+
diffString = `${diffSign}${diffPercent}%`;
|
|
13989
|
+
}
|
|
13990
|
+
const improvements = score.improvements > 0 ? score.improvements.toString() : "-";
|
|
13991
|
+
const regressions = score.regressions > 0 ? score.regressions.toString() : "-";
|
|
13992
|
+
isomorph_default.writeln(
|
|
13993
|
+
`${score.name.padEnd(18)} ${scoreValue.padStart(10)} ${diffString.padStart(10)} ${improvements.padStart(12)} ${regressions.padStart(11)}`
|
|
13994
|
+
);
|
|
13995
|
+
} else {
|
|
13996
|
+
isomorph_default.writeln(`${score.name.padEnd(20)} ${scoreValue.padStart(15)}`);
|
|
13997
|
+
}
|
|
13998
|
+
}
|
|
13999
|
+
for (const metric of Object.values(_nullishCoalesce(summary.metrics, () => ( {})))) {
|
|
14000
|
+
const fractionDigits = Number.isInteger(metric.metric) ? 0 : 2;
|
|
14001
|
+
const formattedValue = metric.metric.toFixed(fractionDigits);
|
|
14002
|
+
const metricValue = metric.unit === "$" ? `${metric.unit}${formattedValue}` : `${formattedValue}${metric.unit}`;
|
|
14003
|
+
if (hasComparison) {
|
|
14004
|
+
let diffString = "-";
|
|
14005
|
+
if (!isEmpty2(metric.diff)) {
|
|
14006
|
+
const diffPercent = (metric.diff * 100).toFixed(2);
|
|
14007
|
+
const diffSign = metric.diff > 0 ? "+" : "";
|
|
14008
|
+
diffString = `${diffSign}${diffPercent}%`;
|
|
14009
|
+
}
|
|
14010
|
+
const improvements = metric.improvements > 0 ? metric.improvements.toString() : "-";
|
|
14011
|
+
const regressions = metric.regressions > 0 ? metric.regressions.toString() : "-";
|
|
14012
|
+
isomorph_default.writeln(
|
|
14013
|
+
`${metric.name.padEnd(18)} ${metricValue.padStart(10)} ${diffString.padStart(10)} ${improvements.padStart(12)} ${regressions.padStart(11)}`
|
|
14014
|
+
);
|
|
14015
|
+
} else {
|
|
14016
|
+
isomorph_default.writeln(
|
|
14017
|
+
`${metric.name.padEnd(20)} ${metricValue.padStart(15)}`
|
|
14018
|
+
);
|
|
14019
|
+
}
|
|
14020
|
+
}
|
|
14021
|
+
}
|
|
14022
|
+
if (summary.experimentUrl) {
|
|
14023
|
+
isomorph_default.writeln("");
|
|
14024
|
+
isomorph_default.writeln(`View results for ${summary.experimentName}`);
|
|
14025
|
+
isomorph_default.writeln(`See results at ${summary.experimentUrl}`);
|
|
14026
|
+
}
|
|
14027
|
+
}
|
|
14028
|
+
isomorph_default.writeln("");
|
|
14029
|
+
return failingResults.length === 0;
|
|
14030
|
+
},
|
|
14031
|
+
async reportRun(evalReports) {
|
|
14032
|
+
return evalReports.every((r) => r);
|
|
14033
|
+
}
|
|
14034
|
+
};
|
|
14035
|
+
|
|
14036
|
+
// dev/types.ts
|
|
14037
|
+
|
|
14038
|
+
var evalBodySchema = _v3.z.object({
|
|
14039
|
+
name: _v3.z.string(),
|
|
14040
|
+
parameters: _v3.z.record(_v3.z.string(), _v3.z.unknown()).nullish(),
|
|
14041
|
+
data: RunEval.shape.data,
|
|
14042
|
+
scores: _v3.z.array(
|
|
14043
|
+
_v3.z.object({
|
|
14044
|
+
function_id: FunctionId,
|
|
14045
|
+
name: _v3.z.string()
|
|
14046
|
+
})
|
|
14047
|
+
).nullish(),
|
|
14048
|
+
experiment_name: _v3.z.string().nullish(),
|
|
14049
|
+
project_id: _v3.z.string().nullish(),
|
|
14050
|
+
parent: InvokeParent.optional(),
|
|
14051
|
+
stream: _v3.z.boolean().optional()
|
|
14052
|
+
});
|
|
14053
|
+
var evalParametersSerializedSchema = _v3.z.record(
|
|
14054
|
+
_v3.z.string(),
|
|
14055
|
+
_v3.z.union([
|
|
14056
|
+
_v3.z.object({
|
|
14057
|
+
type: _v3.z.literal("prompt"),
|
|
14058
|
+
default: PromptData.optional(),
|
|
14059
|
+
description: _v3.z.string().optional()
|
|
14060
|
+
}),
|
|
14061
|
+
_v3.z.object({
|
|
14062
|
+
type: _v3.z.literal("data"),
|
|
14063
|
+
schema: _v3.z.record(_v3.z.unknown()),
|
|
14064
|
+
// JSON Schema
|
|
14065
|
+
default: _v3.z.unknown().optional(),
|
|
14066
|
+
description: _v3.z.string().optional()
|
|
14067
|
+
})
|
|
14068
|
+
])
|
|
14069
|
+
);
|
|
14070
|
+
var evaluatorDefinitionSchema = _v3.z.object({
|
|
14071
|
+
parameters: evalParametersSerializedSchema.optional()
|
|
14072
|
+
});
|
|
14073
|
+
var evaluatorDefinitionsSchema = _v3.z.record(
|
|
14074
|
+
_v3.z.string(),
|
|
14075
|
+
evaluatorDefinitionSchema
|
|
14076
|
+
);
|
|
14077
|
+
|
|
14078
|
+
// src/browser.ts
|
|
14079
|
+
configureBrowser();
|
|
14080
|
+
|
|
14081
|
+
|
|
14082
|
+
|
|
14083
|
+
|
|
14084
|
+
|
|
14085
|
+
|
|
14086
|
+
|
|
14087
|
+
|
|
14088
|
+
|
|
14089
|
+
|
|
14090
|
+
|
|
14091
|
+
|
|
14092
|
+
|
|
14093
|
+
|
|
14094
|
+
|
|
14095
|
+
|
|
14096
|
+
|
|
14097
|
+
|
|
14098
|
+
|
|
14099
|
+
|
|
14100
|
+
|
|
14101
|
+
|
|
14102
|
+
|
|
11482
14103
|
|
|
11483
14104
|
|
|
11484
14105
|
|
|
@@ -11565,4 +14186,4 @@ var browser_default = exports_browser_exports;
|
|
|
11565
14186
|
|
|
11566
14187
|
|
|
11567
14188
|
|
|
11568
|
-
exports.Attachment = Attachment; exports.BaseAttachment = BaseAttachment; exports.BraintrustMiddleware = BraintrustMiddleware; exports.BraintrustState = BraintrustState; exports.BraintrustStream = BraintrustStream; exports.ContextManager = ContextManager; exports.DEFAULT_FETCH_BATCH_SIZE = DEFAULT_FETCH_BATCH_SIZE; exports.Dataset = Dataset2; exports.ERR_PERMALINK = ERR_PERMALINK; exports.Experiment = Experiment2; exports.ExternalAttachment = ExternalAttachment; exports.FailedHTTPResponse = FailedHTTPResponse; exports.IDGenerator = IDGenerator; exports.JSONAttachment = JSONAttachment; exports.LEGACY_CACHED_HEADER = LEGACY_CACHED_HEADER; exports.LazyValue = LazyValue; exports.Logger = Logger; exports.LoginInvalidOrgError = LoginInvalidOrgError; exports.NOOP_SPAN = NOOP_SPAN; exports.NOOP_SPAN_PERMALINK = NOOP_SPAN_PERMALINK; exports.NoopSpan = NoopSpan; exports.Prompt = Prompt2; exports.ReadonlyAttachment = ReadonlyAttachment; exports.ReadonlyExperiment = ReadonlyExperiment; exports.SpanImpl = SpanImpl; exports.TestBackgroundLogger = TestBackgroundLogger; exports.UUIDGenerator = UUIDGenerator; exports.X_CACHED_HEADER = X_CACHED_HEADER; exports._exportsForTestingOnly = _exportsForTestingOnly; exports._internalGetGlobalState = _internalGetGlobalState; exports._internalSetInitialState = _internalSetInitialState; exports.braintrustStreamChunkSchema = braintrustStreamChunkSchema; exports.createFinalValuePassThroughStream = createFinalValuePassThroughStream; exports.currentExperiment = currentExperiment; exports.currentLogger = currentLogger; exports.currentSpan = currentSpan; exports.deepCopyEvent = deepCopyEvent; exports.default =
|
|
14189
|
+
exports.Attachment = Attachment; exports.AttachmentReference = AttachmentReference; exports.BaseAttachment = BaseAttachment; exports.BaseExperiment = BaseExperiment; exports.BraintrustMiddleware = BraintrustMiddleware; exports.BraintrustState = BraintrustState; exports.BraintrustStream = BraintrustStream; exports.CodeFunction = CodeFunction; exports.CodePrompt = CodePrompt; exports.ContextManager = ContextManager; exports.DEFAULT_FETCH_BATCH_SIZE = DEFAULT_FETCH_BATCH_SIZE; exports.Dataset = Dataset2; exports.ERR_PERMALINK = ERR_PERMALINK; exports.Eval = Eval; exports.EvalResultWithSummary = EvalResultWithSummary; exports.Experiment = Experiment2; exports.ExternalAttachment = ExternalAttachment; exports.FailedHTTPResponse = FailedHTTPResponse; exports.IDGenerator = IDGenerator; exports.JSONAttachment = JSONAttachment; exports.LEGACY_CACHED_HEADER = LEGACY_CACHED_HEADER; exports.LazyValue = LazyValue; exports.Logger = Logger; exports.LoginInvalidOrgError = LoginInvalidOrgError; exports.NOOP_SPAN = NOOP_SPAN; exports.NOOP_SPAN_PERMALINK = NOOP_SPAN_PERMALINK; exports.NoopSpan = NoopSpan; exports.Project = Project2; exports.ProjectNameIdMap = ProjectNameIdMap; exports.Prompt = Prompt2; exports.PromptBuilder = PromptBuilder; exports.ReadonlyAttachment = ReadonlyAttachment; exports.ReadonlyExperiment = ReadonlyExperiment; exports.Reporter = Reporter; exports.ScorerBuilder = ScorerBuilder; exports.SpanImpl = SpanImpl; exports.TestBackgroundLogger = TestBackgroundLogger; exports.ToolBuilder = ToolBuilder; exports.UUIDGenerator = UUIDGenerator; exports.X_CACHED_HEADER = X_CACHED_HEADER; exports._exportsForTestingOnly = _exportsForTestingOnly; exports._internalGetGlobalState = _internalGetGlobalState; exports._internalSetInitialState = _internalSetInitialState; exports.braintrustStreamChunkSchema = braintrustStreamChunkSchema; exports.buildLocalSummary = buildLocalSummary; exports.createFinalValuePassThroughStream = createFinalValuePassThroughStream; exports.currentExperiment = currentExperiment; exports.currentLogger = currentLogger; exports.currentSpan = currentSpan; exports.deepCopyEvent = deepCopyEvent; exports.default = exports_exports; exports.defaultErrorScoreHandler = defaultErrorScoreHandler; exports.deserializePlainStringAsJSON = deserializePlainStringAsJSON; exports.devNullWritableStream = devNullWritableStream; exports.evaluatorDefinitionSchema = evaluatorDefinitionSchema; exports.evaluatorDefinitionsSchema = evaluatorDefinitionsSchema; exports.flush = flush; exports.getContextManager = getContextManager; exports.getIdGenerator = getIdGenerator; exports.getPromptVersions = getPromptVersions; exports.getSpanParentObject = getSpanParentObject; exports.graph = graph_framework_exports; exports.init = init; exports.initDataset = initDataset; exports.initExperiment = initExperiment; exports.initFunction = initFunction; exports.initLogger = initLogger; exports.invoke = invoke; exports.loadPrompt = loadPrompt; exports.log = log; exports.logError = logError; exports.login = login; exports.loginToState = loginToState; exports.newId = newId; exports.parseCachedHeader = parseCachedHeader; exports.permalink = permalink; exports.projects = projects; exports.promptContentsSchema = promptContentsSchema; exports.promptDefinitionSchema = promptDefinitionSchema; exports.promptDefinitionToPromptData = promptDefinitionToPromptData; exports.promptDefinitionWithToolsSchema = promptDefinitionWithToolsSchema; exports.renderMessage = renderMessage; exports.renderPromptParams = renderPromptParams; exports.reportFailures = reportFailures; exports.runEvaluator = runEvaluator; exports.setFetch = setFetch; exports.setMaskingFunction = setMaskingFunction; exports.spanComponentsToObjectId = spanComponentsToObjectId; exports.startSpan = startSpan; exports.summarize = summarize; exports.toolFunctionDefinitionSchema = ToolFunctionDefinition; exports.traceable = traceable; exports.traced = traced; exports.updateSpan = updateSpan; exports.withCurrent = withCurrent; exports.withDataset = withDataset; exports.withExperiment = withExperiment; exports.withLogger = withLogger; exports.withParent = withParent; exports.wrapAISDK = wrapAISDK; exports.wrapAISDKModel = wrapAISDKModel; exports.wrapAnthropic = wrapAnthropic; exports.wrapClaudeAgentSDK = wrapClaudeAgentSDK; exports.wrapGoogleGenAI = wrapGoogleGenAI; exports.wrapMastraAgent = wrapMastraAgent; exports.wrapOpenAI = wrapOpenAI; exports.wrapOpenAIv4 = wrapOpenAIv4; exports.wrapTraced = wrapTraced;
|