@anvia/core 1.0.7 → 1.0.8

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/README.md CHANGED
@@ -649,6 +649,158 @@ Import `McpClient` and `McpClientGroup` from `@anvia/mcp`, connect them, and pas
649
649
  `servers` to `new Agent({ mcpServers })`. See the `@anvia/mcp` README for transport configuration,
650
650
  connection ownership, URL safety, and cleanup.
651
651
 
652
+ ## Evaluations
653
+
654
+ Import evaluation APIs from `@anvia/core/evals`. A suite contains cases, a target, and one or more
655
+ metrics. Required metric failures make a case fail; infrastructure or evaluation errors produce an
656
+ `invalid` outcome.
657
+
658
+ ```ts
659
+ import { contains, exactMatch, runEvalSuite } from "@anvia/core/evals";
660
+
661
+ const result = await runEvalSuite({
662
+ name: "support answers",
663
+ cases: [
664
+ {
665
+ id: "refund-window",
666
+ input: "When can I request a refund?",
667
+ expected: "Refunds are available for 30 days.",
668
+ },
669
+ ],
670
+ target: async (input) => answerSupportQuestion(input),
671
+ metrics: [exactMatch(), contains({ expected: "30 days" })],
672
+ });
673
+
674
+ console.log(result.cases);
675
+ console.log(result.results[0]?.scores.exact_match);
676
+ ```
677
+
678
+ `runEvalSuite` infers the case input, target output, expected value, metric names, and score types.
679
+ Metrics that implicitly read `case.expected`, `case.context`, or `case.retrievalContext` require
680
+ those fields at compile time. Supplying an explicit metric value or selector removes the matching
681
+ case requirement.
682
+
683
+ ### Built-in metrics
684
+
685
+ Deterministic metrics do not call a model:
686
+
687
+ - `exactMatch`, `contains`, `notContains`, `containsAll`, and `containsAny`
688
+ - `matches`, `doesNotMatch`, `maxLength`, and `requiredFields`
689
+ - `semanticSimilarity`, which uses an embedding model
690
+
691
+ Judge metrics call a completion model and record their evaluation token usage:
692
+
693
+ - `llmJudge` and `llmScore`
694
+ - `answerRelevancy`, `promptAlignment`, `jsonCorrectness`, and `summarization`
695
+ - `hallucination`, `faithfulness`, and `abstention`
696
+ - `gEval`, `turnRelevancy`, and `knowledgeRetention`
697
+
698
+ Numeric thresholds use values from `0` through `1`. `strictMode` requires a perfect higher-is-better
699
+ score or a zero lower-is-better score. Judge metrics default to including a final explanation;
700
+ setting `includeReason: false` saves that extra judge call when the explanation is unnecessary.
701
+
702
+ ### Typed custom metrics
703
+
704
+ Use `createEvalTypes` to bind input, output, and expected types once when defining multiple custom
705
+ metrics:
706
+
707
+ ```ts
708
+ import { createEvalTypes, EvalOutcome } from "@anvia/core/evals";
709
+
710
+ const supportEvals = createEvalTypes<string, { answer: string }, string>();
711
+
712
+ const noHandoff = supportEvals.defineMetric({
713
+ name: "no_handoff",
714
+ dataType: "BOOLEAN",
715
+ evaluate: ({ output, signal }) =>
716
+ signal.aborted || output.answer.includes("contact support")
717
+ ? EvalOutcome.fail(false)
718
+ : EvalOutcome.pass(true),
719
+ });
720
+ ```
721
+
722
+ Custom metrics return `EvalOutcome.pass`, `EvalOutcome.fail`, or `EvalOutcome.invalid`. Thrown metric
723
+ errors are converted to structured invalid outcomes containing the error kind and original error.
724
+
725
+ ### Execution controls
726
+
727
+ Evaluation targets receive an optional third argument containing the case `AbortSignal`.
728
+
729
+ ```ts
730
+ const result = await runEvalSuite({
731
+ // cases, target, and metrics...
732
+ name: "release gate",
733
+ cases,
734
+ target: async (input, testCase, context) =>
735
+ generateAnswer(input, { signal: context?.signal, metadata: testCase.metadata }),
736
+ metrics,
737
+ targetConcurrency: 4,
738
+ metricConcurrency: 2,
739
+ caseTimeoutMs: 30_000,
740
+ signal: deploymentSignal,
741
+ failFast: true,
742
+ caseIds: ["refund-window", "billing-owner"],
743
+ shard: { index: 0, count: 4 },
744
+ onProgress(event) {
745
+ console.log(event.type);
746
+ },
747
+ });
748
+ ```
749
+
750
+ - `concurrency` remains the shorthand for both target and metric concurrency.
751
+ - `targetConcurrency` and `metricConcurrency` can limit them independently.
752
+ - `caseTimeoutMs` covers the target and its metrics. Cooperative targets and metrics should observe
753
+ the supplied signal; the runner still stops awaiting work that ignores it.
754
+ - Aborting the suite-level `signal` stops scheduling cases and rejects the run with the abort reason.
755
+ - `caseIds`, `caseFilter`, and `shard` select cases before execution.
756
+ - `failFast` throws `EvalFailFastError` after the first completed required failure or invalid case.
757
+ - `onProgress` receives case, target, metric, and case-completion events.
758
+
759
+ Use `selectEvalCaseIds(previousResult)` to select failed and invalid cases for a rerun.
760
+
761
+ ### Results, usage, and failures
762
+
763
+ Every case result includes `targetStatus`, target and total durations, per-case usage and optional
764
+ cost. Every metric result includes its duration, optional cost, outcome, and reporter errors. A
765
+ successful target that returns `undefined` has `targetStatus: "succeeded"` and retains its `output`
766
+ property, so it is distinct from a failed target.
767
+
768
+ The suite aggregates metric totals, case totals, target and evaluation usage, costs, duration, and
769
+ all reporter errors. Invalid outcomes may include these `kind` values: `target`, `metric`,
770
+ `configuration`, `provider`, or `timeout`.
771
+
772
+ ### CI output and expectations
773
+
774
+ `runEvalCli` prints a result and can set `process.exitCode`. Exit code `1` means a required metric
775
+ failed; `2` means a required metric was invalid. Use `defineEvalExpectations` with a defined suite to
776
+ type-check case and metric names.
777
+
778
+ ```ts
779
+ import { defineEvalExpectations, defineEvalSuite, exactMatch, runEvalCli } from "@anvia/core/evals";
780
+
781
+ const suite = defineEvalSuite({
782
+ name: "release gate",
783
+ cases: [{ id: "refund", input: "refund", expected: "30 days" }],
784
+ target: async () => "30 days",
785
+ metrics: [exactMatch({ name: "correct" })],
786
+ });
787
+
788
+ await runEvalCli({
789
+ ...suite,
790
+ expectations: defineEvalExpectations(suite, {
791
+ outcomes: { refund: { correct: "pass" } },
792
+ }),
793
+ exitCode: true,
794
+ maxValueLength: 2_000,
795
+ redact: (value, context) => (context.kind === "input" ? "[redacted]" : value),
796
+ });
797
+ ```
798
+
799
+ Use `formatEvalResult` for pure pretty or JSON formatting without writing to stdout. Both
800
+ `formatEvalResult` and `runEvalCli` support value truncation and redaction. JSON output otherwise
801
+ contains cases, outputs, metadata, and error details, so redact sensitive data before writing it to
802
+ shared CI logs.
803
+
652
804
  ## Public Areas
