evals
patronus.evals
evaluators
Evaluator
Base Evaluator Class
evaluate
abstractmethod
Synchronous version of evaluate method. When inheriting directly from Evaluator class it's permitted to change parameters signature. Return type should stay unchanged.
Source code in src/patronus/evals/evaluators.py
AsyncEvaluator
Bases: Evaluator
evaluate
abstractmethod
async
Asynchronous version of evaluate method. When inheriting directly from Evaluator class it's permitted to change parameters signature. Return type should stay unchanged.
Source code in src/patronus/evals/evaluators.py
StructuredEvaluator
AsyncStructuredEvaluator
RemoteEvaluator
RemoteEvaluator(
evaluator_id_or_alias: str,
criteria: Optional[str] = None,
*,
tags: Optional[dict[str, str]] = None,
explain_strategy: Literal[
"never", "on-fail", "on-success", "always"
] = "always",
criteria_config: Optional[dict[str, Any]] = None,
allow_update: bool = False,
max_attempts: int = 3,
api_: Optional[PatronusAPIClient] = None,
)
Bases: RemoteEvaluatorMixin
, StructuredEvaluator
Synchronous remote evaluator
Source code in src/patronus/evals/evaluators.py
evaluate
evaluate(
*,
system_prompt: Optional[str] = None,
task_context: Union[list[str], str, None] = None,
task_attachments: Union[list[Any], None] = None,
task_input: Optional[str] = None,
task_output: Optional[str] = None,
gold_answer: Optional[str] = None,
task_metadata: Optional[Dict[str, Any]] = None,
**kwargs: Any,
) -> EvaluationResult
Evaluates data using remote Patronus Evaluator
Source code in src/patronus/evals/evaluators.py
AsyncRemoteEvaluator
AsyncRemoteEvaluator(
evaluator_id_or_alias: str,
criteria: Optional[str] = None,
*,
tags: Optional[dict[str, str]] = None,
explain_strategy: Literal[
"never", "on-fail", "on-success", "always"
] = "always",
criteria_config: Optional[dict[str, Any]] = None,
allow_update: bool = False,
max_attempts: int = 3,
api_: Optional[PatronusAPIClient] = None,
)
Bases: RemoteEvaluatorMixin
, AsyncStructuredEvaluator
Asynchronous remote evaluator
Source code in src/patronus/evals/evaluators.py
evaluate
async
evaluate(
*,
system_prompt: Optional[str] = None,
task_context: Union[list[str], str, None] = None,
task_attachments: Union[list[Any], None] = None,
task_input: Optional[str] = None,
task_output: Optional[str] = None,
gold_answer: Optional[str] = None,
task_metadata: Optional[Dict[str, Any]] = None,
**kwargs: Any,
) -> EvaluationResult
Evaluates data using remote Patronus Evaluator
Source code in src/patronus/evals/evaluators.py
get_current_log_id
Return log_id for given arguments in current context. Returns None if there is no context - most likely SDK is not initialized.
Source code in src/patronus/evals/evaluators.py
bundled_eval
Start a span that would automatically bundle evaluations.
Evaluations are passed by arguments passed to the evaluators called inside the context manager.
The following example would create two bundles:
- fist with arguments
x=10, y=20
- second with arguments
spam="abc123"
with bundled_eval():
foo_evaluator(x=10, y=20)
bar_evaluator(x=10, y=20)
tar_evaluator(spam="abc123")
Source code in src/patronus/evals/evaluators.py
evaluator
evaluator(
_fn: Optional[Callable[..., Any]] = None,
*,
evaluator_id: Union[
str, Callable[[], str], None
] = None,
criteria: Union[str, Callable[[], str], None] = None,
metric_name: Optional[str] = None,
metric_description: Optional[str] = None,
is_method: bool = False,
span_name: Optional[str] = None,
log_none_arguments: bool = False,
**kwargs: Any,
) -> typing.Callable[..., typing.Any]
Decorator for creating functional-style evaluators that log execution and results.
This decorator works with both synchronous and asynchronous functions. The decorator doesn't modify the function's return value, but records it after converting to an EvaluationResult.
Evaluators can return different types which are automatically converted to EvaluationResult
objects:
bool
:True
/False
indicating pass/fail.float
/int
: Numerical scores (typically between 0-1).str
: Text output categorizing the result.- EvaluationResult: Complete evaluation with scores, explanations, etc.
None
: Indicates evaluation was skipped and no result will be recorded.
Evaluation results are exported in the background without blocking execution. The SDK must be
initialized with patronus.init()
for evaluations to be recorded, though decorated functions
will still execute even without initialization.
The evaluator integrates with a context-based system to identify and handle shared evaluation logging and tracing spans.
Example:
from patronus import init, evaluator
from patronus.evals import EvaluationResult
# Initialize the SDK to record evaluations
init()
# Simple evaluator function
@evaluator()
def exact_match(actual: str, expected: str) -> bool:
return actual.strip() == expected.strip()
# More complex evaluator with detailed result
@evaluator()
def semantic_match(actual: str, expected: str) -> EvaluationResult:
similarity = calculate_similarity(actual, expected) # Your similarity function
return EvaluationResult(
score=similarity,
pass_=similarity > 0.8,
text_output="High similarity" if similarity > 0.8 else "Low similarity",
explanation=f"Calculated similarity: {similarity}"
)
# Use the evaluators
result = exact_match("Hello world", "Hello world")
print(f"Match: {result}") # Output: Match: True
Parameters:
Name | Type | Description | Default |
---|---|---|---|
_fn
|
Optional[Callable[..., Any]]
|
The function to be decorated. |
None
|
evaluator_id
|
Union[str, Callable[[], str], None]
|
Name for the evaluator. Defaults to function name (or class name in case of class based evaluators). |
None
|
criteria
|
Union[str, Callable[[], str], None]
|
Name of the criteria used by the evaluator. The use of the criteria is only recommended in more complex evaluator setups where evaluation algorithm changes depending on a criteria (think strategy pattern). |
None
|
metric_name
|
Optional[str]
|
Name for the evaluation metric. Defaults to evaluator_id value. |
None
|
metric_description
|
Optional[str]
|
The description of the metric used for evaluation. If not provided then the docstring of the wrapped function is used for this value. |
None
|
is_method
|
bool
|
Whether the wrapped function is a method.
This value is used to determine whether to remove "self" argument from the log.
It also allows for dynamic evaluator_id and criteria discovery
based on |
False
|
span_name
|
Optional[str]
|
Name of the span to represent this evaluation in the tracing system. Defaults to None, in which case a default name is generated based on the evaluator. |
None
|
log_none_arguments
|
bool
|
Controls whether arguments with None values are included in log output. This setting affects only logging behavior and has no impact on function execution. Note: Only applies to top-level arguments. For nested structures like dictionaries, None values will always be logged regardless of this setting. |
False
|
**kwargs
|
Any
|
Additional keyword arguments that may be passed to the decorator or its internal methods. |
{}
|
Returns:
Name | Type | Description |
---|---|---|
Callable |
Callable[..., Any]
|
Returns the decorated function with additional evaluation behavior, suitable for synchronous or asynchronous usage. |
Note
For evaluations that need to be compatible with experiments, consider using StructuredEvaluator or AsyncStructuredEvaluator classes instead.
Source code in src/patronus/evals/evaluators.py
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 |
|
types
EvaluationResult
Bases: BaseModel
Container for evaluation outcomes including score, pass/fail status, explanations, and metadata.
This class stores complete evaluation results with numeric scores, boolean pass/fail statuses, textual outputs, explanations, and arbitrary metadata. Evaluator functions can return instances of this class directly or return simpler types (bool, float, str) which will be automatically converted to EvaluationResult objects during recording.
Attributes:
Name | Type | Description |
---|---|---|
score |
Optional[float]
|
Score of the evaluation. Can be any numerical value, though typically ranges from 0 to 1, where 1 represents the best possible score. |
pass_ |
Optional[bool]
|
Whether the evaluation is considered to pass or fail. |
text_output |
Optional[str]
|
Text output of the evaluation. Usually used for discrete human-readable category evaluation or as a label for score value. |
metadata |
Optional[dict[str, Any]]
|
Arbitrary json-serializable metadata about evaluation. |
explanation |
Optional[str]
|
Human-readable explanation of the evaluation. |
tags |
Optional[dict[str, str]]
|
Key-value pair metadata. |
dataset_id |
Optional[str]
|
ID of the dataset associated with evaluated sample. |
dataset_sample_id |
Optional[str]
|
ID of the sample in a dataset associated with evaluated sample. |
evaluation_duration |
Optional[timedelta]
|
Duration of the evaluation. In case value is not set, @evaluator decorator and Evaluator classes will set this value automatically. |
explanation_duration |
Optional[timedelta]
|
Duration of the evaluation explanation. |
format
pretty_print
Pretty prints the formatted content to the specified file or standard output.