-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathframework.ts
More file actions
1658 lines (1512 loc) · 49.9 KB
/
framework.ts
File metadata and controls
1658 lines (1512 loc) · 49.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import {
makeScorerPropagatedEvent,
mergeDicts,
Score,
SpanComponentsV3,
SpanTypeAttribute,
spanObjectTypeV3ToTypedString,
} from "../util/index";
import {
type GitMetadataSettingsType as GitMetadataSettings,
type ObjectReferenceType as ObjectReference,
type RepoInfoType as RepoInfo,
type SSEProgressEventDataType as SSEProgressEventData,
} from "./generated_types";
import { queue } from "async";
import iso from "./isomorph";
import { GenericFunction } from "./framework-types";
import { CodeFunction, CodePrompt, CodeParameters } from "./framework2";
import { Trace, LocalTrace } from "./trace";
import {
BaseMetadata,
BraintrustState,
Dataset,
DefaultMetadataType,
EvalCase,
Experiment,
ExperimentSummary,
FullInitOptions,
NOOP_SPAN,
RemoteEvalParameters,
Span,
StartSpanArgs,
init as _initExperiment,
currentSpan,
flush,
logError as logSpanError,
startSpan,
traced,
withCurrent,
withParent,
_internalGetGlobalState,
} from "./logger";
import type { ProgressReporter } from "./reporters/types";
import { SimpleProgressReporter } from "./reporters/progress";
import type {
ReporterOpts,
ReporterBody,
ReporterDef,
} from "./reporters/types";
import { isEmpty, InternalAbortError } from "./util";
import {
EvalParameters,
InferParameters,
validateParameters,
} from "./eval-parameters";
export type BaseExperiment<
Input,
Expected,
Metadata extends BaseMetadata = DefaultMetadataType,
> = {
_type: "BaseExperiment";
_phantom?: [Input, Expected, Metadata];
name?: string;
};
/**
* Use this to specify that the dataset should actually be the data from a previous (base) experiment.
* If you do not specify a name, Braintrust will automatically figure out the best base experiment to
* use based on your git history (or fall back to timestamps).
*
* @param options
* @param options.name The name of the base experiment to use. If unspecified, Braintrust will automatically figure out the best base
* using your git history (or fall back to timestamps).
* @returns
*/
export function BaseExperiment<
Input = unknown,
Expected = unknown,
Metadata extends BaseMetadata = DefaultMetadataType,
>(
options: {
name?: string;
} = {},
): BaseExperiment<Input, Expected, Metadata> {
return { _type: "BaseExperiment", ...options };
}
export type EvalData<
Input,
Expected,
Metadata extends BaseMetadata = DefaultMetadataType,
> =
| EvalCase<Input, Expected, Metadata>[]
| (() => EvalCase<Input, Expected, Metadata>[])
| Promise<EvalCase<Input, Expected, Metadata>[]>
| (() => Promise<EvalCase<Input, Expected, Metadata>[]>)
| AsyncGenerator<EvalCase<Input, Expected, Metadata>>
| AsyncIterable<EvalCase<Input, Expected, Metadata>>
| BaseExperiment<Input, Expected, Metadata>
| (() => BaseExperiment<Input, Expected, Metadata>);
export type EvalTask<
Input,
Output,
Expected,
Metadata extends BaseMetadata,
Parameters extends EvalParameters,
> =
| ((
input: Input,
hooks: EvalHooks<Expected, Metadata, Parameters>,
) => Promise<Output>)
| ((
input: Input,
hooks: EvalHooks<Expected, Metadata, Parameters>,
) => Output);
export type TaskProgressEvent = Omit<
SSEProgressEventData,
"id" | "origin" | "object_type" | "name"
>;
export interface EvalHooks<
Expected,
Metadata extends BaseMetadata,
Parameters extends EvalParameters,
> {
/**
* @deprecated Use `metadata` instead.
*/
meta: (info: Metadata) => void;
/**
* The metadata object for the current evaluation. You can mutate this object to add or remove metadata.
*/
metadata: Metadata extends void ? Record<string, unknown> : Metadata;
/**
* The expected output for the current evaluation.
*/
expected: Expected;
/**
* The task's span.
*/
span: Span;
/**
* The current parameters being used for this specific task execution.
* Array parameters are converted to single values.
*/
parameters: InferParameters<Parameters>;
/**
* Report progress that will show up in the playground.
*/
reportProgress: (progress: TaskProgressEvent) => void;
/**
* The index of the current trial (0-based). This is useful when trialCount > 1.
*/
trialIndex: number;
/**
* The tags for the current evaluation.
*/
tags: string[] | undefined;
}
// This happens to be compatible with ScorerArgs defined in "../util".
export type EvalScorerArgs<
Input,
Output,
Expected,
Metadata extends BaseMetadata = DefaultMetadataType,
> = EvalCase<Input, Expected, Metadata> & {
output: Output;
trace?: Trace;
};
export type OneOrMoreScores = Score | number | null | Array<Score>;
export type EvalScorer<
Input,
Output,
Expected,
Metadata extends BaseMetadata = DefaultMetadataType,
> = (
args: EvalScorerArgs<Input, Output, Expected, Metadata>,
) => OneOrMoreScores | Promise<OneOrMoreScores>;
export type EvalResult<
Input,
Output,
Expected,
Metadata extends BaseMetadata = DefaultMetadataType,
> = EvalCase<Input, Expected, Metadata> & {
output: Output;
scores: Record<string, number | null>;
error: unknown;
origin?: ObjectReference;
};
type ErrorScoreHandler = (args: {
rootSpan: Span;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
data: EvalCase<any, any, any>;
unhandledScores: string[];
}) => Record<string, number> | undefined | void;
export interface Evaluator<
Input,
Output,
Expected,
Metadata extends BaseMetadata = DefaultMetadataType,
Parameters extends EvalParameters = EvalParameters,
> {
/**
* A function that returns a list of inputs, expected outputs, and metadata.
*/
data: EvalData<Input, Expected, Metadata>;
/**
* A function that takes an input and returns an output.
*/
task: EvalTask<Input, Output, Expected, Metadata, Parameters>;
/**
* A set of functions that take an input, output, and expected value and return a score.
*/
scores: EvalScorer<Input, Output, Expected, Metadata>[];
/**
* A set of parameters that will be passed to the evaluator.
* Can be:
* - A raw EvalParameters schema (Zod schemas)
* - A Parameters instance from loadParameters()
* - A Promise<Parameters> from loadParameters()
*/
parameters?:
| Parameters
| RemoteEvalParameters<boolean, boolean, InferParameters<Parameters>>
| Promise<
RemoteEvalParameters<boolean, boolean, InferParameters<Parameters>>
>;
/**
* An optional name for the experiment.
*/
experimentName?: string;
/**
* An optional description for the experiment.
*/
description?: string;
/**
* The number of times to run the evaluator per input. This is useful for evaluating applications that
* have non-deterministic behavior and gives you both a stronger aggregate measure and a sense of the
* variance in the results.
*/
trialCount?: number;
/**
* Optional additional metadata for the experiment.
*/
metadata?: Record<string, unknown>;
/**
* Whether the experiment should be public. Defaults to false.
*/
isPublic?: boolean;
/**
* Whether to update an existing experiment with `experiment_name` if one exists. Defaults to false.
*/
update?: boolean;
/**
* The duration, in milliseconds, after which to time out the evaluation.
* Defaults to undefined, in which case there is no timeout.
*/
timeout?: number;
/**
* An abort signal that can be used to stop the evaluation.
*/
signal?: AbortSignal;
/**
* The maximum number of tasks/scorers that will be run concurrently.
* Defaults to undefined, in which case there is no max concurrency.
*/
maxConcurrency?: number;
/**
* If specified, uses the given project ID instead of the evaluator's name to identify the project.
*/
projectId?: string;
/**
* If specified, uses the logger state to initialize Braintrust objects. If unspecified, falls back
* to the global state (initialized using your API key).
*/
state?: BraintrustState;
/**
* An optional experiment name to use as a base. If specified, the new experiment will be summarized
* and compared to this experiment.
*/
baseExperimentName?: string;
/**
* An optional experiment id to use as a base. If specified, the new experiment will be summarized
* and compared to this experiment. This takes precedence over `baseExperimentName` if specified.
*/
baseExperimentId?: string;
/**
* Optional settings for collecting git metadata. By default, will collect all git metadata fields allowed in org-level settings.
*/
gitMetadataSettings?: GitMetadataSettings;
/**
* Optionally explicitly specify the git metadata for this experiment. This takes precedence over `gitMetadataSettings` if specified.
*/
repoInfo?: RepoInfo;
/**
* Optionally supply a custom function to specifically handle score values when tasks or scoring functions have errored.
* A default implementation is exported as `defaultErrorScoreHandler` which will log a 0 score to the root span for any scorer that was not run.
*/
errorScoreHandler?: ErrorScoreHandler;
/**
* Whether to summarize the scores of the experiment after it has run.
* Defaults to true.
*/
summarizeScores?: boolean;
/**
* Flushes spans before calling scoring functions
*/
flushBeforeScoring?: boolean;
}
export class EvalResultWithSummary<
Input,
Output,
Expected,
Metadata extends BaseMetadata = DefaultMetadataType,
> {
constructor(
public summary: ExperimentSummary,
public results: EvalResult<Input, Output, Expected, Metadata>[],
) {}
/**
* @deprecated Use `summary` instead.
*/
toString(): string {
return JSON.stringify(this.summary);
}
[Symbol.for("nodejs.util.inspect.custom")](): string {
return `EvalResultWithSummary(summary="...", results=[...])`;
}
toJSON(): {
summary: ExperimentSummary;
results: EvalResult<Input, Output, Expected, Metadata>[];
} {
return {
summary: this.summary,
results: this.results,
};
}
}
export type {
ReporterOpts,
ReporterBody,
ReporterDef,
} from "./reporters/types";
function makeEvalName(projectName: string, experimentName?: string) {
let out = projectName;
if (experimentName) {
out += ` [experimentName=${experimentName}]`;
}
return out;
}
export type EvaluatorDef<
Input,
Output,
Expected,
Metadata extends BaseMetadata = DefaultMetadataType,
Parameters extends EvalParameters = EvalParameters,
> = {
projectName: string;
evalName: string;
} & Evaluator<Input, Output, Expected, Metadata, Parameters>;
export type EvaluatorFile = {
functions: CodeFunction<
unknown,
unknown,
GenericFunction<unknown, unknown>
>[];
prompts: CodePrompt[];
parameters?: CodeParameters[];
evaluators: {
[evalName: string]: {
evaluator: EvaluatorDef<
unknown,
unknown,
unknown,
BaseMetadata,
EvalParameters
>;
reporter?: ReporterDef<unknown> | string;
};
};
reporters: { [reporterName: string]: ReporterDef<unknown> };
};
function initExperiment<IsOpen extends boolean = false>(
state: BraintrustState | undefined,
options: Readonly<FullInitOptions<IsOpen>> = {},
) {
return _initExperiment({
state,
...options,
setCurrent: false,
});
}
export function callEvaluatorData<
Input,
Expected,
Metadata extends BaseMetadata = DefaultMetadataType,
>(
data: EvalData<Input, Expected, Metadata>,
): {
data: EvalData<Input, Expected, Metadata>;
baseExperiment: string | undefined;
} {
const dataResult = typeof data === "function" ? data() : data;
let baseExperiment: string | undefined = undefined;
if ("_type" in dataResult && dataResult._type === "BaseExperiment") {
baseExperiment = dataResult.name;
}
return {
data: dataResult,
baseExperiment,
};
}
export type SpanContext = {
currentSpan: typeof currentSpan;
startSpan: typeof startSpan;
withCurrent: typeof withCurrent;
NOOP_SPAN: typeof NOOP_SPAN;
};
function isAsyncIterable<T>(value: unknown): value is AsyncIterable<T> {
return (
typeof value === "object" &&
value !== null &&
typeof (value as AsyncIterable<T>)[Symbol.asyncIterator] === "function"
);
}
function isIterable<T>(value: unknown): value is Iterable<T> {
return (
typeof value === "object" &&
value !== null &&
typeof (value as Iterable<T>)[Symbol.iterator] === "function"
);
}
declare global {
var _evals: EvaluatorFile;
var _spanContext: SpanContext | undefined;
var _lazy_load: boolean;
}
globalThis._evals = {
functions: [],
prompts: [],
parameters: [],
evaluators: {},
reporters: {},
};
export interface EvalOptions<EvalReport, Parameters extends EvalParameters> {
/**
* A `Reporter` which you can use to summarize progress after an Eval() runs.
*/
reporter?: ReporterDef<EvalReport> | string;
/**
* Do not send logs to Braintrust. When true, the evaluation runs locally
* and builds a local summary instead of creating an experiment. Defaults to false.
*/
noSendLogs?: boolean;
/**
* A callback function that will be called when an experiment is started with
* information about its project, experiment id, name, and other useful information.
* @param metadata
*/
onStart?: (metadata: Omit<ExperimentSummary, "scores" | "metrics">) => void;
/**
* A function that will be called with progress events, which can be used to
* display intermediate progress.
*
* @param data
*/
stream?: (data: SSEProgressEventData) => void;
/**
* If specified, instead of creating a new experiment object, the Eval() will populate
* the object or span specified by this parent.
*/
parent?: string;
/**
* Specify this to create a custom progress-bar style reporter. Note that this interface
* is somewhat outdated, and may be removed in the future.
*/
progress?: ProgressReporter;
/**
* The parameters to use for the evaluator.
*/
parameters?: InferParameters<Parameters>;
/**
* Whether to retain the per-example Eval results and return them from Eval().
*
* When `true` (default): All evaluation results are collected in memory and returned,
* allowing inspection of individual test case inputs, outputs, scores, and metadata.
* This is convenient for interactive analysis but can consume significant memory for
* large datasets (e.g., millions of examples).
*
* When `false`: Individual results are not retained in memory. Only aggregate score
* statistics are computed incrementally. The returned `results` array will be empty,
* but the `summary` will still contain accurate score aggregates. This is suitable for:
* - Large-scale evaluations (millions of examples)
* - Memory-constrained environments
* - Scenarios where only aggregate metrics are needed
*
* Note: When `false`, you cannot access individual test case results after evaluation.
* If you need to inspect specific failures or outputs, keep this as `true`.
*
* Defaults to `true` for backwards compatibility.
*
* @example
* // Memory-efficient evaluation of a large dataset
* await Eval("large-eval", evaluator, {
* returnResults: false // Only keep aggregate scores
* });
*/
returnResults?: boolean;
/**
* Whether to enable the span cache for this evaluation. The span cache stores span data on disk
* to minimize memory usage and allow scorers to read spans without server round-trips. Defaults to true.
* Set to false to disable caching if you are doing distributed evaluation or want to reduce disk I/O.
*
* @example
* // Disable span cache
* await Eval("my-eval", evaluator, {
* enableCache: false
* });
*/
enableCache?: boolean;
}
export function _initializeSpanContext() {
// This only needs to be set once, but Eval(), Task(), etc. are the only time
// we get to run code while importing a module, so use it to
// grab these values.
globalThis._spanContext = { currentSpan, withCurrent, startSpan, NOOP_SPAN };
}
export async function Eval<
Input,
Output,
Expected = void,
Metadata extends BaseMetadata = DefaultMetadataType,
EvalReport = boolean,
Parameters extends EvalParameters = EvalParameters,
>(
name: string,
evaluator: Evaluator<Input, Output, Expected, Metadata, Parameters>,
reporterOrOpts?:
| ReporterDef<EvalReport>
| string
| EvalOptions<EvalReport, Parameters>,
): Promise<EvalResultWithSummary<Input, Output, Expected, Metadata>> {
const options: EvalOptions<EvalReport, Parameters> = isEmpty(reporterOrOpts)
? {}
: typeof reporterOrOpts === "string"
? { reporter: reporterOrOpts }
: "name" in reporterOrOpts
? { reporter: reporterOrOpts }
: reporterOrOpts;
let evalName = makeEvalName(name, evaluator.experimentName);
if (globalThis._evals.evaluators[evalName]) {
evalName = `${evalName}_${Object.keys(_evals).length}`;
}
if (globalThis._lazy_load) {
globalThis._evals.evaluators[evalName] = {
// eslint-disable-next-line @typescript-eslint/consistent-type-assertions
evaluator: {
evalName,
projectName: name,
...evaluator,
} as EvaluatorDef<
unknown,
unknown,
unknown,
BaseMetadata,
EvalParameters
>,
reporter: options.reporter,
};
_initializeSpanContext();
// Better to return this empty object than have an annoying-to-use signature
return new EvalResultWithSummary(
{
scores: {},
metrics: {},
projectName: "",
experimentName: "",
},
[],
);
}
const progressReporter = options.progress ?? new SimpleProgressReporter();
const shouldCollectResults = options.returnResults ?? true;
if (typeof options.reporter === "string") {
throw new Error(
"Must specify a reporter object, not a name. Can only specify reporter names when running 'braintrust eval'",
);
}
const resolvedReporter = options.reporter || defaultReporter;
try {
const { data, baseExperiment: defaultBaseExperiment } = callEvaluatorData(
evaluator.data,
);
// NOTE: This code is duplicated with initExperiment in js/src/cli.ts. Make sure
// to update that if you change this.
const experiment =
options.parent || options.noSendLogs
? null
: initExperiment(evaluator.state, {
...(evaluator.projectId
? { projectId: evaluator.projectId }
: { project: name }),
experiment: evaluator.experimentName,
description: evaluator.description,
metadata: evaluator.metadata,
isPublic: evaluator.isPublic,
update: evaluator.update,
baseExperiment:
evaluator.baseExperimentName ?? defaultBaseExperiment,
baseExperimentId: evaluator.baseExperimentId,
gitMetadataSettings: evaluator.gitMetadataSettings,
repoInfo: evaluator.repoInfo,
dataset: Dataset.isDataset(data) ? data : undefined,
});
// Ensure experiment ID is resolved before tasks start for OTEL parent attribute support
// The Experiment constructor starts resolution (fire-and-forget), but we await here to ensure completion
// Only needed when OTEL compat mode is enabled
if (
experiment &&
typeof process !== "undefined" &&
globalThis.BRAINTRUST_CONTEXT_MANAGER !== undefined
) {
await experiment._waitForId();
}
if (experiment && options.onStart) {
const summary = await experiment.summarize({ summarizeScores: false });
options.onStart(summary);
}
try {
const evalDef = {
evalName,
projectName: name,
...evaluator,
data,
};
const enableCache = options.enableCache ?? true;
let ret;
if (options.parent) {
ret = await withParent(
options.parent,
() =>
runEvaluator(
null,
evalDef,
progressReporter,
[],
options.stream,
options.parameters,
shouldCollectResults,
enableCache,
),
evaluator.state,
);
} else {
ret = await runEvaluator(
experiment,
evalDef,
progressReporter,
[],
options.stream,
options.parameters,
shouldCollectResults,
enableCache,
);
}
progressReporter.stop();
resolvedReporter.reportEval(evalDef, ret, {
verbose: true,
jsonl: false,
});
return ret;
} finally {
if (experiment) {
await experiment.flush().catch(console.error);
} else if (options.parent) {
await flush().catch(console.error);
}
}
} finally {
progressReporter.stop();
}
}
export function Reporter<EvalReport>(
name: string,
reporter: ReporterBody<EvalReport>,
): ReporterDef<EvalReport> {
const ret = { name, ...reporter };
if (_evals.reporters[name]) {
throw new Error(`Reporter ${name} already exists`);
}
if (globalThis._lazy_load) {
_evals.reporters[name] = ret;
}
return ret;
}
export function getLoadedEvals() {
return _evals;
}
export interface Filter {
path: string[];
pattern: RegExp;
}
export function serializeJSONWithPlainString(v: unknown) {
if (typeof v === "string") {
return v;
} else {
return JSON.stringify(v);
}
}
export function deserializePlainStringAsJSON(s: string) {
try {
return { value: JSON.parse(s), error: undefined };
} catch (e) {
return { value: s, error: e };
}
}
export function parseFilters(filters: string[]): Filter[] {
const result: Filter[] = [];
for (const f of filters) {
const equalsIdx = f.indexOf("=");
if (equalsIdx === -1) {
throw new Error(`Invalid filter ${f}`);
}
const [path, value] = [f.slice(0, equalsIdx), f.slice(equalsIdx + 1)];
let deserializedValue = deserializePlainStringAsJSON(value).value;
if (typeof deserializedValue !== "string") {
deserializedValue = value; // Just fall back to the original input
}
result.push({
path: path.split("."),
pattern: new RegExp(deserializedValue),
});
}
return result;
}
function evaluateFilter(object: unknown, filter: Filter) {
const { path, pattern } = filter;
const key = path.reduce(
(acc, p) =>
typeof acc === "object" && acc !== null
? // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
(acc as Record<string, unknown>)[p]
: undefined,
object,
);
if (key === undefined) {
return false;
}
return pattern.test(serializeJSONWithPlainString(key));
}
export function scorerName(
// eslint-disable-next-line @typescript-eslint/no-explicit-any
scorer: EvalScorer<any, any, any, any>,
scorer_idx: number,
) {
return scorer.name || `scorer_${scorer_idx}`;
}
export async function runEvaluator(
experiment: Experiment | null,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
evaluator: EvaluatorDef<any, any, any, any, any>,
progressReporter: ProgressReporter,
filters: Filter[],
stream: ((data: SSEProgressEventData) => void) | undefined,
parameters?: InferParameters<EvalParameters>,
collectResults = true,
enableCache = true,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
): Promise<EvalResultWithSummary<any, any, any, any>> {
return await runEvaluatorInternal(
experiment,
evaluator,
progressReporter,
filters,
stream,
parameters,
collectResults,
enableCache,
);
}
export const defaultErrorScoreHandler: ErrorScoreHandler = ({
rootSpan,
data: _,
unhandledScores,
}) => {
const scores = Object.fromEntries(unhandledScores.map((s) => [s, 0]));
rootSpan.log({ scores });
return scores;
};
async function runEvaluatorInternal(
experiment: Experiment | null,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
evaluator: EvaluatorDef<any, any, any, any>,
progressReporter: ProgressReporter,
filters: Filter[],
stream: ((data: SSEProgressEventData) => void) | undefined,
parameters: InferParameters<EvalParameters> | undefined,
collectResults: boolean,
enableCache: boolean,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
): Promise<EvalResultWithSummary<any, any, any, any>> {
// Start span cache for this eval (it's disabled by default to avoid temp files outside of evals)
// Only start if enableCache is true (default)
if (enableCache) {
(evaluator.state ?? _internalGetGlobalState())?.spanCache?.start();
}
try {
if (typeof evaluator.data === "string") {
throw new Error("Unimplemented: string data paths");
}
let dataResult =
typeof evaluator.data === "function" ? evaluator.data() : evaluator.data;
parameters = await validateParameters(
parameters ?? {},
evaluator.parameters,
);
if ("_type" in dataResult) {
if (dataResult._type !== "BaseExperiment") {
// For some reason, the typesystem won't let me check if dataResult._type === "BaseExperiment"
throw new Error("Invalid _type");
}
if (!experiment) {
throw new Error(
"Cannot use BaseExperiment() without connecting to Braintrust (you most likely set --no-send-logs)",
);
}
let name = dataResult.name;
if (isEmpty(name)) {
const baseExperiment = await experiment.fetchBaseExperiment();
if (!baseExperiment) {
throw new Error("BaseExperiment() failed to fetch base experiment");
}
name = baseExperiment.name;
}
dataResult = initExperiment(evaluator.state, {
...(evaluator.projectId
? { projectId: evaluator.projectId }
: { project: evaluator.projectName }),
experiment: name,
open: true,
}).asDataset();
}
const resolvedDataResult =
dataResult instanceof Promise ? await dataResult : dataResult;
const dataIterable: AsyncIterable<EvalCase<any, any, any>> = (() => {
if (isAsyncIterable<EvalCase<any, any, any>>(resolvedDataResult)) {
return resolvedDataResult;
}
if (
Array.isArray(resolvedDataResult) ||
isIterable<EvalCase<any, any, any>>(resolvedDataResult)
) {
const iterable = resolvedDataResult as Iterable<
EvalCase<any, any, any>
>;
return (async function* () {
for (const datum of iterable) {
yield datum;
}
})();
}
throw new Error(
"Evaluator data must be an array, iterable, or async iterable",
);
})();
progressReporter.start(evaluator.evalName, 0);
const experimentIdPromise: Promise<string | undefined> | undefined =
experiment
? (async () => {
try {
return await experiment.id;
} catch {
return undefined;
}
})()
: undefined;
const collectedResults: EvalResult<any, any, any, any>[] = [];
const localScoreAccumulator: ScoreAccumulator | null = experiment
? null
: {};
let cancelled = false;
let scheduledTrials = 0;
const q = queue(
async ({
datum,
trialIndex,
}: {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
datum: EvalCase<any, any, any>;
trialIndex: number;
}) => {
if (cancelled) {
return;
}
const eventDataset: Dataset | undefined = experiment
? experiment.dataset
: Dataset.isDataset(evaluator.data)
? evaluator.data
: undefined;
const baseEvent: StartSpanArgs = {
name: "eval",
spanAttributes: {
type: SpanTypeAttribute.EVAL,
},
event: {
input: datum.input,
expected: "expected" in datum ? datum.expected : undefined,
tags: datum.tags,
origin:
eventDataset && datum.id && datum._xact_id
? {
object_type: "dataset",
object_id: await eventDataset.id,
id: datum.id,
created: datum.created,
_xact_id: datum._xact_id,