653
805
 
654
806
  - `agent`: typed Agent runtime, retries, and stream events
@@ -12,6 +12,11 @@ import '../types-DmzRCbU5.js';
12
12
  import '../tool-BpqpoRSE.js';
13
13
  import '../middleware-kcF8AusP.js';
14
14
 
15
+ type EvalOutcomeOptions = {
16
+ comment?: string | undefined;
17
+ metadata?: EvalMetadata | undefined;
18
+ usage?: Usage | undefined;
19
+ };
15
20
  type EvalOutcome<Score = unknown> = {
16
21
  outcome: "pass";
17
22
  score?: Score | undefined;
@@ -27,32 +32,27 @@ type EvalOutcome<Score = unknown> = {
27
32
  } | {
28
33
  outcome: "invalid";
29
34
  reason: string;
35
+ kind?: EvalInvalidKind | undefined;
36
+ error?: unknown;
30
37
  score?: Score | undefined;
31
38
  comment?: string | undefined;
32
39
  metadata?: EvalMetadata | undefined;
33
40
  usage?: Usage | undefined;
34
41
  };
35
42
  declare const EvalOutcome: {
36
- pass<Score>(score?: Score, options?: {
37
- comment?: string | undefined;
38
- metadata?: EvalMetadata | undefined;
39
- usage?: Usage | undefined;
40
- }): EvalOutcome<Score>;
41
- fail<Score>(score?: Score, options?: {
42
- comment?: string | undefined;
43
- metadata?: EvalMetadata | undefined;
44
- usage?: Usage | undefined;
45
- }): EvalOutcome<Score>;
46
- invalid<Score = never>(reason: string, options?: {
43
+ pass<Score>(score?: Score, options?: EvalOutcomeOptions): EvalOutcome<Score>;
44
+ fail<Score>(score?: Score, options?: EvalOutcomeOptions): EvalOutcome<Score>;
45
+ invalid<Score = never>(reason: string, options?: EvalOutcomeOptions & {
47
46
  score?: Score | undefined;
48
- comment?: string | undefined;
49
- metadata?: EvalMetadata | undefined;
50
- usage?: Usage | undefined;
47
+ kind?: EvalInvalidKind | undefined;
48
+ error?: unknown;
51
49
  }): EvalOutcome<Score>;
50
+ fromError(error: unknown, kind?: EvalInvalidKind): EvalOutcome<never>;
52
51
  };
53
52
 
54
53
  type EvalMetadata = JsonObject;
55
54
  type EvalReporterErrorPolicy = "collect" | "throw";
55
+ type EvalInvalidKind = "target" | "metric" | "configuration" | "provider" | "timeout";
56
56
  type EvalRunOptions = {
57
57
  id?: string | undefined;
58
58
  datasetName?: string | undefined;
@@ -85,7 +85,10 @@ type EvalTraceRef = {
85
85
  observationId?: string | undefined;
86
86
  responseId?: string | undefined;
87
87
  };
88
- type EvalTarget<Input, Output, Expected = unknown> = (input: Input, testCase: EvalCase<Input, Expected>) => Output | Promise<Output>;
88
+ type EvalTarget<Input, Output, Expected = unknown> = (input: Input, testCase: EvalCase<Input, Expected>, context?: EvalTargetContext) => Output | Promise<Output>;
89
+ type EvalTargetContext = {
90
+ signal: AbortSignal;
91
+ };
89
92
  type EvalOutcomeStatus = "pass" | "fail" | "invalid";
90
93
  type EvalScoreDirection = "higher_is_better" | "lower_is_better";
91
94
  type EvalDataType = "NUMERIC" | "CATEGORICAL" | "BOOLEAN";
@@ -129,6 +132,7 @@ type EvalMetricArgs<Input, Output, Expected = unknown> = {
129
132
  suiteName: string;
130
133
  case: EvalCase<Input, Expected>;
131
134
  output: Output;
135
+ signal: AbortSignal;
132
136
  };
133
137
  type EvalMetric<Input, Output, Score = unknown, Expected = unknown, Name extends string = string, Requirements extends EvalCaseRequirements = Record<never, never>> = {
134
138
  name: Name;
@@ -149,6 +153,8 @@ type EvalMetricResult<Score = unknown, Name extends string = string> = {
149
153
  direction?: EvalScoreDirection | undefined;
150
154
  threshold?: number | undefined;
151
155
  outcome: EvalOutcome<Score>;
156
+ durationMs: number;
157
+ cost?: number | undefined;
152
158
  reporterErrors: unknown[];
153
159
  };
154
160
  type AnyEvalMetric = EvalMetric<never, never, unknown, never, string>;
@@ -164,10 +170,15 @@ type EvalScoreMap<Metrics extends readonly AnyEvalMetric[]> = {
164
170
  type EvalCaseResult<Input, Output, Expected = unknown, Metrics extends readonly AnyEvalMetric[] = readonly AnyEvalMetric[]> = {
165
171
  case: EvalCase<Input, Expected>;
166
172
  outcome: EvalOutcomeStatus;
173
+ targetStatus: "succeeded" | "failed";
167
174
  output?: Output | undefined;
168
175
  targetError?: unknown;
176
+ targetDurationMs: number;
177
+ durationMs: number;
169
178
  metrics: Array<EvalMetricResultFor<Metrics[number]>>;
170
179
  scores: EvalScoreMap<Metrics>;
180
+ usage: EvalUsageSummary;
181
+ cost?: EvalCostSummary | undefined;
171
182
  };
172
183
  type EvalSuiteResult<Input, Output, Expected = unknown, Metrics extends readonly AnyEvalMetric[] = readonly AnyEvalMetric[]> = {
173
184
  name: string;
@@ -191,6 +202,7 @@ type EvalReportArgs<Input, Output, Score = unknown, Expected = unknown> = {
191
202
  case: EvalCase<Input, Expected>;
192
203
  output?: Output | undefined;
193
204
  targetError?: unknown;
205
+ targetStatus?: "succeeded" | "failed" | undefined;
194
206
  trace?: EvalTraceRef | undefined;
195
207
  metric: EvalMetricDescriptor<Score>;
196
208
  outcome: EvalOutcome<Score>;
@@ -216,6 +228,7 @@ type EvalTraceSelectorArgs<Input, Output, Expected = unknown> = {
216
228
  case: EvalCase<Input, Expected>;
217
229
  output?: Output | undefined;
218
230
  targetError?: unknown;
231
+ targetStatus?: "succeeded" | "failed" | undefined;
219
232
  };
220
233
  type EvalTraceSelector<Input, Output, Expected = unknown> = (args: EvalTraceSelectorArgs<Input, Output, Expected>) => EvalTraceRef | undefined | Promise<EvalTraceRef | undefined>;
221
234
  type EvalReporter<in Input = unknown, in Output = unknown, in Expected = unknown> = {
@@ -242,13 +255,81 @@ type EvalCostOptions<Input, Output, Expected = unknown> = {
242
255
  currency: string;
243
256
  calculate(args: EvalCostCalculatorArgs<Input, Output, Expected>): number | Promise<number>;
244
257
  };
258
+ type EvalCaseLike$1 = EvalCase<unknown, unknown>;
259
+ type EvalMetricRequirements<Metric> = Metric extends EvalMetric<infer _Input, infer _Output, infer _Score, infer _Expected, infer _Name, infer Requirements> ? Requirements : Record<never, never>;
260
+ type RequiredExpected<Metrics extends readonly EvalMetric<never, never>[]> = Extract<EvalMetricRequirements<Metrics[number]>, {
261
+ expected: unknown;
262
+ }>;
263
+ type RequiredContext<Metrics extends readonly EvalMetric<never, never>[]> = Extract<EvalMetricRequirements<Metrics[number]>, {
264
+ context: string[];
265
+ }>;
266
+ type RequiredRetrievalContext<Metrics extends readonly EvalMetric<never, never>[]> = Extract<EvalMetricRequirements<Metrics[number]>, {
267
+ retrievalContext: string[];
268
+ }>;
269
+ type EvalCaseFieldsForMetrics<Metrics extends readonly EvalMetric<never, never>[]> = ([
270
+ RequiredExpected<Metrics>
271
+ ] extends [never] ? Record<never, never> : {
272
+ expected: RequiredExpected<Metrics>["expected"];
273
+ }) & ([RequiredContext<Metrics>] extends [never] ? Record<never, never> : {
274
+ context: string[];
275
+ }) & ([RequiredRetrievalContext<Metrics>] extends [never] ? Record<never, never> : {
276
+ retrievalContext: string[];
277
+ });
278
+ type EvalCasesForMetrics<Cases extends readonly EvalCaseLike$1[], Metrics extends readonly EvalMetric<never, never>[]> = {
279
+ readonly [Index in keyof Cases]: Cases[Index] extends EvalCaseLike$1 ? Cases[Index] & EvalCaseFieldsForMetrics<Metrics> : Cases[Index];
280
+ };
281
+ type EvalShard = {
282
+ index: number;
283
+ count: number;
284
+ };
285
+ type EvalProgressEvent<Input, Output, Expected = unknown> = {
286
+ type: "case-start";
287
+ suiteName: string;
288
+ case: EvalCase<Input, Expected>;
289
+ completedCases: number;
290
+ totalCases: number;
291
+ } | {
292
+ type: "target-complete";
293
+ suiteName: string;
294
+ case: EvalCase<Input, Expected>;
295
+ targetStatus: "succeeded" | "failed";
296
+ output?: Output | undefined;
297
+ error?: unknown;
298
+ durationMs: number;
299
+ completedCases: number;
300
+ totalCases: number;
301
+ } | {
302
+ type: "metric-complete";
303
+ suiteName: string;
304
+ case: EvalCase<Input, Expected>;
305
+ metricName: string;
306
+ outcome: EvalOutcome<unknown>;
307
+ durationMs: number;
308
+ completedCases: number;
309
+ totalCases: number;
310
+ } | {
311
+ type: "case-complete";
312
+ suiteName: string;
313
+ result: EvalCaseResult<Input, Output, Expected>;
314
+ completedCases: number;
315
+ totalCases: number;
316
+ };
245
317
  type RunEvalSuiteOptions<Input, Output, Expected = unknown, Metrics extends readonly EvalMetric<NoInfer<Input>, NoInfer<Output>, unknown, NoInfer<Expected>, string>[] = readonly EvalMetric<NoInfer<Input>, NoInfer<Output>, unknown, NoInfer<Expected>, string>[]> = {
246
318
  name: string;
247
319
  run?: EvalRunOptions | undefined;
248
- cases: readonly EvalCase<Input, Expected>[];
320
+ cases: readonly EvalCase<Input, Expected>[] & EvalCasesForMetrics<readonly EvalCase<Input, Expected>[], Metrics>;
249
321
  target: EvalTarget<Input, Output, Expected>;
250
322
  metrics: Metrics;
251
323
  concurrency?: number | undefined;
324
+ targetConcurrency?: number | undefined;
325
+ metricConcurrency?: number | undefined;
326
+ caseTimeoutMs?: number | undefined;
327
+ signal?: AbortSignal | undefined;
328
+ failFast?: boolean | undefined;
329
+ caseIds?: readonly string[] | undefined;
330
+ caseFilter?(testCase: EvalCase<Input, Expected>, index: number): boolean;
331
+ shard?: EvalShard | undefined;
332
+ onProgress?(event: EvalProgressEvent<Input, Output, Expected>): void | Promise<void>;
252
333
  trace?: EvalTraceSelector<NoInfer<Input>, NoInfer<Output>, NoInfer<Expected>> | undefined;
253
334
  reporters?: readonly EvalReporter<NoInfer<Input>, NoInfer<Output>, NoInfer<Expected>>[] | undefined;
254
335
  reporterErrorPolicy?: EvalReporterErrorPolicy | undefined;
@@ -358,9 +439,20 @@ type GEvalOptions<Input, Output, Expected = unknown> = Omit<LlmEvalOptions<Input
358
439
  context?: SelectorOrValue<Input, Output, Expected, string[]> | undefined;
359
440
  retrievalContext?: SelectorOrValue<Input, Output, Expected, string[]> | undefined;
360
441
  };
361
- declare function gEval<Input, Output, Expected = unknown, const Name extends string = string>(options: GEvalOptions<Input, Output, Expected> & {
442
+ type GEvalCaseRequirements<Params extends readonly GEvalParameter[], ExpectedSelector, ContextSelector, RetrievalContextSelector> = ("expectedOutput" extends Params[number] ? [ExpectedSelector] extends [undefined] ? {
443
+ expected: unknown;
444
+ } : Record<never, never> : Record<never, never>) & ("context" extends Params[number] ? [ContextSelector] extends [undefined] ? {
445
+ context: string[];
446
+ } : Record<never, never> : Record<never, never>) & ("retrievalContext" extends Params[number] ? [RetrievalContextSelector] extends [undefined] ? {
447
+ retrievalContext: string[];
448
+ } : Record<never, never> : Record<never, never>);
449
+ declare function gEval<Input, Output, Expected = unknown, const Name extends string = string, const Params extends readonly GEvalParameter[] = readonly GEvalParameter[], ExpectedSelector extends ValueSelector<Input, Output, Expected, unknown> | undefined = undefined, ContextSelector extends SelectorOrValue<Input, Output, Expected, string[]> | undefined = undefined, RetrievalContextSelector extends SelectorOrValue<Input, Output, Expected, string[]> | undefined = undefined>(options: Omit<GEvalOptions<Input, Output, Expected>, "evaluationParams" | "expected" | "context" | "retrievalContext"> & {
362
450
  name: Name;
363
- }): EvalMetric<Input, Output, number, Expected, Name>;
451
+ evaluationParams: Params;
452
+ expected?: ExpectedSelector;
453
+ context?: ContextSelector;
454
+ retrievalContext?: RetrievalContextSelector;
455
+ }): EvalMetric<Input, Output, number, Expected, Name, GEvalCaseRequirements<Params, ExpectedSelector, ContextSelector, RetrievalContextSelector>>;
364
456
  type ConversationEvalOptions<Input, Output, Expected = unknown> = {
365
457
  name?: string | undefined;
366
458
  required?: boolean | undefined;
@@ -434,26 +526,58 @@ type EvalOutputWriters = {
434
526
  stdout?(text: string): void;
435
527
  stderr?(text: string): void;
436
528
  };
529
+ type EvalRedactionContext = {
530
+ kind: "input" | "expected" | "context" | "retrievalContext" | "output" | "score" | "comment" | "metadata" | "error";
531
+ caseId?: string | undefined;
532
+ metricName?: string | undefined;
533
+ };
534
+ type EvalRedactor = (value: unknown, context: EvalRedactionContext) => unknown;
437
535
  type PrintEvalResultOptions = {
438
536
  format?: EvalOutputFormat | undefined;
439
537
  output?: EvalOutputWriters | undefined;
538
+ maxValueLength?: number | undefined;
539
+ redact?: EvalRedactor | undefined;
540
+ };
541
+ type EvalSuiteShape = {
542
+ cases: readonly {
543
+ id: string;
544
+ }[];
545
+ metrics: readonly {
546
+ name: string;
547
+ }[];
548
+ };
549
+ type EvalExpectedOutcomesFor<Suite extends EvalSuiteShape> = Partial<Record<Suite["cases"][number]["id"], Partial<Record<Suite["metrics"][number]["name"], EvalOutcomeStatus>>>>;
550
+ type EvalExpectationsFor<Suite extends EvalSuiteShape> = Omit<EvalExpectations, "outcomes"> & {
551
+ outcomes?: EvalExpectedOutcomesFor<Suite> | undefined;
440
552
  };
441
553
  type RunEvalCliOptions<Input, Output, Expected = unknown, Metrics extends readonly EvalMetric<NoInfer<Input>, NoInfer<Output>, unknown, NoInfer<Expected>, string>[] = readonly EvalMetric<NoInfer<Input>, NoInfer<Output>, unknown, NoInfer<Expected>, string>[]> = RunEvalSuiteOptions<Input, Output, Expected, Metrics> & {
442
554
  format?: EvalOutputFormat | undefined;
443
555
  exitCode?: boolean | undefined;
444
556
  expectations?: EvalExpectations | undefined;
445
557
  output?: EvalOutputWriters | undefined;
558
+ maxValueLength?: number | undefined;
559
+ redact?: EvalRedactor | undefined;
446
560
  };
447
561
  declare class EvalAssertionError extends Error {
448
562
  readonly mismatches: string[];
449
563
  constructor(message: string, mismatches: string[]);
450
564
  }
565
+ declare function defineEvalExpectations<const Suite extends EvalSuiteShape>(_suite: Suite, expectations: EvalExpectationsFor<NoInfer<Suite>>): EvalExpectationsFor<Suite>;
566
+ declare function formatEvalResult(result: EvalSuiteResult<unknown, unknown, unknown>, options?: Omit<PrintEvalResultOptions, "output">): string;
451
567
  declare function printEvalResult(result: EvalSuiteResult<unknown, unknown, unknown>, options?: PrintEvalResultOptions): void;
452
568
  declare function evalExitCode(result: EvalSuiteResult<unknown, unknown, unknown>, expectations?: EvalExpectations): 0 | 1 | 2;
453
569
  declare function assertEvalTotals(result: EvalSuiteResult<unknown, unknown, unknown>, expected: EvalExpectedTotals): void;
454
570
  declare function assertEvalOutcomes(result: EvalSuiteResult<unknown, unknown, unknown>, expected: EvalExpectedOutcomes): void;
455
571
  declare function runEvalCli<Input, Output, Expected = unknown, const Metrics extends readonly EvalMetric<NoInfer<Input>, NoInfer<Output>, unknown, NoInfer<Expected>, string>[] = readonly EvalMetric<NoInfer<Input>, NoInfer<Output>, unknown, NoInfer<Expected>, string>[]>(options: RunEvalCliOptions<Input, Output, Expected, Metrics>): Promise<EvalSuiteResult<Input, Output, Expected, Metrics>>;
456
572
 
573
+ declare class EvalTimeoutError extends Error {
574
+ readonly timeoutMs: number;
575
+ constructor(timeoutMs: number);
576
+ }
577
+ declare class EvalAbortError extends Error {
578
+ constructor(message?: string);
579
+ }
580
+
457
581
  declare function defineMetric<Input, Output, Score, Expected, const Name extends string = string>(metric: EvalMetric<Input, Output, Score, Expected, Name>): EvalMetric<Input, Output, Score, Expected, Name>;
458
582
 
459
583
  type ExactMatchOptions<Input, Output, Expected = unknown> = {
@@ -489,9 +613,16 @@ declare function contains<Input, Output, Expected = unknown, const Name extends
489
613
  expected: string | RegExp;
490
614
  }>;
491
615
  type NotContainsOptions<Input, Output, Expected = unknown> = ContainsOptions<Input, Output, Expected>;
492
- declare function notContains<Input, Output, Expected = unknown, const Name extends string = string>(options?: NotContainsOptions<Input, Output, Expected> & {
616
+ declare function notContains<Input, Output, Expected = unknown, const Name extends string = string>(options: NotContainsOptions<Input, Output, Expected> & {
617
+ expected: Exclude<NotContainsOptions<Input, Output, Expected>["expected"], undefined>;
493
618
  name?: Name | undefined;
494
619
  }): EvalMetric<Input, Output, boolean, Expected, Name>;
620
+ declare function notContains<Input, Output, Expected = unknown, const Name extends string = string>(options?: Omit<NotContainsOptions<Input, Output, Expected>, "expected"> & {
621
+ expected?: undefined;
622
+ name?: Name | undefined;
623
+ }): EvalMetric<Input, Output, boolean, Expected, Name, {
624
+ expected: string | RegExp;
625
+ }>;
495
626
  type ContainsListOptions<Input, Output, Expected = unknown> = {
496
627
  name?: string | undefined;
497
628
  required?: boolean | undefined;
@@ -500,12 +631,26 @@ type ContainsListOptions<Input, Output, Expected = unknown> = {
500
631
  };
501
632
  type ContainsAllOptions<Input, Output, Expected = unknown> = ContainsListOptions<Input, Output, Expected>;
502
633
  declare function containsAll<Input, Output, Expected = unknown, const Name extends string = string>(options: ContainsAllOptions<Input, Output, Expected> & {
634
+ expected: Exclude<ContainsAllOptions<Input, Output, Expected>["expected"], undefined>;
503
635
  name?: Name | undefined;
504
636
  }): EvalMetric<Input, Output, boolean, Expected, Name>;
637
+ declare function containsAll<Input, Output, Expected = unknown, const Name extends string = string>(options: Omit<ContainsAllOptions<Input, Output, Expected>, "expected"> & {
638
+ expected?: undefined;
639
+ name?: Name | undefined;
640
+ }): EvalMetric<Input, Output, boolean, Expected, Name, {
641
+ expected: ReadonlyArray<string | RegExp>;
642
+ }>;
505
643
  type ContainsAnyOptions<Input, Output, Expected = unknown> = ContainsListOptions<Input, Output, Expected>;
506
644
  declare function containsAny<Input, Output, Expected = unknown, const Name extends string = string>(options: ContainsAnyOptions<Input, Output, Expected> & {
645
+ expected: Exclude<ContainsAnyOptions<Input, Output, Expected>["expected"], undefined>;
507
646
  name?: Name | undefined;
508
647
  }): EvalMetric<Input, Output, boolean, Expected, Name>;
648
+ declare function containsAny<Input, Output, Expected = unknown, const Name extends string = string>(options: Omit<ContainsAnyOptions<Input, Output, Expected>, "expected"> & {
649
+ expected?: undefined;
650
+ name?: Name | undefined;
651
+ }): EvalMetric<Input, Output, boolean, Expected, Name, {
652
+ expected: ReadonlyArray<string | RegExp>;
653
+ }>;
509
654
  type MatchesOptions<Input, Output, Expected = unknown> = {
510
655
  name?: string | undefined;
511
656
  required?: boolean | undefined;
@@ -513,12 +658,26 @@ type MatchesOptions<Input, Output, Expected = unknown> = {
513
658
  expected?: SelectorOrValue<Input, Output, Expected, RegExp> | undefined;
514
659
  };
515
660
  declare function matches<Input, Output, Expected = unknown, const Name extends string = string>(options: MatchesOptions<Input, Output, Expected> & {
661
+ expected: Exclude<MatchesOptions<Input, Output, Expected>["expected"], undefined>;
516
662
  name?: Name | undefined;
517
663
  }): EvalMetric<Input, Output, boolean, Expected, Name>;
664
+ declare function matches<Input, Output, Expected = unknown, const Name extends string = string>(options: Omit<MatchesOptions<Input, Output, Expected>, "expected"> & {
665
+ expected?: undefined;
666
+ name?: Name | undefined;
667
+ }): EvalMetric<Input, Output, boolean, Expected, Name, {
668
+ expected: RegExp;
669
+ }>;
518
670
  type DoesNotMatchOptions<Input, Output, Expected = unknown> = MatchesOptions<Input, Output, Expected>;
519
671
  declare function doesNotMatch<Input, Output, Expected = unknown, const Name extends string = string>(options: DoesNotMatchOptions<Input, Output, Expected> & {
672
+ expected: Exclude<DoesNotMatchOptions<Input, Output, Expected>["expected"], undefined>;
520
673
  name?: Name | undefined;
521
674
  }): EvalMetric<Input, Output, boolean, Expected, Name>;
675
+ declare function doesNotMatch<Input, Output, Expected = unknown, const Name extends string = string>(options: Omit<DoesNotMatchOptions<Input, Output, Expected>, "expected"> & {
676
+ expected?: undefined;
677
+ name?: Name | undefined;
678
+ }): EvalMetric<Input, Output, boolean, Expected, Name, {
679
+ expected: RegExp;
680
+ }>;
522
681
  type MaxLengthOptions<Input, Output, Expected = unknown> = {
523
682
  name?: string | undefined;
524
683
  required?: boolean | undefined;
@@ -598,9 +757,15 @@ declare class EvalReporterDispatchError extends AggregateError {
598
757
  readonly phase: string;
599
758
  constructor(phase: string, errors: readonly unknown[]);
600
759
  }
760
+ declare class EvalFailFastError extends Error {
761
+ readonly caseId: string;
762
+ readonly outcome: "fail" | "invalid";
763
+ constructor(caseId: string, outcome: "fail" | "invalid");
764
+ }
601
765
  declare function runEvalSuite<Input, Output, Expected = unknown, const Metrics extends readonly EvalMetric<NoInfer<Input>, NoInfer<Output>, unknown, NoInfer<Expected>, string>[] = readonly EvalMetric<NoInfer<Input>, NoInfer<Output>, unknown, NoInfer<Expected>, string>[]>(options: RunEvalSuiteOptions<Input, Output, Expected, Metrics>): Promise<EvalSuiteResult<Input, Output, Expected, Metrics>>;
602
766
 
603
767
  declare function selectPromptOutput(args: EvalMetricArgs<unknown, unknown, unknown>): string;
768
+ declare function selectEvalCaseIds(result: EvalSuiteResult<unknown, unknown, unknown>, outcomes?: readonly EvalOutcomeStatus[]): string[];
604
769
 
605
770
  type EvalCaseLike = EvalCase<unknown, unknown>;
606
771
  type EvalCasesInput<Cases extends readonly EvalCaseLike[]> = Cases[number]["input"];
@@ -608,30 +773,9 @@ type EvalCaseExpected<Case> = Case extends {
608
773
  expected: infer Expected;
609
774
  } ? Expected : unknown;
610
775
  type EvalCasesExpected<Cases extends readonly EvalCaseLike[]> = EvalCaseExpected<Cases[number]>;
611
- type EvalMetricRequirements<Metric> = Metric extends EvalMetric<infer _Input, infer _Output, infer _Score, infer _Expected, infer _Name, infer Requirements> ? Requirements : Record<never, never>;
612
- type RequiredExpected<Metrics extends readonly EvalMetric<never, never>[]> = Extract<EvalMetricRequirements<Metrics[number]>, {
613
- expected: unknown;
614
- }>;
615
- type RequiredContext<Metrics extends readonly EvalMetric<never, never>[]> = Extract<EvalMetricRequirements<Metrics[number]>, {
616
- context: string[];
617
- }>;
618
- type RequiredRetrievalContext<Metrics extends readonly EvalMetric<never, never>[]> = Extract<EvalMetricRequirements<Metrics[number]>, {
619
- retrievalContext: string[];
620
- }>;
621
- type EvalCaseFieldsForMetrics<Metrics extends readonly EvalMetric<never, never>[]> = ([
622
- RequiredExpected<Metrics>
623
- ] extends [never] ? Record<never, never> : {
624
- expected: RequiredExpected<Metrics>["expected"];
625
- }) & ([RequiredContext<Metrics>] extends [never] ? Record<never, never> : {
626
- context: string[];
627
- }) & ([RequiredRetrievalContext<Metrics>] extends [never] ? Record<never, never> : {
628
- retrievalContext: string[];
629
- });
630
- type EvalCasesForMetrics<Cases extends readonly EvalCaseLike[], Metrics extends readonly EvalMetric<never, never>[]> = {
631
- readonly [Index in keyof Cases]: Cases[Index] & EvalCaseFieldsForMetrics<Metrics>;
632
- };
633
- type DefinedEvalSuite<Cases extends readonly EvalCaseLike[], Output, Metrics extends readonly EvalMetric<EvalCasesInput<Cases>, Output, unknown, EvalCasesExpected<Cases>, string>[]> = Omit<RunEvalSuiteOptions<EvalCasesInput<Cases>, Output, EvalCasesExpected<Cases>, Metrics>, "cases" | "target" | "metrics"> & {
776
+ type DefinedEvalSuite<Cases extends readonly EvalCaseLike[], Output, Metrics extends readonly EvalMetric<EvalCasesInput<Cases>, Output, unknown, EvalCasesExpected<Cases>, string>[]> = Omit<RunEvalSuiteOptions<EvalCasesInput<Cases>, Output, EvalCasesExpected<Cases>, Metrics>, "caseIds" | "cases" | "target" | "metrics"> & {
634
777
  cases: Cases & EvalCasesForMetrics<NoInfer<Cases>, NoInfer<Metrics>>;
778
+ caseIds?: readonly Cases[number]["id"][] | undefined;
635
779
  target: EvalTarget<EvalCasesInput<Cases>, Output, EvalCasesExpected<Cases>>;
636
780
  metrics: Metrics;
637
781
  };
@@ -662,6 +806,8 @@ type EvalMetricFactory<Input, Output, Expected = unknown> = {
662
806
  }): EvalMetric<Input, Output, Score, Expected, Name>;
663
807
  };
664
808
  declare function defineEvalCases<const Cases extends readonly EvalCaseLike[]>(cases: Cases): Cases;
809
+ declare function createEvalTypes<Input, Output, Expected = unknown>(): EvalMetricFactory<Input, Output, Expected>;
810
+ /** @deprecated Use createEvalTypes() when defining typed custom metrics. */
665
811
  declare function defineEvalSuite<Input, Output, Expected = unknown>(): EvalMetricFactory<Input, Output, Expected>;
666
812
  declare function defineEvalSuite<const Cases extends readonly EvalCaseLike[], const Target extends (input: EvalCasesInput<Cases>, testCase: EvalCase<EvalCasesInput<Cases>, EvalCasesExpected<Cases>>) => unknown, const Metrics extends readonly EvalMetric<EvalCasesInput<Cases>, Awaited<ReturnType<Target>>, unknown, EvalCasesExpected<Cases>, string>[]>(options: DefinedEvalSuite<Cases, Awaited<ReturnType<Target>>, Metrics> & {
667
813
  target: Target;
@@ -669,4 +815,4 @@ declare function defineEvalSuite<const Cases extends readonly EvalCaseLike[], co
669
815
  target: Target;
670
816
  };
671
817
 
672
- export { type AbstentionCategory, type AbstentionOptions, AgentEvalSuspensionError, type AgentEvalTargetOptions, type AnswerRelevancyOptions, type AnyEvalMetric, type ContainsAllOptions, type ContainsAnyOptions, type ContainsListOptions, type ContainsOptions, type DefaultEvalActual, type DefinedEvalSuite, type DoesNotMatchOptions, EvalAssertionError, type EvalCase, type EvalCaseRequirements, type EvalCaseResult, type EvalCasesExpected, type EvalCasesForMetrics, type EvalCasesInput, type EvalCostCalculatorArgs, type EvalCostOptions, type EvalCostSummary, type EvalDataType, type EvalExpectations, type EvalExpectedOutcomes, type EvalExpectedTotals, type EvalMetadata, type EvalMetric, type EvalMetricArgs, type EvalMetricDescriptor, type EvalMetricResult, type EvalMetricResultFor, type EvalMetricScore, EvalOutcome, type EvalOutcomeStatus, type EvalOutputFormat, type EvalOutputWriters, type EvalReportArgs, type EvalReporter, EvalReporterDispatchError, type EvalReporterErrorPolicy, type EvalRunContext, type EvalRunEndArgs, type EvalRunOptions, type EvalRunStartArgs, type EvalScoreDirection, type EvalScoreMap, type EvalScoreProjection, type EvalSuiteResult, type EvalTarget, type EvalTargetUsageSelector, type EvalTotals, type EvalTraceCarrier, type EvalTraceRef, type EvalTraceSelector, type EvalTraceSelectorArgs, type EvalTurn, type EvalUsageSummary, type ExactMatchOptions, type FaithfulnessOptions, type GEvalOptions, type GEvalParameter, type GEvalRubric, type HallucinationOptions, type JsonCorrectnessOptions, type KnowledgeRetentionOptions, type LlmJudgeOptions, type LlmScoreMetricScore, type LlmScoreOptions, type MatchesOptions, type MaxLengthOptions, type NotContainsOptions, type PrintEvalResultOptions, type PromptAlignmentOptions, type RequiredFieldsOptions, type RunEvalCliOptions, type RunEvalSuiteOptions, type SelectorOrValue, type SemanticSimilarityOptions, type SummarizationOptions, type TurnRelevancyOptions, type ValueSelector, abstention, agentEvalTarget, answerRelevancy, assertEvalOutcomes, assertEvalTotals, contains, containsAll, containsAny, defaultEvalTraceSelector, defineEvalCases, defineEvalSuite, defineMetric, doesNotMatch, evalExitCode, exactMatch, faithfulness, gEval, hallucination, jsonCorrectness, knowledgeRetention, llmJudge, llmScore, matches, maxLength, notContains, printEvalResult, projectEvalOutcome, promptAlignment, requiredFields, resolveEvalTraceRef, runEvalCli, runEvalSuite, selectPromptOutput, semanticSimilarity, summarization, turnRelevancy };
818
+ export { type AbstentionCategory, type AbstentionOptions, AgentEvalSuspensionError, type AgentEvalTargetOptions, type AnswerRelevancyOptions, type AnyEvalMetric, type ContainsAllOptions, type ContainsAnyOptions, type ContainsListOptions, type ContainsOptions, type DefaultEvalActual, type DefinedEvalSuite, type DoesNotMatchOptions, EvalAbortError, EvalAssertionError, type EvalCase, type EvalCaseRequirements, type EvalCaseResult, type EvalCasesExpected, type EvalCasesForMetrics, type EvalCasesInput, type EvalCostCalculatorArgs, type EvalCostOptions, type EvalCostSummary, type EvalDataType, type EvalExpectations, type EvalExpectationsFor, type EvalExpectedOutcomes, type EvalExpectedOutcomesFor, type EvalExpectedTotals, EvalFailFastError, type EvalInvalidKind, type EvalMetadata, type EvalMetric, type EvalMetricArgs, type EvalMetricDescriptor, type EvalMetricResult, type EvalMetricResultFor, type EvalMetricScore, EvalOutcome, type EvalOutcomeStatus, type EvalOutputFormat, type EvalOutputWriters, type EvalProgressEvent, type EvalRedactionContext, type EvalRedactor, type EvalReportArgs, type EvalReporter, EvalReporterDispatchError, type EvalReporterErrorPolicy, type EvalRunContext, type EvalRunEndArgs, type EvalRunOptions, type EvalRunStartArgs, type EvalScoreDirection, type EvalScoreMap, type EvalScoreProjection, type EvalShard, type EvalSuiteResult, type EvalTarget, type EvalTargetContext, type EvalTargetUsageSelector, EvalTimeoutError, type EvalTotals, type EvalTraceCarrier, type EvalTraceRef, type EvalTraceSelector, type EvalTraceSelectorArgs, type EvalTurn, type EvalUsageSummary, type ExactMatchOptions, type FaithfulnessOptions, type GEvalOptions, type GEvalParameter, type GEvalRubric, type HallucinationOptions, type JsonCorrectnessOptions, type KnowledgeRetentionOptions, type LlmJudgeOptions, type LlmScoreMetricScore, type LlmScoreOptions, type MatchesOptions, type MaxLengthOptions, type NotContainsOptions, type PrintEvalResultOptions, type PromptAlignmentOptions, type RequiredFieldsOptions, type RunEvalCliOptions, type RunEvalSuiteOptions, type SelectorOrValue, type SemanticSimilarityOptions, type SummarizationOptions, type TurnRelevancyOptions, type ValueSelector, abstention, agentEvalTarget, answerRelevancy, assertEvalOutcomes, assertEvalTotals, contains, containsAll, containsAny, createEvalTypes, defaultEvalTraceSelector, defineEvalCases, defineEvalExpectations, defineEvalSuite, defineMetric, doesNotMatch, evalExitCode, exactMatch, faithfulness, formatEvalResult, gEval, hallucination, jsonCorrectness, knowledgeRetention, llmJudge, llmScore, matches, maxLength, notContains, printEvalResult, projectEvalOutcome, promptAlignment, requiredFields, resolveEvalTraceRef, runEvalCli, runEvalSuite, selectEvalCaseIds, selectPromptOutput, semanticSimilarity, summarization, turnRelevancy };