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.mjs
CHANGED
|
@@ -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 = options?.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 (options?.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 (options?.lower) {
|
|
1142
|
+
slug = slug.toLowerCase();
|
|
1143
|
+
}
|
|
1144
|
+
return slug;
|
|
1145
|
+
}
|
|
1057
1146
|
|
|
1058
1147
|
// util/span_identifier_v4.ts
|
|
1059
1148
|
import { z as z4 } from "zod/v3";
|
|
@@ -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
|
import { z as z5 } from "zod/v3";
|
|
@@ -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 = 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)) {
|
|
@@ -3564,7 +3668,7 @@ var BraintrustState = 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);
|
|
@@ -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: uuidv42(),
|
|
@@ -5173,7 +5277,7 @@ function init(projectOrOptions, optionalOptions) {
|
|
|
5173
5277
|
const state = 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 = 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
|
);
|
|
@@ -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) {
|
|
@@ -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),
|
|
@@ -7473,11 +7577,11 @@ var Prompt2 = 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
|
);
|
|
@@ -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,
|
|
@@ -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)
|
|
@@ -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}]`);
|
|
@@ -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 (m?.specificationVersion === "v1" && typeof m?.provider === "string" && typeof m?.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
|
+
supportsUrl;
|
|
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: ret.usage?.promptTokens,
|
|
10006
|
+
completion_tokens: ret.usage?.completionTokens,
|
|
10007
|
+
cached: parseCachedHeader(
|
|
10008
|
+
ret.rawResponse?.headers?.[X_CACHED_HEADER] ?? ret.rawResponse?.headers?.[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: usage?.promptTokens,
|
|
10101
|
+
completion_tokens: usage?.completionTokens,
|
|
10102
|
+
cached: parseCachedHeader(
|
|
10103
|
+
ret.rawResponse?.headers?.[X_CACHED_HEADER] ?? ret.rawResponse?.headers?.[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: textPart?.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: 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);
|
|
@@ -11434,61 +11834,2265 @@ function unescapePath(path) {
|
|
|
11434
11834
|
}
|
|
11435
11835
|
var graph_framework_default = { createGraph };
|
|
11436
11836
|
|
|
11437
|
-
//
|
|
11438
|
-
|
|
11439
|
-
|
|
11440
|
-
|
|
11441
|
-
|
|
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
|
+
import { z as z10 } from "zod/v3";
|
|
12888
|
+
|
|
12889
|
+
// src/framework2.ts
|
|
12890
|
+
import { z as z9 } from "zod/v3";
|
|
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 = class {
|
|
12899
|
+
name;
|
|
12900
|
+
id;
|
|
12901
|
+
tools;
|
|
12902
|
+
prompts;
|
|
12903
|
+
scorers;
|
|
12904
|
+
_publishableCodeFunctions = [];
|
|
12905
|
+
_publishablePrompts = [];
|
|
12906
|
+
constructor(args) {
|
|
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
|
+
};
|
|
12950
|
+
var ToolBuilder = class {
|
|
12951
|
+
constructor(project) {
|
|
12952
|
+
this.project = project;
|
|
12953
|
+
}
|
|
12954
|
+
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 = opts ?? {};
|
|
12960
|
+
const { handler, name, slug, parameters, returns, ...rest } = opts;
|
|
12961
|
+
let resolvedName = 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: 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
|
+
};
|
|
12980
|
+
var ScorerBuilder = class {
|
|
12981
|
+
constructor(project) {
|
|
12982
|
+
this.project = project;
|
|
12983
|
+
}
|
|
12984
|
+
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 = 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
|
+
};
|
|
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
|
+
handler;
|
|
13055
|
+
name;
|
|
13056
|
+
slug;
|
|
13057
|
+
type;
|
|
13058
|
+
description;
|
|
13059
|
+
parameters;
|
|
13060
|
+
returns;
|
|
13061
|
+
ifExists;
|
|
13062
|
+
metadata;
|
|
13063
|
+
key() {
|
|
13064
|
+
return JSON.stringify([
|
|
13065
|
+
this.project.id ?? "",
|
|
13066
|
+
this.project.name ?? "",
|
|
13067
|
+
this.slug
|
|
13068
|
+
]);
|
|
13069
|
+
}
|
|
13070
|
+
};
|
|
13071
|
+
var CodePrompt = class {
|
|
13072
|
+
project;
|
|
13073
|
+
name;
|
|
13074
|
+
slug;
|
|
13075
|
+
prompt;
|
|
13076
|
+
ifExists;
|
|
13077
|
+
description;
|
|
13078
|
+
id;
|
|
13079
|
+
functionType;
|
|
13080
|
+
toolFunctions;
|
|
13081
|
+
metadata;
|
|
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: 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 = z9.union([
|
|
13131
|
+
z9.object({
|
|
13132
|
+
prompt: z9.string()
|
|
13133
|
+
}),
|
|
13134
|
+
z9.object({
|
|
13135
|
+
messages: z9.array(ChatCompletionMessageParam)
|
|
13136
|
+
})
|
|
13137
|
+
]);
|
|
13138
|
+
var promptDefinitionSchema = promptContentsSchema.and(
|
|
13139
|
+
z9.object({
|
|
13140
|
+
model: z9.string(),
|
|
13141
|
+
params: ModelParams.optional()
|
|
13142
|
+
})
|
|
13143
|
+
);
|
|
13144
|
+
var promptDefinitionWithToolsSchema = promptDefinitionSchema.and(
|
|
13145
|
+
z9.object({
|
|
13146
|
+
tools: z9.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 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 = 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
|
+
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 = class {
|
|
13207
|
+
nameToId = {};
|
|
13208
|
+
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 = z9.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 = z9.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
|
+
};
|
|
13242
|
+
|
|
13243
|
+
// src/eval-parameters.ts
|
|
13244
|
+
var evalParametersSchema = z10.record(
|
|
13245
|
+
z10.string(),
|
|
13246
|
+
z10.union([
|
|
13247
|
+
z10.object({
|
|
13248
|
+
type: z10.literal("prompt"),
|
|
13249
|
+
default: promptDefinitionWithToolsSchema.optional(),
|
|
13250
|
+
description: z10.string().optional()
|
|
13251
|
+
}),
|
|
13252
|
+
z10.instanceof(z10.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 = options.progress ?? new SimpleProgressReporter();
|
|
13377
|
+
const shouldCollectResults = 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: 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(parameters ?? {}, 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 = [...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: parameters ?? {},
|
|
13612
|
+
reportProgress: (event) => {
|
|
13613
|
+
stream?.({
|
|
13614
|
+
...event,
|
|
13615
|
+
id: rootSpan.id,
|
|
13616
|
+
origin: baseEvent.event?.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 = 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: baseEvent.event?.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(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 = evaluator.trialCount ?? 1;
|
|
13799
|
+
for (let trialIndex = 0; trialIndex < trialCount; trialIndex++) {
|
|
13800
|
+
if (cancelled) {
|
|
13801
|
+
break;
|
|
13802
|
+
}
|
|
13803
|
+
scheduledTrials++;
|
|
13804
|
+
progressReporter.setTotal?.(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
|
+
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 = 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 = 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(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(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
|
+
import { z as z11 } from "zod/v3";
|
|
14038
|
+
var evalBodySchema = z11.object({
|
|
14039
|
+
name: z11.string(),
|
|
14040
|
+
parameters: z11.record(z11.string(), z11.unknown()).nullish(),
|
|
11442
14041
|
data: RunEval.shape.data,
|
|
11443
|
-
scores:
|
|
11444
|
-
|
|
14042
|
+
scores: z11.array(
|
|
14043
|
+
z11.object({
|
|
11445
14044
|
function_id: FunctionId,
|
|
11446
|
-
name:
|
|
14045
|
+
name: z11.string()
|
|
11447
14046
|
})
|
|
11448
14047
|
).nullish(),
|
|
11449
|
-
experiment_name:
|
|
11450
|
-
project_id:
|
|
14048
|
+
experiment_name: z11.string().nullish(),
|
|
14049
|
+
project_id: z11.string().nullish(),
|
|
11451
14050
|
parent: InvokeParent.optional(),
|
|
11452
|
-
stream:
|
|
14051
|
+
stream: z11.boolean().optional()
|
|
11453
14052
|
});
|
|
11454
|
-
var evalParametersSerializedSchema =
|
|
11455
|
-
|
|
11456
|
-
|
|
11457
|
-
|
|
11458
|
-
type:
|
|
14053
|
+
var evalParametersSerializedSchema = z11.record(
|
|
14054
|
+
z11.string(),
|
|
14055
|
+
z11.union([
|
|
14056
|
+
z11.object({
|
|
14057
|
+
type: z11.literal("prompt"),
|
|
11459
14058
|
default: PromptData.optional(),
|
|
11460
|
-
description:
|
|
14059
|
+
description: z11.string().optional()
|
|
11461
14060
|
}),
|
|
11462
|
-
|
|
11463
|
-
type:
|
|
11464
|
-
schema:
|
|
14061
|
+
z11.object({
|
|
14062
|
+
type: z11.literal("data"),
|
|
14063
|
+
schema: z11.record(z11.unknown()),
|
|
11465
14064
|
// JSON Schema
|
|
11466
|
-
default:
|
|
11467
|
-
description:
|
|
14065
|
+
default: z11.unknown().optional(),
|
|
14066
|
+
description: z11.string().optional()
|
|
11468
14067
|
})
|
|
11469
14068
|
])
|
|
11470
14069
|
);
|
|
11471
|
-
var evaluatorDefinitionSchema =
|
|
14070
|
+
var evaluatorDefinitionSchema = z11.object({
|
|
11472
14071
|
parameters: evalParametersSerializedSchema.optional()
|
|
11473
14072
|
});
|
|
11474
|
-
var evaluatorDefinitionsSchema =
|
|
11475
|
-
|
|
14073
|
+
var evaluatorDefinitionsSchema = z11.record(
|
|
14074
|
+
z11.string(),
|
|
11476
14075
|
evaluatorDefinitionSchema
|
|
11477
14076
|
);
|
|
11478
14077
|
|
|
11479
14078
|
// src/browser.ts
|
|
11480
14079
|
configureBrowser();
|
|
11481
|
-
var browser_default = exports_browser_exports;
|
|
11482
14080
|
export {
|
|
11483
14081
|
Attachment,
|
|
14082
|
+
AttachmentReference,
|
|
11484
14083
|
BaseAttachment,
|
|
14084
|
+
BaseExperiment,
|
|
11485
14085
|
BraintrustMiddleware,
|
|
11486
14086
|
BraintrustState,
|
|
11487
14087
|
BraintrustStream,
|
|
14088
|
+
CodeFunction,
|
|
14089
|
+
CodePrompt,
|
|
11488
14090
|
ContextManager,
|
|
11489
14091
|
DEFAULT_FETCH_BATCH_SIZE,
|
|
11490
14092
|
Dataset2 as Dataset,
|
|
11491
14093
|
ERR_PERMALINK,
|
|
14094
|
+
Eval,
|
|
14095
|
+
EvalResultWithSummary,
|
|
11492
14096
|
Experiment2 as Experiment,
|
|
11493
14097
|
ExternalAttachment,
|
|
11494
14098
|
FailedHTTPResponse,
|
|
@@ -11501,23 +14105,31 @@ export {
|
|
|
11501
14105
|
NOOP_SPAN,
|
|
11502
14106
|
NOOP_SPAN_PERMALINK,
|
|
11503
14107
|
NoopSpan,
|
|
14108
|
+
Project2 as Project,
|
|
14109
|
+
ProjectNameIdMap,
|
|
11504
14110
|
Prompt2 as Prompt,
|
|
14111
|
+
PromptBuilder,
|
|
11505
14112
|
ReadonlyAttachment,
|
|
11506
14113
|
ReadonlyExperiment,
|
|
14114
|
+
Reporter,
|
|
14115
|
+
ScorerBuilder,
|
|
11507
14116
|
SpanImpl,
|
|
11508
14117
|
TestBackgroundLogger,
|
|
14118
|
+
ToolBuilder,
|
|
11509
14119
|
UUIDGenerator,
|
|
11510
14120
|
X_CACHED_HEADER,
|
|
11511
14121
|
_exportsForTestingOnly,
|
|
11512
14122
|
_internalGetGlobalState,
|
|
11513
14123
|
_internalSetInitialState,
|
|
11514
14124
|
braintrustStreamChunkSchema,
|
|
14125
|
+
buildLocalSummary,
|
|
11515
14126
|
createFinalValuePassThroughStream,
|
|
11516
14127
|
currentExperiment,
|
|
11517
14128
|
currentLogger,
|
|
11518
14129
|
currentSpan,
|
|
11519
14130
|
deepCopyEvent,
|
|
11520
|
-
|
|
14131
|
+
exports_exports as default,
|
|
14132
|
+
defaultErrorScoreHandler,
|
|
11521
14133
|
deserializePlainStringAsJSON,
|
|
11522
14134
|
devNullWritableStream,
|
|
11523
14135
|
evaluatorDefinitionSchema,
|
|
@@ -11542,13 +14154,21 @@ export {
|
|
|
11542
14154
|
newId,
|
|
11543
14155
|
parseCachedHeader,
|
|
11544
14156
|
permalink,
|
|
14157
|
+
projects,
|
|
14158
|
+
promptContentsSchema,
|
|
14159
|
+
promptDefinitionSchema,
|
|
14160
|
+
promptDefinitionToPromptData,
|
|
14161
|
+
promptDefinitionWithToolsSchema,
|
|
11545
14162
|
renderMessage,
|
|
11546
14163
|
renderPromptParams,
|
|
14164
|
+
reportFailures,
|
|
14165
|
+
runEvaluator,
|
|
11547
14166
|
setFetch,
|
|
11548
14167
|
setMaskingFunction,
|
|
11549
14168
|
spanComponentsToObjectId,
|
|
11550
14169
|
startSpan,
|
|
11551
14170
|
summarize,
|
|
14171
|
+
ToolFunctionDefinition as toolFunctionDefinitionSchema,
|
|
11552
14172
|
traceable,
|
|
11553
14173
|
traced,
|
|
11554
14174
|
updateSpan,
|
|
@@ -11558,6 +14178,7 @@ export {
|
|
|
11558
14178
|
withLogger,
|
|
11559
14179
|
withParent,
|
|
11560
14180
|
wrapAISDK,
|
|
14181
|
+
wrapAISDKModel,
|
|
11561
14182
|
wrapAnthropic,
|
|
11562
14183
|
wrapClaudeAgentSDK,
|
|
11563
14184
|
wrapGoogleGenAI,
|