-
Notifications
You must be signed in to change notification settings - Fork 368
Expand file tree
/
Copy patheval_api.py
More file actions
1603 lines (1405 loc) · 61.4 KB
/
eval_api.py
File metadata and controls
1603 lines (1405 loc) · 61.4 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 contextlib
import json
from collections import defaultdict
from typing import Annotated, Any, Dict, List, Set, Tuple
from fastapi import FastAPI, HTTPException, Path, Query, Request
from fastapi.responses import StreamingResponse
from kiln_ai.adapters.eval.eval_runner import EvalRunner
from kiln_ai.adapters.fine_tune.finetune_run_config_id import (
finetune_from_finetune_run_config_id,
finetune_run_config_id,
)
from kiln_ai.adapters.ml_model_list import ModelProviderName
from kiln_ai.adapters.prompt_builders import prompt_builder_from_id
from kiln_ai.datamodel import BasePrompt, Task, TaskRun
from kiln_ai.datamodel.basemodel import ID_TYPE
from kiln_ai.datamodel.dataset_filters import DatasetFilterId, dataset_filter_from_id
from kiln_ai.datamodel.eval import (
Eval,
EvalConfig,
EvalConfigType,
EvalDataType,
EvalOutputScore,
EvalRun,
EvalTemplateId,
)
from kiln_ai.datamodel.json_schema import string_to_json_key
from kiln_ai.datamodel.prompt_id import is_frozen_prompt
from kiln_ai.datamodel.run_config import KilnAgentRunConfigProperties
from kiln_ai.datamodel.spec import SpecStatus
from kiln_ai.datamodel.task import RunConfigProperties, TaskRunConfig
from kiln_ai.datamodel.task_output import normalize_rating
from kiln_ai.utils.name_generator import generate_memorable_name
from kiln_server.git_sync_decorators import build_save_context, no_write_lock
from kiln_server.sse import stream_with_heartbeat
from kiln_server.task_api import task_from_id
from kiln_server.utils.agent_checks.policy import (
ALLOW_AGENT,
DENY_AGENT,
agent_policy_require_approval,
)
from pydantic import BaseModel, Field
from .correlation_calculator import (
CorrelationCalculator,
CorrelationResult,
CorrelationScore,
)
def eval_from_id(project_id: str, task_id: str, eval_id: str) -> Eval:
task = task_from_id(project_id, task_id)
eval = Eval.from_id_and_parent_path(eval_id, task.path)
if eval is not None:
return eval
raise HTTPException(
status_code=404,
detail=f"Eval not found. ID: {eval_id}",
)
def eval_config_from_id(
project_id: str, task_id: str, eval_id: str, eval_config_id: str
) -> EvalConfig:
eval = eval_from_id(project_id, task_id, eval_id)
for config in eval.configs():
if config.id == eval_config_id:
return config
raise HTTPException(
status_code=404,
detail=f"Eval config not found. ID: {eval_config_id}",
)
def get_all_run_configs(project_id: str, task_id: str) -> list[TaskRunConfig]:
"""
Returns all run configs for a task, including completed fine-tune run configs.
Only includes fine-tunes that have a fine_tune_model_id (are completed and usable).
"""
task = task_from_id(project_id, task_id)
configs = task.run_configs()
# Get run configs from finetunes and only include completed fine-tunes
finetunes = task.finetunes()
for finetune in finetunes:
if finetune.run_config is not None and finetune.fine_tune_model_id is not None:
configs.append(
TaskRunConfig(
id=finetune_run_config_id(project_id, task_id, str(finetune.id)),
name=finetune.name,
description=finetune.description,
run_config_properties=finetune.run_config,
parent=task, # special case, we need to reference the task model
)
)
return configs
def task_run_config_from_id(
project_id: str, task_id: str, run_config_id: str
) -> TaskRunConfig:
task = task_from_id(project_id, task_id)
for run_config in task.run_configs():
if run_config.id == run_config_id:
return run_config
# special case for finetune run configs, it's inside the finetune model
if run_config_id.startswith("finetune_run_config::"):
finetune = finetune_from_finetune_run_config_id(run_config_id)
if finetune.run_config is not None:
return TaskRunConfig(
id=finetune_run_config_id(project_id, task_id, str(finetune.id)),
name=finetune.name,
description=finetune.description,
run_config_properties=finetune.run_config,
parent=task, # special case, we need to reference the task model
)
raise HTTPException(
status_code=404,
detail=f"Task run config not found. ID: {run_config_id}",
)
def _format_progress_sse(progress) -> str:
data = {
"progress": progress.complete,
"total": progress.total,
"errors": progress.errors,
}
return f"data: {json.dumps(data)}\n\n"
async def run_eval_runner_with_status(
eval_runner: EvalRunner, request: Request
) -> StreamingResponse:
# Yields async messages designed to be used with server sent events (SSE)
# https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events
async def event_generator():
# aclosing ensures prompt cleanup: when event_generator is cancelled
# (client disconnect → Starlette aclose's the body iterator → GeneratorExit
# here), hb.aclose() fires, which runs stream_with_heartbeat's finally,
# which aclose's the runner, which runs AsyncJobRunner's finally and
# cancels its workers.
hb = stream_with_heartbeat(
eval_runner.run(),
_format_progress_sse,
is_disconnected=request.is_disconnected,
)
async with contextlib.aclosing(hb) as stream:
async for chunk in stream:
yield chunk
if not await request.is_disconnected():
# Send the final complete message the app expects, and uses to stop listening
yield "data: complete\n\n"
return StreamingResponse(
content=event_generator(),
media_type="text/event-stream",
)
class CreateEvaluatorRequest(BaseModel):
"""Request to create a new evaluator."""
name: str = Field(description="The name of the evaluator.")
description: str | None = Field(
default=None, description="The description of the evaluator."
)
template: EvalTemplateId | None = Field(
default=None, description="The eval template to use."
)
output_scores: list[EvalOutputScore] = Field(
description="The scores this evaluator should produce."
)
eval_set_filter_id: DatasetFilterId = Field(
description="The dataset filter for the eval set."
)
eval_configs_filter_id: DatasetFilterId | None = Field(
default=None, description="The dataset filter for comparing eval configs."
)
template_properties: dict[str, str | float | int | bool] | None = Field(
default=None, description="Template-specific properties."
)
evaluation_data_type: EvalDataType = Field(
description="The type of task output to evaluate."
)
class CreateEvalConfigRequest(BaseModel):
"""Request to create a new eval configuration."""
name: str | None = Field(default=None, description="The name of the eval config.")
type: EvalConfigType = Field(description="The type of eval config.")
properties: dict[str, Any] = Field(
description="Properties for the eval config, specific to the type."
)
model_name: str = Field(description="The model to use for evaluation.")
provider: ModelProviderName = Field(
description="The provider of the evaluation model."
)
class CreateTaskRunConfigRequest(BaseModel):
"""Request to create a new run config for eval."""
name: str | None = Field(default=None, description="The name of the run config.")
description: str | None = Field(
default=None, description="The description of the run config."
)
run_config_properties: RunConfigProperties = Field(
description="The run configuration properties."
)
class UpdateRunConfigRequest(BaseModel):
"""Request to update a run config."""
name: str | None = Field(default=None, description="The updated name.")
starred: bool | None = Field(
default=None, description="The updated starred status."
)
prompt_name: str | None = Field(
default=None, description="The updated prompt name."
)
class RunEvalConfigRequest(BaseModel):
"""Request to run an eval with specific run configs."""
run_config_ids: list[str] = Field(description="The run config IDs to evaluate.")
class ScoreSummary(BaseModel):
"""Summary of scores for an eval run."""
mean_score: float = Field(description="The mean score across all runs.")
class MeanUsage(BaseModel):
"""Average token usage across eval runs."""
mean_input_tokens: float | None = Field(
default=None, description="Average input tokens per run."
)
mean_output_tokens: float | None = Field(
default=None, description="Average output tokens per run."
)
mean_total_tokens: float | None = Field(
default=None, description="Average total tokens per run."
)
mean_cost: float | None = Field(
default=None, description="Average cost per run in USD."
)
class EvalRunResult(BaseModel):
"""Results of an eval run including the eval and run config."""
results: List[EvalRun] = Field(description="The individual eval run results.")
eval: Eval = Field(description="The parent eval.")
eval_config: EvalConfig = Field(description="The eval config used.")
run_config: TaskRunConfig = Field(description="The run config used.")
class UpdateFavouriteRequest(BaseModel):
"""Request to update the favourite status of an eval."""
favourite: bool = Field(description="Whether the eval is a favourite.")
class UpdateEvalRequest(BaseModel):
"""Request to update an eval."""
name: str | None = Field(default=None, description="The updated name.")
description: str | None = Field(
default=None, description="The updated description."
)
train_set_filter_id: str | None = Field(
default=None, description="The updated train set filter ID."
)
class EvalProgress(BaseModel):
"""Progress information for an eval."""
dataset_size: int = Field(description="The total size of the eval dataset.")
golden_dataset_size: int = Field(
description="The total size of the golden dataset."
)
golden_dataset_not_rated_count: int = Field(
description="Number of unrated golden dataset items."
)
golden_dataset_partially_rated_count: int = Field(
description="Number of partially rated golden dataset items."
)
golden_dataset_fully_rated_count: int = Field(
description="Number of fully rated golden dataset items."
)
train_dataset_size: int = Field(description="The total size of the train dataset.")
current_eval_method: EvalConfig | None = Field(
default=None, description="The currently selected eval config."
)
class EvalResultSummary(BaseModel):
"""Summary of eval results across run configs."""
results: Dict[ID_TYPE, Dict[str, ScoreSummary]] = Field(
description="Scores keyed by run_config_id then output_score_id."
)
run_config_percent_complete: Dict[ID_TYPE, float] = Field(
description="Percent of dataset processed per run config."
)
dataset_size: int = Field(description="Total size of the eval dataset.")
class EvalResultsSummaryEvalInfo(BaseModel):
"""Metadata for a single eval within eval results summary."""
name: str = Field(description="The eval name.")
default_judge_config_id: ID_TYPE | None = Field(
description="The default judge config ID for this eval, if any."
)
dataset_size: int = Field(description="Total size of the eval dataset.")
output_score_keys: list[str] = Field(
description="The output score keys for this eval."
)
class EvalResultsSummaryRunConfigInfo(BaseModel):
"""Metadata for a run config within eval results summary."""
name: str = Field(description="The run config name.")
class EvalResultsSummaryResultCell(BaseModel):
"""Results for a single (eval, run_config) cell."""
mean_scores: Dict[str, float] = Field(
description="Mean scores keyed by output_score_key."
)
percent_complete: float = Field(
description="Percent of dataset processed for this run config."
)
class EvalResultsSummaryResponse(BaseModel):
"""Aggregated eval results across all evals for a task."""
evals_by_id: Dict[ID_TYPE, EvalResultsSummaryEvalInfo] = Field(
description="Eval metadata keyed by eval ID."
)
run_configs_by_id: Dict[ID_TYPE, EvalResultsSummaryRunConfigInfo] = Field(
description="Run config metadata keyed by run config ID."
)
scores_by_run_config_by_eval: Dict[
ID_TYPE, Dict[ID_TYPE, EvalResultsSummaryResultCell]
] = Field(description="Results keyed by run config ID then eval ID.")
class EvalConfigCompareSummary(BaseModel):
"""Summary comparing eval configs against human ratings."""
results: Dict[ID_TYPE, Dict[str, CorrelationResult]] = Field(
description="Correlation results keyed by eval_config_id then output_score_id."
)
eval_config_percent_complete: Dict[ID_TYPE, float] = Field(
description="Percent of dataset processed per eval config."
)
dataset_size: int = Field(
description="Total size of the eval config comparison dataset."
)
fully_rated_count: int = Field(description="Number of fully rated dataset items.")
partially_rated_count: int = Field(
description="Number of partially rated dataset items."
)
not_rated_count: int = Field(description="Number of unrated dataset items.")
class EvalConfigResult(BaseModel):
"""Results for a single eval config."""
eval_config_id: ID_TYPE = Field(description="The eval config ID.")
results: Dict[str, ScoreSummary | None] = Field(
description="Scores keyed by output_score_id. None when no data."
)
percent_complete: float = Field(description="Percent of the dataset processed.")
class RunConfigEvalResult(BaseModel):
"""Eval results for a specific run config."""
eval_id: ID_TYPE = Field(description="The unique identifier of the eval.")
eval_name: str = Field(description="The human-readable name of the eval.")
dataset_size: int = Field(description="The dataset size for this eval.")
eval_config_result: EvalConfigResult | None = Field(
default=None, description="The eval config results, if available."
)
missing_default_eval_config: bool = Field(
description="Whether the default eval config is missing."
)
spec_id: ID_TYPE | None = Field(
default=None, description="The associated spec ID, if any."
)
class RunConfigEvalScoresSummary(BaseModel):
"""Summary of all eval scores for a run config."""
eval_results: List[RunConfigEvalResult] = Field(
description="Eval results for each eval."
)
mean_usage: MeanUsage | None = Field(
default=None, description="Average usage statistics across eval runs."
)
def dataset_ids_in_filter(
task: Task, filter_id: DatasetFilterId, readonly: bool
) -> Set[ID_TYPE]:
# Fetch all the dataset items IDs in a filter
filter = dataset_filter_from_id(filter_id)
return {run.id for run in task.runs(readonly=readonly) if filter(run)}
def runs_in_filter(
task: Task, filter_id: DatasetFilterId, readonly: bool
) -> list[TaskRun]:
# Fetch all the dataset items IDs in a filter
filter = dataset_filter_from_id(filter_id)
return [run for run in task.runs(readonly=readonly) if filter(run)]
def build_score_key_to_task_requirement_id(task: Task) -> Dict[str, ID_TYPE]:
# Create a map of score_key -> Task requirement ID
score_key_to_task_requirement_id: Dict[str, ID_TYPE] = {}
for task_requirement in task.requirements:
score_key = string_to_json_key(task_requirement.name)
score_key_to_task_requirement_id[score_key] = task_requirement.id
return score_key_to_task_requirement_id
def human_score_from_task_run(
task_run: TaskRun,
score: EvalOutputScore,
score_key_to_task_requirement_id: Dict[str, ID_TYPE],
) -> float | None:
if not task_run.output.rating:
return None
score_key = score.json_key()
# Overall rating
if score_key == "overall_rating":
return task_run.output.rating.value
# Task requirement ratings
req_id = score_key_to_task_requirement_id.get(score_key, None)
if req_id:
req_rating = task_run.output.rating.requirement_ratings.get(req_id, None)
if req_rating is not None:
return req_rating.value
return None
# Named ratings
named_score_id = f"named::{score.name}"
named_rating = task_run.output.rating.requirement_ratings.get(named_score_id, None)
if named_rating is not None:
return named_rating.value
return None
def count_human_evals(
items: List[TaskRun],
eval: Eval,
score_key_to_task_requirement_id: Dict[str, ID_TYPE],
) -> Tuple[int, int, int]:
# Track how often we are missing human evals in dataset items
fully_rated_count: int = 0
partially_rated_count: int = 0
not_rated_count: int = 0
for dataset_item in items:
has_all_scores = True
has_any_scores = False
for output_score in eval.output_scores:
score = human_score_from_task_run(
dataset_item, output_score, score_key_to_task_requirement_id
)
if score is None:
has_all_scores = False
else:
has_any_scores = True
if not has_any_scores:
not_rated_count += 1
elif has_all_scores:
fully_rated_count += 1
else:
partially_rated_count += 1
return fully_rated_count, partially_rated_count, not_rated_count
def compute_score_summary(
eval: Eval,
eval_config: EvalConfig,
task_run_configs: list[TaskRunConfig],
expected_dataset_ids: set[ID_TYPE],
) -> EvalResultSummary:
if len(expected_dataset_ids) == 0:
return EvalResultSummary(
results={},
run_config_percent_complete={},
dataset_size=0,
)
remaining_expected_dataset_ids: Dict[ID_TYPE, Set[ID_TYPE]] = {
run_config.id: set(expected_dataset_ids) for run_config in task_run_configs
}
partial_incomplete_counts: Dict[ID_TYPE, int] = {
run_config.id: 0 for run_config in task_run_configs
}
total_scores: Dict[ID_TYPE, Dict[str, float]] = defaultdict(
lambda: defaultdict(float)
)
score_counts: Dict[ID_TYPE, Dict[str, int]] = defaultdict(lambda: defaultdict(int))
for eval_run in eval_config.runs(readonly=True):
if eval_run.task_run_config_id is None:
continue
run_config_id = eval_run.task_run_config_id
if run_config_id not in remaining_expected_dataset_ids:
continue
if eval_run.dataset_id not in remaining_expected_dataset_ids[run_config_id]:
continue
else:
remaining_expected_dataset_ids[run_config_id].remove(eval_run.dataset_id)
incomplete = False
# Ensure this run_config_id has an entry even if no scores match
_ = total_scores[run_config_id]
for output_score in eval.output_scores:
score_key = output_score.json_key()
if score_key in eval_run.scores:
total_scores[run_config_id][score_key] += eval_run.scores[score_key]
score_counts[run_config_id][score_key] += 1
else:
incomplete = True
if incomplete:
partial_incomplete_counts[run_config_id] += 1
results: Dict[ID_TYPE, Dict[str, ScoreSummary]] = {}
for run_config_id, output_scores in total_scores.items():
results[run_config_id] = {}
for output_score_id, score in output_scores.items():
count = score_counts[run_config_id][output_score_id]
if count > 0:
results[run_config_id][output_score_id] = ScoreSummary(
mean_score=score / count
)
run_config_percent_complete: Dict[ID_TYPE, float] = {}
for run_config in task_run_configs:
incomplete_count = partial_incomplete_counts[run_config.id] + len(
remaining_expected_dataset_ids[run_config.id]
)
percent_incomplete = incomplete_count / len(expected_dataset_ids)
run_config_percent_complete[run_config.id] = 1 - percent_incomplete
return EvalResultSummary(
results=results,
run_config_percent_complete=run_config_percent_complete,
dataset_size=len(expected_dataset_ids),
)
def connect_evals_api(app: FastAPI):
@app.post(
"/api/projects/{project_id}/tasks/{task_id}/create_evaluator",
summary="Create Evaluator",
tags=["Evals"],
openapi_extra=ALLOW_AGENT,
)
async def create_evaluator(
project_id: Annotated[
str, Path(description="The unique identifier of the project.")
],
task_id: Annotated[
str,
Path(description="The unique identifier of the task within the project."),
],
request: CreateEvaluatorRequest,
) -> Eval:
task = task_from_id(project_id, task_id)
eval = Eval(
name=request.name,
description=request.description,
template=request.template,
output_scores=request.output_scores,
eval_set_filter_id=request.eval_set_filter_id,
eval_configs_filter_id=request.eval_configs_filter_id,
template_properties=request.template_properties,
evaluation_data_type=request.evaluation_data_type,
parent=task,
)
eval.save_to_file()
return eval
@app.get(
"/api/projects/{project_id}/tasks/{task_id}/run_configs",
summary="List Run Configs",
tags=["Run Configs"],
openapi_extra=ALLOW_AGENT,
)
async def get_run_configs(
project_id: Annotated[
str, Path(description="The unique identifier of the project.")
],
task_id: Annotated[
str,
Path(description="The unique identifier of the task within the project."),
],
) -> list[TaskRunConfig]:
return get_all_run_configs(project_id, task_id)
@app.get(
"/api/projects/{project_id}/tasks/{task_id}/evals/{eval_id}",
summary="Get Eval",
tags=["Evals"],
openapi_extra=ALLOW_AGENT,
)
async def get_eval(
project_id: Annotated[
str, Path(description="The unique identifier of the project.")
],
task_id: Annotated[
str,
Path(description="The unique identifier of the task within the project."),
],
eval_id: Annotated[str, Path(description="The unique identifier of the eval.")],
) -> Eval:
return eval_from_id(project_id, task_id, eval_id)
@app.delete(
"/api/projects/{project_id}/tasks/{task_id}/evals/{eval_id}",
summary="Delete Eval",
tags=["Evals"],
openapi_extra=DENY_AGENT,
)
async def delete_eval(
project_id: Annotated[
str, Path(description="The unique identifier of the project.")
],
task_id: Annotated[
str,
Path(description="The unique identifier of the task within the project."),
],
eval_id: Annotated[str, Path(description="The unique identifier of the eval.")],
) -> None:
eval = eval_from_id(project_id, task_id, eval_id)
eval.delete()
@app.patch(
"/api/projects/{project_id}/tasks/{task_id}/evals/{eval_id}",
summary="Update Eval",
tags=["Evals"],
openapi_extra=agent_policy_require_approval(
"Allow agent to edit eval? Ensure you backup your project before allowing agentic edits."
),
)
async def update_eval(
project_id: Annotated[
str, Path(description="The unique identifier of the project.")
],
task_id: Annotated[
str,
Path(description="The unique identifier of the task within the project."),
],
eval_id: Annotated[str, Path(description="The unique identifier of the eval.")],
request: UpdateEvalRequest,
) -> Eval:
eval = eval_from_id(project_id, task_id, eval_id)
if request.name is not None:
eval.name = request.name
if request.description is not None:
eval.description = request.description
# legacy evals (not created with Specs) do not have a train set filter, but we need one
# for some features such as prompt optimization
if request.train_set_filter_id is not None:
# if the eval already has a train set filter, we do not allow changing it because it
# would make comparing results before and after the change very confusing
if eval.train_set_filter_id is not None:
raise HTTPException(
status_code=400,
detail="Train set filter is already set and cannot be changed. Please create a new eval if you need a different train set.",
)
eval.train_set_filter_id = request.train_set_filter_id
eval.save_to_file()
return eval
@app.get(
"/api/projects/{project_id}/tasks/{task_id}/evals",
summary="List Evals",
tags=["Evals"],
openapi_extra=ALLOW_AGENT,
)
async def get_evals(
project_id: Annotated[
str, Path(description="The unique identifier of the project.")
],
task_id: Annotated[
str,
Path(description="The unique identifier of the task within the project."),
],
) -> list[Eval]:
"""List all evals for a task."""
task = task_from_id(project_id, task_id)
return task.evals()
@app.get(
"/api/projects/{project_id}/tasks/{task_id}/evals/{eval_id}/eval_configs",
summary="List Eval Configs",
tags=["Evals"],
openapi_extra=ALLOW_AGENT,
)
async def get_eval_configs(
project_id: Annotated[
str, Path(description="The unique identifier of the project.")
],
task_id: Annotated[
str,
Path(description="The unique identifier of the task within the project."),
],
eval_id: Annotated[str, Path(description="The unique identifier of the eval.")],
) -> list[EvalConfig]:
eval = eval_from_id(project_id, task_id, eval_id)
return eval.configs()
@app.get(
"/api/projects/{project_id}/tasks/{task_id}/evals/{eval_id}/eval_config/{eval_config_id}",
summary="Get Eval Config",
tags=["Evals"],
openapi_extra=ALLOW_AGENT,
)
async def get_eval_config(
project_id: Annotated[
str, Path(description="The unique identifier of the project.")
],
task_id: Annotated[
str,
Path(description="The unique identifier of the task within the project."),
],
eval_id: Annotated[str, Path(description="The unique identifier of the eval.")],
eval_config_id: Annotated[
str, Path(description="The unique identifier of the eval configuration.")
],
) -> EvalConfig:
eval_config = eval_config_from_id(project_id, task_id, eval_id, eval_config_id)
return eval_config
@app.post(
"/api/projects/{project_id}/tasks/{task_id}/run_configs",
summary="Create Run Config",
tags=["Run Configs"],
openapi_extra=ALLOW_AGENT,
)
async def create_task_run_config(
project_id: Annotated[
str, Path(description="The unique identifier of the project.")
],
task_id: Annotated[
str,
Path(description="The unique identifier of the task within the project."),
],
request: CreateTaskRunConfigRequest,
) -> TaskRunConfig:
task = task_from_id(project_id, task_id)
name = request.name or generate_memorable_name()
parent_project = task.parent_project()
if parent_project is None:
raise HTTPException(
status_code=400,
detail="Task must have a parent project.",
)
frozen_prompt: BasePrompt | None = None
run_config_properties = request.run_config_properties
if isinstance(run_config_properties, KilnAgentRunConfigProperties):
prompt_id = run_config_properties.prompt_id
if not is_frozen_prompt(prompt_id):
# For dynamic prompts, we "freeze" a copy of this prompt into the task run config so we don't accidentally invalidate evals if the user changes something that impacts the prompt (example: changing data for multi-shot, or changing task for basic-prompt)
# We then point the task_run_config.run_properties.prompt_id to this new frozen prompt
prompt_builder = prompt_builder_from_id(prompt_id, task)
prompt_name = generate_memorable_name()
frozen_prompt = BasePrompt(
name=prompt_name,
description=f"Frozen copy of prompt '{prompt_id}'.",
generator_id=prompt_id,
prompt=prompt_builder.build_base_prompt(),
chain_of_thought_instructions=prompt_builder.chain_of_thought_prompt(),
)
task_run_config = TaskRunConfig(
parent=task,
name=name,
run_config_properties=run_config_properties,
description=request.description,
prompt=frozen_prompt,
)
if frozen_prompt is not None:
# Set after, because the ID isn't known until the TaskRunConfig is created
if isinstance(
task_run_config.run_config_properties, KilnAgentRunConfigProperties
):
task_run_config.run_config_properties.prompt_id = f"task_run_config::{parent_project.id}::{task.id}::{task_run_config.id}"
task_run_config.save_to_file()
return task_run_config
@app.patch(
"/api/projects/{project_id}/tasks/{task_id}/run_configs/{run_config_id}",
summary="Update Run Config",
tags=["Run Configs"],
openapi_extra=agent_policy_require_approval(
"Allow agent to edit run config? Ensure you backup your project before allowing agentic edits."
),
)
async def update_run_config(
project_id: Annotated[
str, Path(description="The unique identifier of the project.")
],
task_id: Annotated[
str,
Path(description="The unique identifier of the task within the project."),
],
run_config_id: Annotated[
str, Path(description="The unique identifier of the run configuration.")
],
request: UpdateRunConfigRequest,
) -> TaskRunConfig:
run_config = task_run_config_from_id(project_id, task_id, run_config_id)
if run_config.path is None:
raise HTTPException(
status_code=400,
detail="Cannot update this run config.",
)
if request.name is not None:
run_config.name = request.name
if request.starred is not None:
run_config.starred = request.starred
if request.prompt_name is not None:
if run_config.prompt is None:
raise HTTPException(
status_code=400,
detail="Run config has no frozen prompt to rename.",
)
run_config.prompt = run_config.prompt.model_copy(
update={"name": request.prompt_name}
)
run_config.save_to_file()
return run_config
@app.post(
"/api/projects/{project_id}/tasks/{task_id}/evals/{eval_id}/create_eval_config",
summary="Create Eval Config",
tags=["Evals"],
openapi_extra=ALLOW_AGENT,
)
async def create_eval_config(
project_id: Annotated[
str, Path(description="The unique identifier of the project.")
],
task_id: Annotated[
str,
Path(description="The unique identifier of the task within the project."),
],
eval_id: Annotated[str, Path(description="The unique identifier of the eval.")],
request: CreateEvalConfigRequest,
) -> EvalConfig:
eval = eval_from_id(project_id, task_id, eval_id)
name = request.name or generate_memorable_name()
eval_config = EvalConfig(
name=name,
config_type=request.type,
properties=request.properties,
model_name=request.model_name,
model_provider=request.provider,
parent=eval,
)
eval_config.save_to_file()
return eval_config
# JS SSE client (EventSource) doesn't work with POST requests, so we use GET, even though post would be better
@app.get(
"/api/projects/{project_id}/tasks/{task_id}/evals/{eval_id}/eval_config/{eval_config_id}/run_comparison",
summary="Run Run Config Comparison",
tags=["Evals"],
openapi_extra=agent_policy_require_approval("Run eval comparison?"),
)
@no_write_lock
async def run_eval_config(
request: Request,
project_id: Annotated[
str, Path(description="The unique identifier of the project.")
],
task_id: Annotated[
str,
Path(description="The unique identifier of the task within the project."),
],
eval_id: Annotated[str, Path(description="The unique identifier of the eval.")],
eval_config_id: Annotated[
str, Path(description="The unique identifier of the eval configuration.")
],
run_config_ids: Annotated[
list[str],
Query(description="The list of run configuration IDs to evaluate."),
] = [],
all_run_configs: Annotated[
bool,
Query(
description="Whether to evaluate all run configurations for the task."
),
] = False,
) -> StreamingResponse:
"""Run a specific eval config against one or more run configs and stream progress via SSE. Executes model runs and scores them."""
eval_config = eval_config_from_id(project_id, task_id, eval_id, eval_config_id)
# Load the list of run configs to use. Two options:
run_configs: list[TaskRunConfig] = []
if all_run_configs:
# special case, we cannot directly lod task.run_configs(), we need to also get all finetune run configs which lives inside the finetune model
run_configs = get_all_run_configs(project_id, task_id)
else:
if len(run_config_ids) == 0:
raise HTTPException(
status_code=400,
detail="No run config ids provided. At least one run config id is required.",
)
run_configs = [
task_run_config_from_id(project_id, task_id, run_config_id)
for run_config_id in run_config_ids
]
eval_runner = EvalRunner(
eval_configs=[eval_config],
run_configs=run_configs,
eval_run_type="task_run_eval",
save_context=build_save_context(request),
)
return await run_eval_runner_with_status(eval_runner, request)
@app.post(
"/api/projects/{project_id}/tasks/{task_id}/evals/{eval_id}/set_current_eval_config/{eval_config_id}",
summary="Set Default Eval Config",
tags=["Evals"],
openapi_extra=ALLOW_AGENT,
)
async def set_default_eval_config(
project_id: Annotated[
str, Path(description="The unique identifier of the project.")
],
task_id: Annotated[
str,
Path(description="The unique identifier of the task within the project."),
],
eval_id: Annotated[str, Path(description="The unique identifier of the eval.")],
eval_config_id: Annotated[
str,
Path(
description="The unique identifier of the eval configuration to set as default, or 'None' to clear the default."
),
],
) -> Eval:
eval = eval_from_id(project_id, task_id, eval_id)
if eval_config_id == "None":
eval.current_config_id = None
else:
eval_config = next(
(
eval_config
for eval_config in eval.configs()
if eval_config.id == eval_config_id
),
None,
)
if eval_config is None:
raise HTTPException(
status_code=400,