karenina.schemas.entities¶
entities
¶
Core business entity models.
This module contains the fundamental entities used throughout Karenina: - BaseAnswer: Base class for answer templates - Question: Benchmark question definition - Rubric: Rubric traits for qualitative evaluation - VerifiedField: Declarative field verification for answer templates - Primitives: Verification primitives (ExactMatch, BooleanMatch, etc.) - Composition: Strategy nodes for combining field results (AllOf, AnyOf, etc.)
Classes¶
AgenticRubricTrait
¶
Bases: BaseModel
Rubric trait evaluated by an agent with tools.
Unlike LLMRubricTrait (single LLM call), this trait launches an agent that can investigate the response and workspace using tools before producing a score. Supports boolean, score, literal, and template kinds.
When kind is a BaseModel subclass (template kind), the agent
produces structured output matching that schema instead of a scalar
score. Template kinds require higher_is_better=None because
directionality is not meaningful for structured results.
Source code in src/karenina/schemas/entities/rubric.py
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 | |
Attributes¶
is_template_kind
property
¶
Return True if kind is a BaseModel subclass (template kind).
Functions¶
serialize_kind
¶
Serialize BaseModel subclass to a template dict with JSON Schema.
Source code in src/karenina/schemas/entities/rubric.py
set_legacy_defaults
classmethod
¶
Set default for higher_is_better when loading legacy data.
Skips the legacy default (True) when kind is a template, because template kinds require higher_is_better=None.
Source code in src/karenina/schemas/entities/rubric.py
validate_higher_is_better
classmethod
¶
Enforce higher_is_better=None for template kind.
Source code in src/karenina/schemas/entities/rubric.py
validate_kind
classmethod
¶
Accept string literals, BaseModel subclasses, or serialized template dicts.
Source code in src/karenina/schemas/entities/rubric.py
validate_kind_fields
¶
validate_kind_fields() -> AgenticRubricTrait
Validate kind-specific field constraints.
Source code in src/karenina/schemas/entities/rubric.py
validate_model_override_supports_agents
¶
validate_model_override_supports_agents() -> (
AgenticRubricTrait
)
Validate that model_override supports agent creation (if set).
Source code in src/karenina/schemas/entities/rubric.py
validate_score
¶
Validate that a given score is valid for this trait.
Source code in src/karenina/schemas/entities/rubric.py
AllOf
¶
Bases: AllOf
All child conditions must pass (template domain).
Overrides conditions with the discriminated StrategyNode union so nested trees deserialize correctly.
Source code in src/karenina/schemas/entities/composition.py
AnyOf
¶
Bases: AnyOf
At least one child condition must pass (template domain).
Overrides conditions with the discriminated StrategyNode union so nested trees deserialize correctly.
Source code in src/karenina/schemas/entities/composition.py
AtLeastN
¶
Bases: AtLeastN
N or more child conditions must pass (template domain).
Overrides conditions with the discriminated StrategyNode union so nested trees deserialize correctly.
Source code in src/karenina/schemas/entities/composition.py
BaseAnswer
¶
Bases: BaseModel
Base class for all answer templates in Karenina.
This class provides common functionality and configuration for answer validation and processing.
Source code in src/karenina/schemas/entities/answer.py
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 | |
Functions¶
get_source_code
classmethod
¶
Get the source code of this Answer class.
Returns:
| Type | Description |
|---|---|
str | None
|
The source code string if available, None otherwise. |
For file-based classes, source code is captured automatically. For exec-created classes, source code must be set manually.
Source code in src/karenina/schemas/entities/answer.py
model_json_schema
classmethod
¶
Generate JSON schema with verification metadata stripped.
Overrides Pydantic's default to ensure verification metadata (containing ground truth values) is never exposed in the schema. This prevents ground truth leakage to LLM judges regardless of which adapter or code path generates the schema.
All args are forwarded to Pydantic's model_json_schema().
Source code in src/karenina/schemas/entities/answer.py
model_post_init
¶
Post-init hook for auto-generating ground truth from VerifiedField metadata.
For templates using VerifiedField, this automatically populates self.correct with {field_name: ground_truth} if not already set. Classic templates and templates with custom ground_truth() are unaffected because the bridge in init_subclass overrides this method.
Source code in src/karenina/schemas/entities/answer.py
set_question_id
¶
set_question_id(question_id: str) -> None
Set the question ID programmatically.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
question_id
¶ |
str
|
The unique identifier for the question this answer relates to. |
required |
set_source_code_from_notebook
classmethod
¶
Capture source code from notebook cell history (Jupyter/IPython only).
This is a convenience method for interactive environments where inspect.getsource() doesn't work. It attempts to find the class definition in the recent cell execution history.
Usage in notebook
class Answer(BaseAnswer): # your class definition pass Answer.set_source_code_from_notebook()
Source code in src/karenina/schemas/entities/answer.py
verify_regex
¶
verify_regex(raw_trace: str) -> dict[str, Any]
Verify regex patterns against the raw LLM response trace.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
raw_trace
¶ |
str
|
The complete raw response text from the LLM |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Dictionary containing regex validation results with keys: |
dict[str, Any]
|
|
dict[str, Any]
|
|
dict[str, Any]
|
|
Source code in src/karenina/schemas/entities/answer.py
BooleanMatch
¶
Bases: VerificationPrimitive
Compare extracted bool to ground truth bool.
Both values are coerced to bool before comparison.
Source code in src/karenina/schemas/primitives/comparisons.py
CallableRubricTrait
¶
Bases: BaseModel
Callable-based evaluation trait using custom Python functions.
This trait type serializes and stores custom Python functions using cloudpickle, enabling complex, stateful, or domain-specific validation logic that cannot be expressed as simple regex patterns.
SECURITY WARNING: Deserializing callable code can execute arbitrary Python code. Only load CallableRubricTrait instances from trusted sources. CallableRubricTrait cannot be created via the web API for security reasons.
The trait can return either boolean (pass/fail) or numeric score results, matching LLMRubricTrait behavior.
Examples:
Boolean: - Word count validation: lambda text: len(text.split()) >= 50 - Custom domain logic: checking medical terminology consistency
Score: - Readability score: lambda text: calculate_flesch_kincaid(text) - Custom metric: lambda text: compute_domain_score(text)
Source code in src/karenina/schemas/entities/rubric.py
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 | |
Functions¶
deserialize_callable
¶
Deserialize the callable function from stored bytes.
SECURITY WARNING: This executes code that was serialized and may contain arbitrary Python code. Only deserialize callables from trusted sources.
Returns:
| Type | Description |
|---|---|
Callable[[str], bool | int]
|
The deserialized callable function |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If deserialization fails |
Source code in src/karenina/schemas/entities/rubric.py
evaluate
¶
evaluate(text: str) -> bool | int
Evaluate the trait against the provided text.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text
¶ |
str
|
The text to evaluate (verification trace or answer text) |
required |
Returns:
| Type | Description |
|---|---|
bool | int
|
Boolean result for kind='boolean', numeric score for kind='score' |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If evaluation fails |
ValueError
|
If return type doesn't match kind or score is out of range |
Source code in src/karenina/schemas/entities/rubric.py
from_callable
classmethod
¶
from_callable(
name: str,
func: Callable[[str], bool | int],
kind: TraitKind,
description: str | None = None,
summary: str | None = None,
min_score: int | None = None,
max_score: int | None = None,
invert_result: bool = False,
higher_is_better: bool = True,
) -> CallableRubricTrait
Create a CallableRubricTrait from a callable function.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
¶ |
str
|
Trait name |
required |
func
¶ |
Callable[[str], bool | int]
|
Function that takes a string (the verification trace/answer text) and returns bool or int |
required |
kind
¶ |
TraitKind
|
Type of evaluation - 'boolean' or 'score' |
required |
description
¶ |
str | None
|
Optional trait description |
None
|
summary
¶ |
str | None
|
Short concept label for dynamic rubric presence check |
None
|
min_score
¶ |
int | None
|
Minimum score (required if kind='score') |
None
|
max_score
¶ |
int | None
|
Maximum score (required if kind='score') |
None
|
invert_result
¶ |
bool
|
Whether to invert boolean result (only for kind='boolean') |
False
|
higher_is_better
¶ |
bool
|
Whether higher return values indicate better performance |
True
|
Returns:
| Type | Description |
|---|---|
CallableRubricTrait
|
CallableRubricTrait instance with serialized function |
Raises:
| Type | Description |
|---|---|
ValueError
|
If function signature is invalid or score parameters are missing |
Source code in src/karenina/schemas/entities/rubric.py
serialize_callable_code
¶
Serialize callable_code bytes to base64 string for JSON export.
set_legacy_defaults
classmethod
¶
Set default for higher_is_better when loading legacy data.
Source code in src/karenina/schemas/entities/rubric.py
validate_callable_code
classmethod
¶
Convert base64 string to bytes if needed.
Source code in src/karenina/schemas/entities/rubric.py
ContainsAll
¶
Bases: VerificationPrimitive
Check that extracted text contains all of the given substrings.
Source code in src/karenina/schemas/primitives/comparisons.py
ContainsAny
¶
Bases: VerificationPrimitive
Check that extracted text contains at least one of the given substrings.
Source code in src/karenina/schemas/primitives/comparisons.py
DateMatch
¶
Bases: VerificationPrimitive
Parse and compare dates (format-flexible).
Uses python-dateutil for flexible parsing when no format is specified.
Source code in src/karenina/schemas/primitives/comparisons.py
DateRange
¶
Bases: VerificationPrimitive
Check that extracted date falls within a range.
Source code in src/karenina/schemas/primitives/comparisons.py
DateTolerance
¶
Bases: VerificationPrimitive
Check that extracted date is within tolerance of expected date.
Source code in src/karenina/schemas/primitives/comparisons.py
DynamicRubric
¶
Bases: BaseModel
Rubric whose traits are conditionally evaluated based on concept presence.
Unlike a regular Rubric (evaluated unconditionally), a DynamicRubric gates
each trait on whether its concept is detected in the response. Every trait
must carry either a summary or description so that the presence
check prompt can describe the concept to the judge LLM.
Source code in src/karenina/schemas/entities/rubric.py
1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 | |
Functions¶
get_trait_names
¶
Return names of all traits in type order: llm, regex, callable, metric, agentic.
is_empty
¶
resolve_concept_text
¶
resolve_concept_text(trait: _AnyTrait) -> str
Return the text to use for concept presence checking.
Prefers summary when set; falls back to description.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
trait
¶ |
_AnyTrait
|
A trait instance from this dynamic rubric. |
required |
Returns:
| Type | Description |
|---|---|
str
|
The concept text string (summary or description). |
Source code in src/karenina/schemas/entities/rubric.py
validate_concept_text
¶
validate_concept_text() -> DynamicRubric
Ensure every trait has text usable for concept presence checking.
Each trait must have at least one of summary or description.
If summary is None but description exists, a warning is logged
because summary is the preferred short label for the presence check
prompt. If both are None, the trait cannot participate in presence
checking and a ValueError is raised.
Source code in src/karenina/schemas/entities/rubric.py
validate_trait_names
¶
validate_trait_names() -> DynamicRubric
Reject duplicate trait names within and across types.
Mirrors Rubric.validate_trait_names. Both same-type and
cross-type duplicates are rejected.
Source code in src/karenina/schemas/entities/rubric.py
ExactMatch
¶
Bases: VerificationPrimitive
Normalize then compare strings for equality.
Default normalization: lowercase + strip whitespace.
Source code in src/karenina/schemas/primitives/comparisons.py
FieldCheck
¶
LLMRubricTrait
¶
Bases: BaseModel
LLM-evaluated trait for qualitative assessment.
A trait can be: - boolean (true/false): Binary pass/fail assessment - score (1-5 scale): Numeric rating within a range - literal (categorical): Classification into predefined classes
For kind="literal":
- The classes field is REQUIRED
- min_score is automatically set to 0 (first class index)
- max_score is automatically set to len(classes)-1 (last class index)
- Returns int index (0, 1, 2...) based on class order
- higher_is_better controls ordering interpretation
Deep Judgment Mode (optional): When enabled, provides evidence-based evaluation with: - Optional excerpt extraction from answer text - Retry mechanism with validation feedback - Reasoning generation explaining the score - Optional search-enhanced hallucination detection
Source code in src/karenina/schemas/entities/rubric.py
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 | |
Functions¶
get_class_index
¶
Get numeric index for a class name. Returns -1 if invalid. Only for kind='literal'.
Source code in src/karenina/schemas/entities/rubric.py
get_class_names
¶
Get list of valid class names (preserves dict order). Only for kind='literal'.
set_legacy_defaults
classmethod
¶
Set default for higher_is_better when loading legacy data.
Source code in src/karenina/schemas/entities/rubric.py
validate_classes
classmethod
¶
Validate class definitions when present.
Source code in src/karenina/schemas/entities/rubric.py
validate_kind_fields
¶
validate_kind_fields() -> LLMRubricTrait
Validate and set kind-specific fields.
Source code in src/karenina/schemas/entities/rubric.py
validate_score
¶
Validate that a given score is valid for this trait.
Source code in src/karenina/schemas/entities/rubric.py
LiteralMatch
¶
Bases: VerificationPrimitive
Exact equality for Literal-typed fields.
Source code in src/karenina/schemas/primitives/comparisons.py
MetricRubricTrait
¶
Bases: BaseModel
Metric evaluation trait using instruction-level confusion matrix analysis.
Two evaluation modes are supported:
- TP-only mode (evaluation_mode="tp_only"):
- User defines: TP instructions (what should be present)
- System evaluates:
- TP: Instructions found in answer
- FN: Instructions missing from answer
- FP: Extra content in answer not matching TP instructions
- TN: Cannot be computed (no explicit negative set)
-
Available metrics: precision, recall, f1
-
Full matrix mode (evaluation_mode="full_matrix"):
- User defines: TP instructions (should be present) + TN instructions (should NOT be present)
- System evaluates:
- TP: TP instructions found in answer
- FN: TP instructions missing from answer
- TN: TN instructions correctly absent
- FP: TN instructions incorrectly present
- Available metrics: precision, recall, specificity, accuracy, f1
The trait returns confusion matrix counts/lists and computed metric values.
Source code in src/karenina/schemas/entities/rubric.py
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 | |
Functions¶
get_required_buckets
¶
Get the set of confusion matrix buckets that will be computed for this trait.
Source code in src/karenina/schemas/entities/rubric.py
validate_metric_computability
¶
validate_metric_computability() -> MetricRubricTrait
Validate that requested metrics are compatible with the evaluation mode and provided instructions.
Source code in src/karenina/schemas/entities/rubric.py
validate_metric_names
classmethod
¶
Validate that all requested metrics are valid.
Source code in src/karenina/schemas/entities/rubric.py
NumericExact
¶
Bases: VerificationPrimitive
Exact numeric equality after float coercion.
Source code in src/karenina/schemas/primitives/comparisons.py
NumericRange
¶
Bases: VerificationPrimitive
Check that extracted number falls within a range.
Either min or max can be None for open-ended ranges.
Boundaries are inclusive by default. Set exclusive_min or
exclusive_max to True for strict inequality on that side.
Source code in src/karenina/schemas/primitives/comparisons.py
NumericTolerance
¶
Bases: VerificationPrimitive
Check that extracted number is within tolerance of expected.
Modes: - "relative": |extracted - expected| / |expected| <= tolerance - "absolute": |extracted - expected| <= tolerance
Source code in src/karenina/schemas/primitives/comparisons.py
OrderedMatch
¶
Bases: VerificationPrimitive
Compare lists element-by-element after normalization.
Source code in src/karenina/schemas/primitives/comparisons.py
Question
¶
Bases: BaseModel
Represents a self-contained benchmark question with its metadata.
This class defines the structure and validation rules for questions in the benchmark, including unique identifiers, question text, categorization keywords, and intrinsic metadata.
Backward compatibility: the legacy tags key is accepted during
construction and automatically converted to keywords.
Source code in src/karenina/schemas/entities/question.py
QuestionRegistryEntry
¶
Bases: BaseModel
Tracks benchmark-level state for a question.
This is separate from the Question model because finished status
and benchmark-level timestamps are properties of the question's
membership in a benchmark, not intrinsic to the question itself.
Source code in src/karenina/schemas/entities/question.py
RegexMatch
¶
Bases: VerificationPrimitive
Check that extracted text matches a regex pattern.
Source code in src/karenina/schemas/primitives/comparisons.py
RegexRubricTrait
¶
Bases: BaseModel
Regex-based evaluation trait for deterministic pattern matching.
This trait type uses regular expressions to perform simple text matching against answers. It always returns a boolean result.
Examples:
- Email format validation: r"\S+@\S+"
- Keyword presence: r"\bmachine learning\b"
- URL detection: r"https?://[^\s]+"
Source code in src/karenina/schemas/entities/rubric.py
Functions¶
evaluate
¶
evaluate(text: str) -> bool
Evaluate the trait against the provided text.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text
¶ |
str
|
The text to evaluate |
required |
Returns:
| Type | Description |
|---|---|
bool
|
Boolean evaluation result |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If evaluation fails |
Source code in src/karenina/schemas/entities/rubric.py
set_legacy_defaults
classmethod
¶
Set default for higher_is_better when loading legacy data.
Source code in src/karenina/schemas/entities/rubric.py
validate_regex_pattern
classmethod
¶
Validate that pattern is a valid regex.
Source code in src/karenina/schemas/entities/rubric.py
Rubric
¶
Bases: BaseModel
Collection of evaluation traits applied to all question-answer pairs.
A rubric defines the qualitative criteria used to evaluate LLM responses beyond basic correctness checking. Supports LLM-based, regex, callable, and metric traits.
Source code in src/karenina/schemas/entities/rubric.py
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 | |
Functions¶
get_agentic_trait_names
¶
get_callable_trait_names
¶
get_llm_trait_names
¶
get_metric_trait_names
¶
get_regex_trait_names
¶
get_trait_directionalities
¶
Get higher_is_better for LLM, regex, callable, and agentic traits.
Note: MetricRubricTraits are excluded as metrics (precision/recall/F1) are inherently 'higher is better'.
Returns:
| Type | Description |
|---|---|
dict[str, bool | None]
|
Dict mapping trait name to higher_is_better value. Template kind |
dict[str, bool | None]
|
agentic traits map to None because directionality is not meaningful |
dict[str, bool | None]
|
for structured results. |
Source code in src/karenina/schemas/entities/rubric.py
get_trait_max_scores
¶
Get max_score for all score-based traits (LLM and callable).
Returns:
| Type | Description |
|---|---|
dict[str, int]
|
Dict mapping trait name to max_score for traits with kind='score' or 'literal'. |
dict[str, int]
|
Boolean traits and metric traits are not included. |
dict[str, int]
|
For literal traits, max_score is len(classes)-1. |
Source code in src/karenina/schemas/entities/rubric.py
get_trait_names
¶
Get list of all trait names in this rubric (LLM, regex, callable, metric, and agentic).
Source code in src/karenina/schemas/entities/rubric.py
validate_evaluation
¶
Validate that an evaluation result matches this rubric structure.
Note: This validates LLM, regex, callable, and agentic trait scores. Metric traits are stored separately in VerificationResult fields (metric_trait_confusion_lists and metric_trait_metrics) and don't participate in this validation.
Template kind agentic traits produce dot-expanded keys (e.g.
"trait_name.field_name"), so the expected names set and per-key
validation logic account for this notation.
Source code in src/karenina/schemas/entities/rubric.py
validate_trait_names
¶
validate_trait_names() -> Rubric
Reject duplicate trait names (within and across types) and dots in agentic names.
Each trait type list must have unique names. Cross-type name overlaps are also rejected because downstream consumers (DataFrames, result dicts) use trait names as keys without type prefixes.
Dots in agentic trait names are rejected because template kind traits
produce dot-expanded keys (trait.field). A trait named "foo.bar"
would be ambiguous.
Source code in src/karenina/schemas/entities/rubric.py
RubricEvaluation
¶
Bases: BaseModel
Result of applying a rubric to a specific question-answer pair.
Source code in src/karenina/schemas/entities/rubric.py
SemanticMatch
¶
Bases: VerificationPrimitive
Check embedding similarity between extracted and expected text.
Requires an embedding model to be configured at runtime.
Source code in src/karenina/schemas/primitives/comparisons.py
SetContainment
¶
Bases: VerificationPrimitive
Compare lists as sets with configurable containment mode.
Modes: - "exact": extracted and expected contain the same elements - "subset": extracted is a subset of expected - "superset": extracted is a superset of expected - "overlap": at least min_overlap elements in common
Source code in src/karenina/schemas/primitives/comparisons.py
SynonymMap
¶
TemplateFieldSpec
¶
Bases: BaseModel
Specification for a single template field.
Maps to a VerifiedField declaration in the Python template code.
Source code in src/karenina/schemas/entities/template_spec.py
TemplateSpec
¶
Bases: BaseModel
Complete specification for a VerifiedField answer template.
This is the JSON interchange format between the visual builder GUI and the Python template code. When verify_strategy is None, the default AllOf-all-fields strategy is used.
Source code in src/karenina/schemas/entities/template_spec.py
TraceContains
¶
Bases: TracePrimitive
Check for substring in raw LLM response.
Source code in src/karenina/schemas/primitives/trace.py
TraceLength
¶
Bases: TracePrimitive
Check length of raw LLM response.
Source code in src/karenina/schemas/primitives/trace.py
TracePrimitive
¶
Bases: VerificationPrimitive
Base class for primitives that operate on raw LLM response text.
Fields using TracePrimitive are excluded from the judge's parsing schema. The pipeline evaluates them directly against the raw response.
Source code in src/karenina/schemas/primitives/trace.py
Functions¶
check
¶
Not used for trace primitives. Use check_trace() instead.
check_trace
¶
check_trace(raw_trace: str) -> bool
Evaluate the raw LLM response.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
raw_trace
¶ |
str
|
The raw text response from the answering LLM. |
required |
Returns:
| Type | Description |
|---|---|
bool
|
True if the pattern is found/condition is met. |
Source code in src/karenina/schemas/primitives/trace.py
TraceRegex
¶
Bases: TracePrimitive
Check for regex pattern in raw LLM response.
Returns True if the pattern is found (or count >= count_min).
Source code in src/karenina/schemas/primitives/trace.py
VerificationMeta
¶
Bases: BaseModel
Metadata stored on each VerifiedField, not visible to the judge.
Serialized into json_schema_extra["verification"] on the Pydantic FieldInfo. The prompt builder strips this key before sending the schema to the judge LLM.
Source code in src/karenina/schemas/entities/verified_field.py
VerificationPrimitive
¶
Bases: BaseModel
Base class for all verification primitives.
Subclasses implement check() to compare an extracted value against an expected value. The primitive type determines whether the field is included in the judge's parsing schema.
Source code in src/karenina/schemas/primitives/comparisons.py
Functions¶
check
¶
Compare extracted value against expected value.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
extracted
¶ |
Any
|
Value extracted by the judge LLM. |
required |
expected
¶ |
Any
|
Ground truth value from VerifiedField. |
required |
Returns:
| Type | Description |
|---|---|
bool
|
True if the values match according to this primitive's rules. |
Source code in src/karenina/schemas/primitives/comparisons.py
VerifyStrategySpec
¶
Bases: BaseModel
Specification for a composition strategy node.
Maps to AllOf, AnyOf, AtLeastN, or FieldCheck in the Python template.
Source code in src/karenina/schemas/entities/template_spec.py
Functions¶
VerifiedField
¶
VerifiedField(
description: str,
ground_truth: Any,
verify_with: Any,
weight: float = 1.0,
extraction_hint: str | None = None,
**kwargs: Any,
) -> Any
Create a Pydantic Field with verification metadata attached.
Unlike plain Field(), description is mandatory because the judge LLM relies on it to know what to extract.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
str
|
What to extract (goes into the JSON schema description). |
required |
|
Any
|
Expected correct value. |
required |
|
Any
|
Verification primitive instance (ExactMatch, BooleanMatch, etc.). |
required |
|
float
|
Weight for verify_granular() scoring. Default: 1.0. |
1.0
|
|
str | None
|
Optional formatting guidance for the judge. |
None
|
|
Any
|
Additional Pydantic Field arguments. |
{}
|
Returns:
| Type | Description |
|---|---|
Any
|
Pydantic FieldInfo with verification metadata in json_schema_extra. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If verify_with is None or description is empty/whitespace. |
Source code in src/karenina/schemas/entities/verified_field.py
apply_normalizer
¶
apply_normalizer(normalizer: Normalizer, text: str) -> str
Apply a single normalizer to text.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
Normalizer
|
A string normalizer name or SynonymMap instance. |
required |
|
str
|
The text to normalize. |
required |
Returns:
| Type | Description |
|---|---|
str
|
Normalized text. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If normalizer name is not recognized. |
Source code in src/karenina/schemas/primitives/normalizers.py
apply_normalizers
¶
apply_normalizers(
normalizers: list[Normalizer], text: str
) -> str
Apply a chain of normalizers in sequence.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
list[Normalizer]
|
Ordered list of normalizers to apply. |
required |
|
str
|
The text to normalize. |
required |
Returns:
| Type | Description |
|---|---|
str
|
Text after all normalizers have been applied. |
Source code in src/karenina/schemas/primitives/normalizers.py
capture_answer_source
¶
capture_answer_source(answer_class: type) -> type
Decorator/function to automatically capture source code for Answer classes in notebooks.
Usage as decorator
@capture_answer_source class Answer(BaseAnswer): # your class definition pass
Usage as function
class Answer(BaseAnswer): # your class definition pass Answer = capture_answer_source(Answer)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
type
|
The Answer class to capture source for |
required |
Returns:
| Type | Description |
|---|---|
type
|
The same class with source code captured |
Source code in src/karenina/schemas/entities/answer.py
evaluate_strategy
¶
evaluate_strategy(
node: StrategyNode, field_results: dict[str, bool]
) -> bool
Evaluate a composition strategy tree against field results.
Thin wrapper around evaluate_composition() that supplies the
FieldCheck leaf evaluator for the template domain.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
StrategyNode
|
The root node of the strategy tree. |
required |
|
dict[str, bool]
|
Mapping of field names to their pass/fail results. |
required |
Returns:
| Type | Description |
|---|---|
bool
|
True if the strategy passes. |
Raises:
| Type | Description |
|---|---|
KeyError
|
If a FieldCheck references a field not in field_results. |
Source code in src/karenina/schemas/entities/composition.py
merge_dynamic_rubrics
¶
merge_dynamic_rubrics(
global_dynamic: DynamicRubric | None,
question_dynamic: DynamicRubric | None,
) -> DynamicRubric | None
Merge global and question-specific dynamic rubrics.
Mirrors :func:merge_rubrics for the dynamic rubric variant. Same-type
name collisions are rejected; cross-type overlaps are allowed.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
DynamicRubric | None
|
The global dynamic rubric (applied to all questions). |
required |
|
DynamicRubric | None
|
Question-specific dynamic rubric. |
required |
Returns:
| Type | Description |
|---|---|
DynamicRubric | None
|
Merged DynamicRubric with traits from both sources, or None if both are None. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If a trait name appears in both rubrics within the same trait type. |
Source code in src/karenina/schemas/entities/rubric.py
merge_rubrics
¶
merge_rubrics(
global_rubric: Rubric | None,
question_rubric: Rubric | None,
) -> Rubric | None
Merge global and question-specific rubrics.
Same-type trait name collisions (e.g., both rubrics have an LLM trait
named "safety") raise ValueError. Cross-type collisions (e.g., global
regex trait "quality" + question LLM trait "quality") are allowed because
results are stored in type-segregated dicts.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
Rubric | None
|
The global rubric (applied to all questions). |
required |
|
Rubric | None
|
Question-specific rubric (adds to global). |
required |
Returns:
| Type | Description |
|---|---|
Rubric | None
|
Merged rubric, or None if both are None. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If a trait name appears in both rubrics within the same trait type. |