-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathframework.py
More file actions
1744 lines (1463 loc) · 62.9 KB
/
framework.py
File metadata and controls
1744 lines (1463 loc) · 62.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 abc
import asyncio
import contextvars
import dataclasses
import inspect
import json
import re
import sys
import traceback
import warnings
from collections import defaultdict
from collections.abc import Awaitable, Callable, Coroutine, Iterable, Iterator, Sequence
from concurrent.futures import ThreadPoolExecutor
from contextlib import contextmanager
from multiprocessing import cpu_count
from typing import (
Any,
Generic,
Literal,
Optional,
TypeVar,
Union,
)
from tqdm.asyncio import tqdm as async_tqdm
from tqdm.auto import tqdm as std_tqdm
from typing_extensions import NotRequired, Protocol, TypedDict
from .generated_types import FunctionFormat, FunctionOutputType, ObjectReference
from .git_fields import GitMetadataSettings, RepoInfo
from .logger import (
BraintrustState,
Dataset,
Experiment,
ExperimentSummary,
Metadata,
ScoreSummary,
Span,
_ExperimentDatasetEvent,
parent_context,
start_span,
stringify_exception,
)
from .logger import init as _init_experiment
from .parameters import (
EvalParameters,
RemoteEvalParameters,
ValidatedParameters,
is_eval_parameter_schema,
validate_parameters,
)
from .resource_manager import ResourceManager
from .score import Score, is_score, is_scorer
from .serializable_data_class import SerializableDataClass
from .span_types import SpanTypeAttribute
from .util import bt_iscoroutinefunction, eprint, merge_dicts
Input = TypeVar("Input")
Output = TypeVar("Output")
# https://stackoverflow.com/questions/287871/how-do-i-print-colored-text-to-the-terminal
class bcolors:
# HEADER = "\033[95m"
# OKBLUE = "\033[94m"
# OKCYAN = "\033[96m"
# OKGREEN = "\033[92m"
WARNING = "\033[93m"
FAIL = "\033[91m"
ENDC = "\033[0m"
# BOLD = "\033[1m"
# UNDERLINE = "\033[4m"
@dataclasses.dataclass
class EvalCase(SerializableDataClass, Generic[Input, Output]):
"""
An evaluation case. This is a single input to the evaluation task, along with an optional expected
output, metadata, and tags.
"""
input: Input
expected: Output | None = None
metadata: Metadata | None = None
tags: Sequence[str] | None = None
# These fields are only set if the EvalCase is part of a Dataset.
id: str | None = None
_xact_id: str | None = None
created: str | None = None
class _EvalCaseDictNoOutput(Generic[Input], TypedDict):
"""
Workaround for the Pyright type checker handling of generics. Specifically,
the type checker doesn't know that a dict which is missing the key
"expected" can be used to satisfy `_EvalCaseDict[Input, Output]` for any
`Output` type.
"""
input: Input
metadata: NotRequired[Metadata | None]
tags: NotRequired[Sequence[str] | None]
id: NotRequired[str | None]
_xact_id: NotRequired[str | None]
class _EvalCaseDict(Generic[Input, Output], _EvalCaseDictNoOutput[Input]):
"""
Mirrors EvalCase for callers who pass a dict instead of dataclass.
"""
expected: NotRequired[Output | None]
# Inheritance doesn't quite work for dataclasses, so we redefine the fields
# from EvalCase here.
@dataclasses.dataclass
class EvalResult(SerializableDataClass, Generic[Input, Output]):
"""The result of an evaluation. This includes the input, expected output, actual output, and metadata."""
input: Input
output: Output
scores: dict[str, float | None]
expected: Output | None = None
metadata: Metadata | None = None
tags: list[str] | None = None
error: Exception | None = None
exc_info: str | None = None
@dataclasses.dataclass
class TaskProgressEvent(TypedDict):
"""Progress event that can be reported during task execution."""
format: FunctionFormat
output_type: FunctionOutputType
event: Literal[
"reasoning_delta",
"text_delta",
"json_delta",
"error",
"console",
"start",
"done",
"progress",
]
data: str
class SSEProgressEvent(TaskProgressEvent):
"""
A progress event that can be reported during task execution, specifically for SSE (Server-Sent Events) streams.
This is a subclass of TaskProgressEvent with additional fields for SSE-specific metadata.
"""
id: str
object_type: str
origin: ObjectReference
name: str
class EvalHooks(abc.ABC, Generic[Output]):
"""
An object that can be used to add metadata to an evaluation. This is passed to the `task` function.
"""
@property
@abc.abstractmethod
def metadata(self) -> Metadata | None:
"""
The metadata object for the current evaluation. You can mutate this object to add or remove metadata.
"""
@property
@abc.abstractmethod
def expected(self) -> Output | None:
"""
The expected output for the current evaluation.
"""
@property
@abc.abstractmethod
def span(self) -> Span:
"""
Access the span under which the task is run. Also accessible via braintrust.current_span()
"""
@property
@abc.abstractmethod
def trial_index(self) -> int:
"""
The index of the current trial (0-based). This is useful when trial_count > 1.
"""
@property
@abc.abstractmethod
def tags(self) -> Sequence[str]:
"""
The tags for the current evaluation. You can mutate this object to add or remove tags.
"""
@abc.abstractmethod
def report_progress(self, _progress: TaskProgressEvent) -> None:
"""
Report progress that will show up in the playground.
"""
...
@abc.abstractmethod
def meta(self, **info: Any) -> None:
"""
DEPRECATED: Use the metadata field on the hook directly.
Adds metadata to the evaluation. This metadata will be logged to the Braintrust. You can pass in metadaa
as keyword arguments, e.g. `hooks.meta(foo="bar")`.
"""
...
@property
@abc.abstractmethod
def parameters(self) -> ValidatedParameters | None:
"""
The parameters for the current evaluation. These are the validated parameter values
that were passed to the evaluator.
"""
class EvalScorerArgs(SerializableDataClass, Generic[Input, Output]):
"""
Arguments passed to an evaluator scorer. This includes the input, expected output, actual output, and metadata.
"""
input: Input
output: Output
expected: Output | None = None
metadata: Metadata | None = None
OneOrMoreScores = Union[float, int, bool, None, Score, list[Score]]
# Synchronous scorer interface - implements callable
class SyncScorerLike(Protocol, Generic[Input, Output]):
"""
Protocol for synchronous scorers that implement the callable interface.
This is the most common interface and is used when no async version is available.
"""
def __call__(
self, input: Input, output: Output, expected: Output | None = None, **kwargs: Any
) -> OneOrMoreScores: ...
# Asynchronous scorer interface
class AsyncScorerLike(Protocol, Generic[Input, Output]):
"""
Protocol for asynchronous scorers that implement the eval_async interface.
The framework will prefer this interface if available.
"""
async def eval_async(self, output: Output, expected: Output | None = None, **kwargs: Any) -> OneOrMoreScores: ...
# Union type for any kind of scorer (for typing)
ScorerLike = Union[SyncScorerLike[Input, Output], AsyncScorerLike[Input, Output]]
EvalScorer = Union[
ScorerLike[Input, Output],
type[ScorerLike[Input, Output]],
Callable[[Input, Output, Output], OneOrMoreScores],
Callable[[Input, Output, Output], Awaitable[OneOrMoreScores]],
]
@dataclasses.dataclass
class BaseExperiment:
"""
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).
"""
name: str | None = None
"""
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).
"""
_AnyEvalCase = Union[
EvalCase[Input, Output],
_EvalCaseDict[Input, Output],
_EvalCaseDictNoOutput[Input],
_ExperimentDatasetEvent,
]
_EvalDataObject = Union[
Iterable[_AnyEvalCase[Input, Output]],
Iterator[_AnyEvalCase[Input, Output]],
Awaitable[Iterator[_AnyEvalCase[Input, Output]]],
Callable[[], Union[Iterator[_AnyEvalCase[Input, Output]], Awaitable[Iterator[_AnyEvalCase[Input, Output]]]]],
BaseExperiment,
]
EvalData = Union[_EvalDataObject[Input, Output], type[_EvalDataObject[Input, Output]], Dataset]
EvalTask = Union[
Callable[[Input], Union[Output, Awaitable[Output]]],
Callable[[Input, EvalHooks[Output]], Union[Output, Awaitable[Output]]],
]
ErrorScoreHandler = Callable[[Span, EvalCase[Input, Output], list[str]], Optional[dict[str, float]]]
@dataclasses.dataclass
class Evaluator(Generic[Input, Output]):
"""
An evaluator is an abstraction that defines an evaluation dataset, a task to run on the dataset, and a set of
scorers to evaluate the results of the task. Each method attribute can be synchronous or asynchronous (for
optimal performance, it is recommended to provide asynchronous implementations).
You should not create Evaluators directly if you plan to use the Braintrust eval framework. Instead, you should
create them using the `Eval()` method, which will register them so that `braintrust eval ...` can find them.
"""
project_name: str
"""
The name of the project the eval falls under.
"""
eval_name: str
"""
A name that describes the experiment. You do not need to change it each time the experiment runs.
"""
data: EvalData[Input, Output]
"""
Returns an iterator over the evaluation dataset. Each element of the iterator should be an `EvalCase` or a dict
with the same fields as an `EvalCase` (`input`, `expected`, `metadata`).
"""
task: EvalTask[Input, Output]
"""
Runs the evaluation task on a single input. The `hooks` object can be used to add metadata to the evaluation.
"""
scores: list[EvalScorer[Input, Output]]
"""
A list of scorers to evaluate the results of the task. Each scorer can be a Scorer object or a function
that takes `input`, `output`, and `expected` arguments and returns a `Score` object. The function can be async.
"""
experiment_name: str | None
"""
Optional experiment name. If not specified, a name will be generated automatically.
"""
metadata: Metadata | None
"""
A dictionary with additional data about the test example, model outputs, or just about anything else that's
relevant, that you can use to help find and analyze examples later. For example, you could log the `prompt`,
example's `id`, or anything else that would be useful to slice/dice later. The values in `metadata` can be any
JSON-serializable type, but its keys must be strings.
"""
tags: list[str] | None = None
"""
Optional list of tags for the experiment
"""
trial_count: int = 1
"""
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.
"""
is_public: bool = False
"""
Whether the experiment should be public. Defaults to false.
"""
update: bool = False
"""
Whether to update an existing experiment with `experiment_name` if one exists. Defaults to false.
"""
timeout: float | None = None
"""
The duration, in seconds, after which to time out the evaluation.
Defaults to None, in which case there is no timeout.
"""
max_concurrency: int | None = None
"""
The maximum number of tasks/scorers that will be run concurrently.
Defaults to None, in which case there is no max concurrency.
"""
project_id: str | None = None
"""
If specified, uses the given project ID instead of the evaluator's name to identify the project.
"""
base_experiment_name: str | None = None
"""
An optional experiment name to use as a base. If specified, the new experiment will be summarized and
compared to this experiment.
"""
base_experiment_id: str | None = None
"""
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 `base_experiment_name` if specified.
"""
git_metadata_settings: GitMetadataSettings | None = None
"""
Optional settings for collecting git metadata. By default, will collect all
git metadata fields allowed in org-level settings.
"""
repo_info: RepoInfo | None = None
"""
Optionally explicitly specify the git metadata for this experiment. This
takes precedence over `git_metadata_settings` if specified.
"""
error_score_handler: ErrorScoreHandler | None = None
"""
Optionally supply a custom function to specifically handle score values when tasks or scoring functions have errored.
A default implementation is exported as `default_error_score_handler` which will log a 0 score to the root span for any scorer that was not run.
"""
description: str | None = None
"""
An optional description for the experiment.
"""
summarize_scores: bool = True
"""
Whether to summarize the scores of the experiment after it has run.
"""
parameters: EvalParameters | RemoteEvalParameters | None = None
"""
A set of parameters that will be passed to the evaluator.
Can be used to define prompts or other configurable values.
"""
parameter_values: dict[str, Any] | None = None
@dataclasses.dataclass
class EvalResultWithSummary(SerializableDataClass, Generic[Input, Output]):
summary: ExperimentSummary
results: list[EvalResult[Input, Output]]
def _repr_pretty_(self, p, _cycle):
p.text(f'EvalResultWithSummary(summary="...", results=[...])')
EvalReport = TypeVar("EvalReport")
async def await_or_run(event_loop, f, *args, **kwargs):
if bt_iscoroutinefunction(f):
return await f(*args, **kwargs)
else:
def run_f(args, kwargs, ctx):
tokens = [(var, var.set(value)) for var, value in ctx.items()]
try:
return f(*args, **kwargs)
finally:
for var, tok in tokens:
var.reset(tok)
with _THREAD_POOL_SINGLETON.get() as thread_pool:
return await event_loop.run_in_executor(
thread_pool.thread_pool(), run_f, args, kwargs, contextvars.copy_context()
)
def _call_user_fn_args(fn, kwargs):
try:
signature = inspect.signature(fn)
except:
return [], kwargs
accepts_kwargs = any(p.kind == inspect.Parameter.VAR_KEYWORD for p in signature.parameters.values())
positional_args = []
final_kwargs = {}
for name, param in signature.parameters.items():
# VAR_POSITIONAL is *args
# VAR_KEYWORD is **kwargs
# We don't want to use eithers' name
if param.kind == inspect.Parameter.VAR_POSITIONAL or param.kind == inspect.Parameter.VAR_KEYWORD:
continue
if name in kwargs:
final_kwargs[name] = kwargs.pop(name)
else:
next_arg = list(kwargs.keys())[0]
final_kwargs[name] = kwargs.pop(next_arg)
if accepts_kwargs:
final_kwargs.update(kwargs)
return positional_args, final_kwargs
async def call_user_fn(event_loop, fn, **kwargs):
positional_args, final_kwargs = _call_user_fn_args(fn, kwargs)
return await await_or_run(event_loop, fn, *positional_args, **final_kwargs)
@dataclasses.dataclass
class ReporterDef(SerializableDataClass, Generic[Input, Output, EvalReport]):
"""
A reporter takes an evaluator and its result and returns a report.
"""
name: str
"""
The name of the reporter.
"""
report_eval: Callable[
[Evaluator[Input, Output], EvalResultWithSummary[Input, Output], bool, bool],
EvalReport | Awaitable[EvalReport],
]
"""
A function that takes an evaluator and its result and returns a report.
"""
report_run: Callable[[list[EvalReport], bool, bool], bool | Awaitable[bool]]
"""
A function that takes all evaluator results and returns a boolean indicating whether the run was successful.
If you return false, the `braintrust eval` command will exit with a non-zero status code.
"""
async def _call_report_eval(
self,
evaluator: Evaluator[Input, Output],
result: EvalResultWithSummary[Input, Output],
verbose: bool,
jsonl: bool,
) -> EvalReport | Awaitable[EvalReport]:
event_loop = asyncio.get_event_loop()
return await call_user_fn(
event_loop, self.report_eval, evaluator=evaluator, result=result, verbose=verbose, jsonl=jsonl
)
async def _call_report_run(self, results: list[EvalReport], verbose: bool, jsonl: bool) -> bool | Awaitable[bool]:
event_loop = asyncio.get_event_loop()
return await call_user_fn(event_loop, self.report_run, results=results, verbose=verbose, jsonl=jsonl)
@dataclasses.dataclass
class EvaluatorInstance(SerializableDataClass, Generic[Input, Output, EvalReport]):
evaluator: Evaluator[Input, Output]
reporter: ReporterDef[Input, Output, EvalReport] | str | None
@dataclasses.dataclass
class EvaluatorFile(SerializableDataClass):
evaluators: dict[str, EvaluatorInstance] = dataclasses.field(default_factory=dict)
reporters: dict[str, ReporterDef] = dataclasses.field(default_factory=dict)
def clear(self):
self.evaluators.clear()
self.reporters.clear()
def copy(self):
return EvaluatorFile(
evaluators={k: v for k, v in self.evaluators.items()},
reporters={k: v for k, v in self.reporters.items()},
)
_evals = EvaluatorFile()
_lazy_load = False
@contextmanager
def _set_lazy_load(lazy_load: bool):
global _lazy_load
current = _lazy_load
try:
_lazy_load = lazy_load
yield
finally:
_lazy_load = current
def _is_lazy_load():
return _lazy_load
def pluralize(n, singular, plural):
if n == 1:
return singular
else:
return plural
def report_failures(evaluator: Evaluator, failing_results: Iterable[EvalResult], verbose: bool, jsonl: bool) -> None:
eprint(
f"{bcolors.FAIL}Evaluator {evaluator.eval_name} failed with {len(failing_results)} {pluralize(len(failing_results), 'error', 'errors')}{bcolors.ENDC}"
)
errors = [
(
result.exc_info
if verbose or jsonl
else "\n".join(traceback.format_exception_only(type(result.error), result.error))
)
for result in failing_results
]
if jsonl:
print(json.dumps({"eval_name": evaluator.eval_name, "errors": errors}))
else:
info = "".join(errors).rstrip()
eprint(f"{bcolors.FAIL}{info}{bcolors.ENDC}")
eprint(f"{bcolors.FAIL}Add --verbose to see full stack traces.{bcolors.ENDC}")
def report_evaluator_result(evaluator: Evaluator, result: EvalResultWithSummary, verbose: bool, jsonl: bool) -> bool:
results = result.results
summary = result.summary
failing_results = [x for x in results if x.error]
if len(failing_results) > 0:
report_failures(evaluator, failing_results, verbose=verbose, jsonl=jsonl)
else:
print(json.dumps(summary.as_dict()) if jsonl else f"{summary}")
return len(failing_results) == 0
default_reporter = ReporterDef(
name="default",
report_eval=report_evaluator_result,
report_run=lambda results, verbose, jsonl: all(x for x in results),
)
def _make_eval_name(name: str, experiment_name: str | None):
out = name
if experiment_name is not None:
out += f" [experiment_name={experiment_name}]"
return out
def _EvalCommon(
name: str,
data: EvalData[Input, Output],
task: EvalTask[Input, Output],
scores: Sequence[EvalScorer[Input, Output]],
experiment_name: str | None,
trial_count: int,
metadata: Metadata | None,
tags: list[str] | None,
is_public: bool,
update: bool,
reporter: ReporterDef[Input, Output, EvalReport] | None,
timeout: float | None,
max_concurrency: int | None,
project_id: str | None,
base_experiment_name: str | None,
base_experiment_id: str | None,
git_metadata_settings: GitMetadataSettings | None,
repo_info: RepoInfo | None,
description: str | None,
summarize_scores: bool,
no_send_logs: bool,
error_score_handler: ErrorScoreHandler | None = None,
parameters: EvalParameters | RemoteEvalParameters | None = None,
on_start: Callable[[ExperimentSummary], None] | None = None,
stream: Callable[[SSEProgressEvent], None] | None = None,
parent: str | None = None,
state: BraintrustState | None = None,
enable_cache: bool = True,
) -> Callable[[], Coroutine[Any, Any, EvalResultWithSummary[Input, Output]]]:
"""
This helper is needed because in case of `_lazy_load`, we need to update
the `_evals` global immediately instead of whenever the coroutine is
awaited.
"""
eval_name = _make_eval_name(name, experiment_name)
global _evals
if eval_name in _evals.evaluators:
eval_name = f"{eval_name}_{len(_evals.evaluators)}"
evaluator = Evaluator(
eval_name=eval_name,
project_name=name,
data=data,
task=task,
scores=scores,
experiment_name=experiment_name,
trial_count=trial_count,
metadata=metadata,
tags=tags,
is_public=is_public,
update=update,
timeout=timeout,
max_concurrency=max_concurrency,
project_id=project_id,
base_experiment_name=base_experiment_name,
base_experiment_id=base_experiment_id,
git_metadata_settings=git_metadata_settings,
repo_info=repo_info,
error_score_handler=error_score_handler,
description=description,
summarize_scores=summarize_scores,
parameters=parameters,
)
if _lazy_load:
_evals.evaluators[eval_name] = EvaluatorInstance(evaluator=evaluator, reporter=reporter)
# Better to return this empty object than have an annoying-to-use signature.
async def make_empty_summary():
return EvalResultWithSummary(summary=build_local_summary(evaluator, []), results=[])
return make_empty_summary
else:
if isinstance(reporter, str):
raise ValueError(
"Must specify a reporter object, not a name. Can only specify reporter names when running 'braintrust eval'"
)
reporter = reporter or default_reporter
if base_experiment_name is None and isinstance(evaluator.data, BaseExperiment):
base_experiment_name = evaluator.data.name
dataset = None
if isinstance(evaluator.data, Dataset):
dataset = evaluator.data
experiment_parameters = None
if isinstance(evaluator.parameters, RemoteEvalParameters) and evaluator.parameters.id is not None:
experiment_parameters = {"id": evaluator.parameters.id}
if evaluator.parameters.version is not None:
experiment_parameters["version"] = evaluator.parameters.version
# NOTE: This code is duplicated with run_evaluator_task in py/src/braintrust/cli/eval.py.
# Make sure to update those arguments if you change this.
experiment = None
if not no_send_logs and parent is None:
experiment = init_experiment(
project_name=evaluator.project_name if evaluator.project_id is None else None,
project_id=evaluator.project_id,
experiment_name=evaluator.experiment_name,
description=evaluator.description,
metadata=evaluator.metadata,
tags=evaluator.tags,
is_public=evaluator.is_public,
update=evaluator.update,
base_experiment=base_experiment_name,
base_experiment_id=base_experiment_id,
git_metadata_settings=evaluator.git_metadata_settings,
repo_info=evaluator.repo_info,
dataset=dataset,
parameters=experiment_parameters,
state=state,
)
if on_start:
summary = experiment.summarize(summarize_scores=False)
on_start(summary)
async def run_to_completion():
with parent_context(parent, state):
try:
ret = await run_evaluator(experiment, evaluator, 0, [], stream, state, enable_cache)
reporter.report_eval(evaluator, ret, verbose=True, jsonl=False)
return ret
finally:
if experiment:
experiment.flush()
elif state is not None:
state.flush()
return run_to_completion
async def EvalAsync(
name: str,
data: EvalData[Input, Output],
task: EvalTask[Input, Output],
scores: Sequence[EvalScorer[Input, Output]],
experiment_name: str | None = None,
trial_count: int = 1,
metadata: Metadata | None = None,
tags: list[str] | None = None,
is_public: bool = False,
update: bool = False,
reporter: ReporterDef[Input, Output, EvalReport] | None = None,
timeout: float | None = None,
max_concurrency: int | None = None,
project_id: str | None = None,
base_experiment_name: str | None = None,
base_experiment_id: str | None = None,
git_metadata_settings: GitMetadataSettings | None = None,
repo_info: RepoInfo | None = None,
error_score_handler: ErrorScoreHandler | None = None,
description: str | None = None,
summarize_scores: bool = True,
no_send_logs: bool = False,
parameters: EvalParameters | RemoteEvalParameters | None = None,
on_start: Callable[[ExperimentSummary], None] | None = None,
stream: Callable[[SSEProgressEvent], None] | None = None,
parent: str | None = None,
state: BraintrustState | None = None,
enable_cache: bool = True,
) -> EvalResultWithSummary[Input, Output]:
"""
A function you can use to define an evaluator. This is a convenience wrapper around the `Evaluator` class.
Use this function over `Eval()` when you are running in an async context, including in a Jupyter notebook.
Example:
```python
await EvalAsync(
name="my-evaluator",
data=lambda: [
EvalCase(input=1, expected=2),
EvalCase(input=2, expected=4),
],
task=lambda input, hooks: input * 2,
scores=[
NumericDiff,
],
)
```
:param name: The name of the evaluator. This corresponds to a project name in Braintrust.
:param data: Returns an iterator over the evaluation dataset. Each element of the iterator should be a `EvalCase`.
:param task: Runs the evaluation task on a single input. The `hooks` object can be used to add metadata to the evaluation.
:param scores: A list of scorers to evaluate the results of the task. Each scorer can be a Scorer object or a function
that takes `(input, output, expected)` arguments and returns a `Score` object.
:param experiment_name: (Optional) Experiment name. If not specified, a name will be generated automatically.
:param trial_count: 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.
:param metadata: (Optional) A dictionary with additional data about the test example, model outputs, or just about
anything else that's relevant, that you can use to help find and analyze examples later. For example, you could log
the `prompt`, example's `id`, or anything else that would be useful to slice/dice later. The values in `metadata`
can be any JSON-serializable type, but its keys must be strings.
:param tags: (Optional) A list of tags to associate with the experiment.
:param is_public: (Optional) Whether the experiment should be public. Defaults to false.
:param reporter: (Optional) A reporter that takes an evaluator and its result and returns a report.
:param timeout: (Optional) The duration, in seconds, after which to time out the evaluation.
Defaults to None, in which case there is no timeout.
:param project_id: (Optional) If specified, uses the given project ID instead of the evaluator's name to identify the project.
:param base_experiment_name: An optional experiment name to use as a base. If specified, the new experiment will be
summarized and compared to this experiment.
:param base_experiment_id: 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 `base_experiment_name` if specified.
:param git_metadata_settings: Optional settings for collecting git metadata. By default, will collect all git metadata fields allowed in org-level settings.
:param repo_info: Optionally explicitly specify the git metadata for this experiment. This takes precedence over `git_metadata_settings` if specified.
:param error_score_handler: Optionally supply a custom function to specifically handle score values when tasks or scoring functions have errored.
:param description: An optional description for the experiment.
:param summarize_scores: Whether to summarize the scores of the experiment after it has run.
:param no_send_logs: 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.
:param parameters: A set of parameters that will be passed to the evaluator.
:param on_start: An optional callback that will be called when the evaluation starts. It receives the
`ExperimentSummary` object, which can be used to display metadata about the experiment.
:param stream: A function that will be called with progress events, which can be used to
display intermediate progress.
:param parent: If specified, instead of creating a new experiment object, the Eval() will populate
the object or span specified by this parent.
:param state: Optional BraintrustState to use for the evaluation. If not specified, the global login state will be used.
:param enable_cache: Whether to enable the span cache for this evaluation. Defaults to True. The span cache stores
span data on disk to minimize memory usage and allow scorers to read spans without server round-trips.
:return: An `EvalResultWithSummary` object, which contains all results and a summary.
"""
f = _EvalCommon(
name=name,
data=data,
task=task,
scores=scores,
experiment_name=experiment_name,
trial_count=trial_count,
metadata=metadata,
tags=tags,
is_public=is_public,
update=update,
reporter=reporter,
timeout=timeout,
max_concurrency=max_concurrency,
project_id=project_id,
base_experiment_name=base_experiment_name,
base_experiment_id=base_experiment_id,
git_metadata_settings=git_metadata_settings,
repo_info=repo_info,
description=description,
summarize_scores=summarize_scores,
no_send_logs=no_send_logs,
parameters=parameters,
on_start=on_start,
stream=stream,
parent=parent,
state=state,
enable_cache=enable_cache,
)
return await f()
_has_printed_eval_async_warning = False
def Eval(
name: str,
data: EvalData[Input, Output],
task: EvalTask[Input, Output],
scores: Sequence[EvalScorer[Input, Output]],
experiment_name: str | None = None,
trial_count: int = 1,
metadata: Metadata | None = None,
tags: list[str] | None = None,
is_public: bool = False,
update: bool = False,
reporter: ReporterDef[Input, Output, EvalReport] | None = None,
timeout: float | None = None,
max_concurrency: int | None = None,
project_id: str | None = None,
base_experiment_name: str | None = None,
base_experiment_id: str | None = None,
git_metadata_settings: GitMetadataSettings | None = None,
repo_info: RepoInfo | None = None,
error_score_handler: ErrorScoreHandler | None = None,
description: str | None = None,
summarize_scores: bool = True,
no_send_logs: bool = False,
parameters: EvalParameters | RemoteEvalParameters | None = None,
on_start: Callable[[ExperimentSummary], None] | None = None,
stream: Callable[[SSEProgressEvent], None] | None = None,
parent: str | None = None,
state: BraintrustState | None = None,
enable_cache: bool = True,
) -> EvalResultWithSummary[Input, Output]:
"""
A function you can use to define an evaluator. This is a convenience wrapper around the `Evaluator` class.
For callers running in an async context, use `EvalAsync()` instead.
Example:
```python
Eval(
name="my-evaluator",
data=lambda: [
EvalCase(input=1, expected=2),
EvalCase(input=2, expected=4),
],
task=lambda input, hooks: input * 2,
scores=[
NumericDiff,
],
)
```
:param name: The name of the evaluator. This corresponds to a project name in Braintrust.
:param data: Returns an iterator over the evaluation dataset. Each element of the iterator should be a `EvalCase`.
:param task: Runs the evaluation task on a single input. The `hooks` object can be used to add metadata to the evaluation.
:param scores: A list of scorers to evaluate the results of the task. Each scorer can be a Scorer object or a function
that takes `(input, output, expected)` arguments and returns a `Score` object.
:param experiment_name: (Optional) Experiment name. If not specified, a name will be generated automatically.
:param trial_count: 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.
:param metadata: (Optional) A dictionary with additional data about the test example, model outputs, or just about
anything else that's relevant, that you can use to help find and analyze examples later. For example, you could log
the `prompt`, example's `id`, or anything else that would be useful to slice/dice later. The values in `metadata`
can be any JSON-serializable type, but its keys must be strings.
:param tags: (Optional) A list of tags to associate with the experiment.
:param is_public: (Optional) Whether the experiment should be public. Defaults to false.
:param reporter: (Optional) A reporter that takes an evaluator and its result and returns a report.
:param timeout: (Optional) The duration, in seconds, after which to time out the evaluation.
Defaults to None, in which case there is no timeout.
:param project_id: (Optional) If specified, uses the given project ID instead of the evaluator's name to identify the project.
:param base_experiment_name: An optional experiment name to use as a base. If specified, the new experiment will be
summarized and compared to this experiment.
:param base_experiment_id: 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 `base_experiment_name` if specified.
:param git_metadata_settings: Optional settings for collecting git metadata. By default, will collect all git metadata fields allowed in org-level settings.
:param repo_info: Optionally explicitly specify the git metadata for this experiment. This takes precedence over `git_metadata_settings` if specified.
:param error_score_handler: Optionally supply a custom function to specifically handle score values when tasks or scoring functions have errored.