Skip to content

honeyhive.evaluation.evaluators

Evaluation utilities for HoneyHive.

logger module-attribute

logger = getLogger(__name__)

BUILTIN_EVALUATORS module-attribute

BUILTIN_EVALUATORS = {
    "exact_match": ExactMatchEvaluator,
    "f1_score": F1ScoreEvaluator,
    "length": LengthEvaluator,
    "semantic_similarity": SemanticSimilarityEvaluator,
}

EvaluationResult dataclass

Result of an evaluation.

Source code in src/honeyhive/evaluation/evaluators.py
27
28
29
30
31
32
33
34
35
36
@dataclass
class EvaluationResult:
    """Result of an evaluation."""

    score: float
    metrics: Dict[str, Any]
    feedback: Optional[str] = None
    metadata: Optional[Dict[str, Any]] = None
    evaluation_id: str = field(default_factory=lambda: str(uuid.uuid4()))
    timestamp: Optional[str] = None

score instance-attribute

score: float

metrics instance-attribute

metrics: Dict[str, Any]

feedback class-attribute instance-attribute

feedback: Optional[str] = None

metadata class-attribute instance-attribute

metadata: Optional[Dict[str, Any]] = None

evaluation_id class-attribute instance-attribute

evaluation_id: str = field(
    default_factory=lambda: str(uuid4())
)

timestamp class-attribute instance-attribute

timestamp: Optional[str] = None

EvaluationContext dataclass

Context for evaluation runs.

Source code in src/honeyhive/evaluation/evaluators.py
39
40
41
42
43
44
45
46
@dataclass
class EvaluationContext:
    """Context for evaluation runs."""

    project: str
    source: str
    session_id: Optional[str] = None
    metadata: Optional[Dict[str, Any]] = None

project instance-attribute

project: str

source instance-attribute

source: str

session_id class-attribute instance-attribute

session_id: Optional[str] = None

metadata class-attribute instance-attribute

metadata: Optional[Dict[str, Any]] = None

BaseEvaluator

Base class for custom evaluators.

Source code in src/honeyhive/evaluation/evaluators.py
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
class BaseEvaluator:
    """Base class for custom evaluators."""

    def __init__(self, name: str, **kwargs: Any) -> None:
        """Initialize the evaluator."""
        self.name = name
        self.__name__ = name  # Add __name__ attribute for compatibility
        self.config = kwargs

    def evaluate(
        self,
        inputs: Dict[str, Any],
        outputs: Dict[str, Any],
        ground_truth: Optional[Dict[str, Any]] = None,
        **kwargs: Any,
    ) -> Dict[str, Any]:
        """Evaluate the given inputs and outputs."""
        raise NotImplementedError("Subclasses must implement evaluate method")

    def __call__(
        self,
        inputs: Dict[str, Any],
        outputs: Dict[str, Any],
        ground_truth: Optional[Dict[str, Any]] = None,
        **kwargs: Any,
    ) -> Dict[str, Any]:
        """Make the evaluator callable."""
        return self.evaluate(inputs, outputs, ground_truth, **kwargs)

name instance-attribute

name = name

config instance-attribute

config = kwargs

evaluate

evaluate(
    inputs: Dict[str, Any],
    outputs: Dict[str, Any],
    ground_truth: Optional[Dict[str, Any]] = None,
    **kwargs: Any
) -> Dict[str, Any]

Evaluate the given inputs and outputs.

Source code in src/honeyhive/evaluation/evaluators.py
58
59
60
61
62
63
64
65
66
def evaluate(
    self,
    inputs: Dict[str, Any],
    outputs: Dict[str, Any],
    ground_truth: Optional[Dict[str, Any]] = None,
    **kwargs: Any,
) -> Dict[str, Any]:
    """Evaluate the given inputs and outputs."""
    raise NotImplementedError("Subclasses must implement evaluate method")

ExactMatchEvaluator

Bases: BaseEvaluator

Evaluator for exact string matching.

Source code in src/honeyhive/evaluation/evaluators.py
 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
class ExactMatchEvaluator(BaseEvaluator):  # pylint: disable=too-few-public-methods
    """Evaluator for exact string matching."""

    def __init__(self, **kwargs: Any) -> None:
        """Initialize the exact match evaluator."""
        super().__init__("exact_match", **kwargs)

    def evaluate(
        self,
        inputs: Dict[str, Any],
        outputs: Dict[str, Any],
        ground_truth: Optional[Dict[str, Any]] = None,
        **kwargs: Any,
    ) -> Dict[str, Any]:
        """Evaluate exact match between expected and actual outputs."""
        expected = inputs.get("expected", "")
        actual = outputs.get("response", "")

        # Handle different types
        if isinstance(expected, str) and isinstance(actual, str):
            score = float(expected.strip().lower() == actual.strip().lower())
        else:
            score = float(expected == actual)

        return {
            "exact_match": score,
            "expected": expected,
            "actual": actual,
        }

evaluate

evaluate(
    inputs: Dict[str, Any],
    outputs: Dict[str, Any],
    ground_truth: Optional[Dict[str, Any]] = None,
    **kwargs: Any
) -> Dict[str, Any]

Evaluate exact match between expected and actual outputs.

Source code in src/honeyhive/evaluation/evaluators.py
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
def evaluate(
    self,
    inputs: Dict[str, Any],
    outputs: Dict[str, Any],
    ground_truth: Optional[Dict[str, Any]] = None,
    **kwargs: Any,
) -> Dict[str, Any]:
    """Evaluate exact match between expected and actual outputs."""
    expected = inputs.get("expected", "")
    actual = outputs.get("response", "")

    # Handle different types
    if isinstance(expected, str) and isinstance(actual, str):
        score = float(expected.strip().lower() == actual.strip().lower())
    else:
        score = float(expected == actual)

    return {
        "exact_match": score,
        "expected": expected,
        "actual": actual,
    }

F1ScoreEvaluator

Bases: BaseEvaluator

Evaluator for F1 score calculation.

Source code in src/honeyhive/evaluation/evaluators.py
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
class F1ScoreEvaluator(BaseEvaluator):  # pylint: disable=too-few-public-methods
    """Evaluator for F1 score calculation."""

    def __init__(self, **kwargs: Any) -> None:
        """Initialize the F1 score evaluator."""
        super().__init__("f1_score", **kwargs)

    def evaluate(
        self,
        inputs: Dict[str, Any],
        outputs: Dict[str, Any],
        ground_truth: Optional[Dict[str, Any]] = None,
        **kwargs: Any,
    ) -> Dict[str, Any]:
        """Evaluate F1 score between expected and actual outputs."""
        expected = inputs.get("expected", "")
        actual = outputs.get("response", "")

        if not isinstance(expected, str) or not isinstance(actual, str):
            return {"f1_score": 0.0, "error": "Both inputs must be strings"}

        score = self._compute_f1_score(actual, expected)
        return {"f1_score": score}

    def _compute_f1_score(self, prediction: str, ground_truth: str) -> float:
        """Compute F1 score between prediction and ground truth."""
        pred_words = set(prediction.lower().split())
        gt_words = set(ground_truth.lower().split())

        if not pred_words or not gt_words:
            return 0.0

        intersection = pred_words & gt_words
        precision = len(intersection) / len(pred_words)
        recall = len(intersection) / len(gt_words)

        if precision + recall == 0:
            return 0.0

        return 2 * (precision * recall) / (precision + recall)

evaluate

evaluate(
    inputs: Dict[str, Any],
    outputs: Dict[str, Any],
    ground_truth: Optional[Dict[str, Any]] = None,
    **kwargs: Any
) -> Dict[str, Any]

Evaluate F1 score between expected and actual outputs.

Source code in src/honeyhive/evaluation/evaluators.py
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
def evaluate(
    self,
    inputs: Dict[str, Any],
    outputs: Dict[str, Any],
    ground_truth: Optional[Dict[str, Any]] = None,
    **kwargs: Any,
) -> Dict[str, Any]:
    """Evaluate F1 score between expected and actual outputs."""
    expected = inputs.get("expected", "")
    actual = outputs.get("response", "")

    if not isinstance(expected, str) or not isinstance(actual, str):
        return {"f1_score": 0.0, "error": "Both inputs must be strings"}

    score = self._compute_f1_score(actual, expected)
    return {"f1_score": score}

LengthEvaluator

Bases: BaseEvaluator

Evaluator for response length analysis.

Source code in src/honeyhive/evaluation/evaluators.py
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
class LengthEvaluator(BaseEvaluator):  # pylint: disable=too-few-public-methods
    """Evaluator for response length analysis."""

    def __init__(self, **kwargs: Any) -> None:
        """Initialize the length evaluator."""
        super().__init__("length", **kwargs)

    def evaluate(
        self,
        inputs: Dict[str, Any],
        outputs: Dict[str, Any],
        ground_truth: Optional[Dict[str, Any]] = None,
        **kwargs: Any,
    ) -> Dict[str, Any]:
        """Evaluate response length metrics."""
        response = outputs.get("response", "")

        if isinstance(response, str):
            char_count = len(response)
            word_count = len(response.split())
            line_count = len(response.splitlines())
        else:
            char_count = len(str(response))
            word_count = 1
            line_count = 1

        return {
            "char_count": char_count,
            "word_count": word_count,
            "line_count": line_count,
        }

evaluate

evaluate(
    inputs: Dict[str, Any],
    outputs: Dict[str, Any],
    ground_truth: Optional[Dict[str, Any]] = None,
    **kwargs: Any
) -> Dict[str, Any]

Evaluate response length metrics.

Source code in src/honeyhive/evaluation/evaluators.py
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
def evaluate(
    self,
    inputs: Dict[str, Any],
    outputs: Dict[str, Any],
    ground_truth: Optional[Dict[str, Any]] = None,
    **kwargs: Any,
) -> Dict[str, Any]:
    """Evaluate response length metrics."""
    response = outputs.get("response", "")

    if isinstance(response, str):
        char_count = len(response)
        word_count = len(response.split())
        line_count = len(response.splitlines())
    else:
        char_count = len(str(response))
        word_count = 1
        line_count = 1

    return {
        "char_count": char_count,
        "word_count": word_count,
        "line_count": line_count,
    }

SemanticSimilarityEvaluator

Bases: BaseEvaluator

Evaluator for semantic similarity using basic heuristics.

Source code in src/honeyhive/evaluation/evaluators.py
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
class SemanticSimilarityEvaluator(BaseEvaluator):
    # pylint: disable=too-few-public-methods
    """Evaluator for semantic similarity using basic heuristics."""

    def __init__(self, **kwargs: Any) -> None:
        """Initialize the semantic similarity evaluator."""
        super().__init__("semantic_similarity", **kwargs)

    def evaluate(
        self,
        inputs: Dict[str, Any],
        outputs: Dict[str, Any],
        ground_truth: Optional[Dict[str, Any]] = None,
        **kwargs: Any,
    ) -> Dict[str, Any]:
        """Evaluate semantic similarity between expected and actual outputs."""
        expected = inputs.get("expected", "")
        actual = outputs.get("response", "")

        if not isinstance(expected, str) or not isinstance(actual, str):
            return {"semantic_similarity": 0.0, "error": "Both inputs must be strings"}

        # Simple semantic similarity using word overlap and structure
        score = self._compute_semantic_similarity(actual, expected)
        return {"semantic_similarity": score}

    def _compute_semantic_similarity(self, prediction: str, ground_truth: str) -> float:
        """Compute semantic similarity score."""
        pred_words = set(prediction.lower().split())
        gt_words = set(ground_truth.lower().split())

        if not pred_words or not gt_words:
            return 0.0

        # Word overlap
        overlap = len(pred_words & gt_words)
        total_unique = len(pred_words | gt_words)

        # Structure similarity (simple heuristic)
        pred_sentences = len(prediction.split("."))
        gt_sentences = len(ground_truth.split("."))
        structure_similarity = 1.0 - abs(pred_sentences - gt_sentences) / max(
            pred_sentences, gt_sentences, 1
        )

        # Combined score
        word_similarity = overlap / total_unique if total_unique > 0 else 0.0
        final_score = (word_similarity * 0.7) + (structure_similarity * 0.3)

        return min(1.0, max(0.0, final_score))

evaluate

evaluate(
    inputs: Dict[str, Any],
    outputs: Dict[str, Any],
    ground_truth: Optional[Dict[str, Any]] = None,
    **kwargs: Any
) -> Dict[str, Any]

Evaluate semantic similarity between expected and actual outputs.

Source code in src/honeyhive/evaluation/evaluators.py
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
def evaluate(
    self,
    inputs: Dict[str, Any],
    outputs: Dict[str, Any],
    ground_truth: Optional[Dict[str, Any]] = None,
    **kwargs: Any,
) -> Dict[str, Any]:
    """Evaluate semantic similarity between expected and actual outputs."""
    expected = inputs.get("expected", "")
    actual = outputs.get("response", "")

    if not isinstance(expected, str) or not isinstance(actual, str):
        return {"semantic_similarity": 0.0, "error": "Both inputs must be strings"}

    # Simple semantic similarity using word overlap and structure
    score = self._compute_semantic_similarity(actual, expected)
    return {"semantic_similarity": score}

get_evaluator

get_evaluator(
    evaluator_name: str, **kwargs: Any
) -> BaseEvaluator

Get a built-in evaluator by name.

Source code in src/honeyhive/evaluation/evaluators.py
246
247
248
249
250
251
def get_evaluator(evaluator_name: str, **kwargs: Any) -> BaseEvaluator:
    """Get a built-in evaluator by name."""
    if evaluator_name not in BUILTIN_EVALUATORS:
        raise ValueError(f"Unknown evaluator: {evaluator_name}")

    return BUILTIN_EVALUATORS[evaluator_name](**kwargs)

evaluate

evaluate(
    prediction: str,
    ground_truth: str,
    metrics: Optional[List[str]] = None,
    **kwargs: Any
) -> EvaluationResult

Evaluate a prediction against ground truth.

Parameters:

Name Type Description Default
prediction str

Model prediction

required
ground_truth str

Ground truth value

required
metrics Optional[List[str]]

List of metrics to compute

None
**kwargs Any

Additional evaluation parameters

{}

Returns:

Type Description
EvaluationResult

Evaluation result

Source code in src/honeyhive/evaluation/evaluators.py
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
def evaluate(
    prediction: str,
    ground_truth: str,
    metrics: Optional[List[str]] = None,
    **kwargs: Any,
) -> EvaluationResult:
    """Evaluate a prediction against ground truth.

    Args:
        prediction: Model prediction
        ground_truth: Ground truth value
        metrics: List of metrics to compute
        **kwargs: Additional evaluation parameters

    Returns:
        Evaluation result
    """
    # Default metrics
    if metrics is None:
        metrics = ["exact_match", "f1_score"]

    result_metrics = {}

    # Create inputs/outputs dict for evaluators
    inputs = {"expected": ground_truth}
    outputs = {"response": prediction}

    # Run each metric
    for metric in metrics:
        if metric in BUILTIN_EVALUATORS:
            eval_instance = BUILTIN_EVALUATORS[metric]()
            try:
                metric_result = eval_instance.evaluate(inputs, outputs)
                result_metrics.update(metric_result)
            except Exception as e:
                logger.warning("Failed to compute %s: %s", metric, e)
                result_metrics[metric] = 0.0

    # Compute overall score (average of numeric metrics)
    numeric_metrics = [
        v for v in result_metrics.values() if isinstance(v, (int, float))
    ]
    overall_score = (
        sum(numeric_metrics) / len(numeric_metrics) if numeric_metrics else 0.0
    )

    # Ensure score is in 0-1 range
    overall_score = max(0.0, min(1.0, overall_score))

    return EvaluationResult(score=overall_score, metrics=result_metrics, **kwargs)

evaluate_decorator

evaluate_decorator(
    evaluators: Optional[
        List[Union[str, BaseEvaluator, Callable]]
    ] = None,
    **kwargs: Any
) -> Callable[[Callable], Callable]

Decorator for functions that should be evaluated.

This is the main @evaluate decorator that can be used with evaluators.

Parameters:

Name Type Description Default
evaluators Optional[List[Union[str, BaseEvaluator, Callable]]]

List of evaluators to apply

None
**kwargs Any

Additional evaluation parameters

{}
Source code in src/honeyhive/evaluation/evaluators.py
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
def evaluate_decorator(
    evaluators: Optional[List[Union[str, BaseEvaluator, Callable]]] = None,
    **kwargs: Any,
) -> Callable[[Callable], Callable]:
    """Decorator for functions that should be evaluated.

    This is the main @evaluate decorator that can be used with evaluators.

    Args:
        evaluators: List of evaluators to apply
        **kwargs: Additional evaluation parameters
    """

    def decorator(func: Callable) -> Callable:
        # Check if function is async
        if asyncio.iscoroutinefunction(func):  # pylint: disable=no-else-return

            @functools.wraps(func)
            async def async_wrapper(*args: Any, **func_kwargs: Any) -> Any:
                # Execute the async function first
                result = await func(*args, **func_kwargs)

                # If we have evaluators and the first argument is a dict (inputs)
                if evaluators and args and isinstance(args[0], dict):
                    inputs = args[0]

                    # Convert result to outputs format if it's not already
                    if isinstance(result, dict):
                        outputs = result
                    else:
                        outputs = {"response": result}

                    # Run evaluation
                    try:
                        eval_result = evaluate_with_evaluators(
                            evaluators=evaluators,
                            inputs=inputs,
                            outputs=outputs,
                            **kwargs,
                        )

                        # Store evaluation result in metadata if result is a dict
                        if isinstance(result, dict):
                            if "evaluation" not in result:
                                result["evaluation"] = {}
                            result["evaluation"]["result"] = eval_result
                        else:
                            # If result is not a dict, we can't easily attach evaluation
                            # but we could log it or store it elsewhere
                            logger.info("Evaluation result: %s", eval_result)

                    except Exception as e:
                        logger.warning("Evaluation failed: %s", e)

                return result

            return async_wrapper
        else:

            @functools.wraps(func)
            def sync_wrapper(*args: Any, **func_kwargs: Any) -> Any:
                # Execute the function first
                result = func(*args, **func_kwargs)

                # If we have evaluators and the first argument is a dict (inputs)
                if evaluators and args and isinstance(args[0], dict):
                    inputs = args[0]

                    # Convert result to outputs format if it's not already
                    if isinstance(result, dict):
                        outputs = result
                    else:
                        outputs = {"response": result}

                    # Run evaluation
                    try:
                        eval_result = evaluate_with_evaluators(
                            evaluators=evaluators,
                            inputs=inputs,
                            outputs=outputs,
                            **kwargs,
                        )

                        # Store evaluation result in metadata if result is a dict
                        if isinstance(result, dict):
                            if "evaluation" not in result:
                                result["evaluation"] = {}
                            result["evaluation"]["result"] = eval_result
                        else:
                            # If result is not a dict, we can't easily attach evaluation
                            # but we could log it or store it elsewhere
                            logger.info("Evaluation result: %s", eval_result)

                    except Exception as e:
                        logger.warning("Evaluation failed: %s", e)

                return result

            return sync_wrapper

    return decorator

evaluator

evaluator(
    _name: Optional[str] = None,
    _session_id: Optional[str] = None,
    **_kwargs: Any
) -> Callable[[Callable], Callable]

Decorator for synchronous evaluation functions.

Parameters:

Name Type Description Default
name

Evaluation name

required
session_id

Session ID for tracing

required
**kwargs

Additional evaluation parameters

required
Source code in src/honeyhive/evaluation/evaluators.py
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
def evaluator(
    _name: Optional[str] = None, _session_id: Optional[str] = None, **_kwargs: Any
) -> Callable[[Callable], Callable]:
    """Decorator for synchronous evaluation functions.

    Args:
        name: Evaluation name
        session_id: Session ID for tracing
        **kwargs: Additional evaluation parameters
    """

    def decorator(func: Callable) -> Callable:
        @functools.wraps(func)
        def wrapper(*args: Any, **kwargs: Any) -> Any:
            # Execute evaluation
            result = func(*args, **kwargs)

            # Note: Event creation for evaluation functions is disabled to avoid \
            # type issues
            # The evaluation functionality works independently of event creation

            return result

        return wrapper

    return decorator

aevaluator

aevaluator(
    _name: Optional[str] = None,
    _session_id: Optional[str] = None,
    **_kwargs: Any
) -> Callable[[Callable], Callable]

Decorator for asynchronous evaluation functions.

Parameters:

Name Type Description Default
name

Evaluation name

required
session_id

Session ID for tracing

required
**kwargs

Additional evaluation parameters

required
Source code in src/honeyhive/evaluation/evaluators.py
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
def aevaluator(
    _name: Optional[str] = None, _session_id: Optional[str] = None, **_kwargs: Any
) -> Callable[[Callable], Callable]:
    """Decorator for asynchronous evaluation functions.

    Args:
        name: Evaluation name
        session_id: Session ID for tracing
        **kwargs: Additional evaluation parameters
    """

    def decorator(func: Callable) -> Callable:
        @functools.wraps(func)
        async def wrapper(*args: Any, **kwargs: Any) -> Any:
            # Execute evaluation
            result = await func(*args, **kwargs)

            # Note: Event creation for evaluation functions is disabled to avoid \
            # type issues
            # The evaluation functionality works independently of event creation

            return result

        return wrapper

    return decorator

evaluate_with_evaluators

evaluate_with_evaluators(
    evaluators: List[Union[str, BaseEvaluator, Callable]],
    inputs: Dict[str, Any],
    outputs: Dict[str, Any],
    *,
    ground_truth: Optional[Dict[str, Any]] = None,
    context: Optional[EvaluationContext] = None,
    max_workers: int = 1,
    run_concurrently: bool = True
) -> EvaluationResult

Evaluate outputs using multiple evaluators with optional threading support.

Parameters:

Name Type Description Default
evaluators List[Union[str, BaseEvaluator, Callable]]

List of evaluators to apply

required
inputs Dict[str, Any]

Input data for evaluation

required
outputs Dict[str, Any]

Output data to evaluate

required
ground_truth Optional[Dict[str, Any]]

Ground truth data for comparison

None
context Optional[EvaluationContext]

Evaluation context

None
max_workers int

Maximum number of worker threads for parallel evaluation

1
run_concurrently bool

Whether to run evaluators concurrently

True

Returns:

Type Description
EvaluationResult

EvaluationResult with aggregated metrics

Source code in src/honeyhive/evaluation/evaluators.py
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
def evaluate_with_evaluators(
    # pylint: disable=too-many-arguments,too-many-branches
    evaluators: List[Union[str, BaseEvaluator, Callable]],
    inputs: Dict[str, Any],
    outputs: Dict[str, Any],
    *,
    ground_truth: Optional[Dict[str, Any]] = None,
    context: Optional[EvaluationContext] = None,
    max_workers: int = 1,
    run_concurrently: bool = True,
) -> EvaluationResult:
    """Evaluate outputs using multiple evaluators with optional threading support.

    Args:
        evaluators: List of evaluators to apply
        inputs: Input data for evaluation
        outputs: Output data to evaluate
        ground_truth: Ground truth data for comparison
        context: Evaluation context
        max_workers: Maximum number of worker threads for parallel evaluation
        run_concurrently: Whether to run evaluators concurrently

    Returns:
        EvaluationResult with aggregated metrics
    """
    if not evaluators:
        return EvaluationResult(
            score=0.0,
            metrics={},
            metadata={
                "inputs": inputs,
                "outputs": outputs,
                "ground_truth": ground_truth,
                "context": context.__dict__ if context else None,
            },
        )

    metrics: Dict[str, Any] = {}

    if run_concurrently and max_workers > 1 and len(evaluators) > 1:
        # Run evaluators concurrently using ThreadPoolExecutor
        with ThreadPoolExecutor(max_workers=max_workers) as executor:
            # Submit evaluation tasks
            futures = []
            for eval_item in evaluators:
                eval_func = _get_evaluator_function(eval_item)

                # Create context for each thread
                ctx = contextvars.copy_context()
                future = executor.submit(
                    ctx.run,
                    functools.partial(
                        _run_single_evaluator, eval_func, inputs, outputs, ground_truth
                    ),
                )
                futures.append((eval_item, future))

            # Collect results
            for eval_item, future in futures:
                try:
                    result = future.result()
                    if isinstance(eval_item, str):
                        evaluator_name = eval_item
                    elif isinstance(eval_item, BaseEvaluator):
                        evaluator_name = eval_item.name
                    else:
                        evaluator_name = getattr(eval_item, "__name__", str(eval_item))

                    metrics[evaluator_name] = result
                except Exception as e:
                    logger.warning("Evaluator %s failed: %s", eval_item, e)
                    if isinstance(eval_item, str):
                        evaluator_name = eval_item
                    elif isinstance(eval_item, BaseEvaluator):
                        evaluator_name = eval_item.name
                    else:
                        evaluator_name = getattr(eval_item, "__name__", str(eval_item))
                    metrics[evaluator_name] = None
    else:
        # Run evaluators sequentially
        for eval_item in evaluators:
            try:
                eval_func = _get_evaluator_function(eval_item)

                if isinstance(eval_item, str):
                    evaluator_name = eval_item
                elif isinstance(eval_item, BaseEvaluator):
                    evaluator_name = eval_item.name
                else:
                    evaluator_name = getattr(eval_item, "__name__", str(eval_item))

                result = _run_single_evaluator(eval_func, inputs, outputs, ground_truth)
                metrics[evaluator_name] = result
            except Exception as e:
                logger.warning("Evaluator %s failed: %s", eval_item, e)
                if isinstance(eval_item, str):
                    evaluator_name = eval_item
                elif isinstance(eval_item, BaseEvaluator):
                    evaluator_name = eval_item.name
                else:
                    evaluator_name = getattr(eval_item, "__name__", str(eval_item))
                metrics[evaluator_name] = None

    # Calculate overall score
    valid_scores = []
    for metric_result in metrics.values():
        if metric_result is not None and isinstance(metric_result, dict):
            # Extract numeric scores from metric result dictionaries
            for value in metric_result.values():
                if isinstance(value, (int, float)) and value > 0:
                    valid_scores.append(value)
        elif isinstance(metric_result, (int, float)) and metric_result > 0:
            valid_scores.append(metric_result)

    if valid_scores:
        overall_score = sum(valid_scores) / len(valid_scores)
        # Normalize score to 0-1 range
        overall_score = max(0.0, min(1.0, overall_score))
    else:
        overall_score = 0.0

    return EvaluationResult(
        score=overall_score,
        metrics=metrics,
        metadata={
            "inputs": inputs,
            "outputs": outputs,
            "ground_truth": ground_truth,
            "context": context.__dict__ if context else None,
        },
    )

evaluate_batch

evaluate_batch(
    evaluators: List[Union[str, BaseEvaluator, Callable]],
    dataset: List[Dict[str, Any]],
    max_workers: int = 4,
    run_concurrently: bool = True,
    context: Optional[EvaluationContext] = None,
) -> List[EvaluationResult]

Evaluate a batch of data points using multiple evaluators with threading support.

Parameters:

Name Type Description Default
evaluators List[Union[str, BaseEvaluator, Callable]]

List of evaluators to apply

required
dataset List[Dict[str, Any]]

List of data points, each containing inputs, outputs, and optional ground_truth

required
max_workers int

Maximum number of worker threads for parallel evaluation

4
run_concurrently bool

Whether to run evaluations concurrently

True
context Optional[EvaluationContext]

Evaluation context

None

Returns:

Type Description
List[EvaluationResult]

List of EvaluationResult objects

Source code in src/honeyhive/evaluation/evaluators.py
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
def evaluate_batch(
    evaluators: List[Union[str, BaseEvaluator, Callable]],
    dataset: List[Dict[str, Any]],
    max_workers: int = 4,
    run_concurrently: bool = True,
    context: Optional[EvaluationContext] = None,
) -> List[EvaluationResult]:
    """Evaluate a batch of data points using multiple evaluators with threading support.

    Args:
        evaluators: List of evaluators to apply
        dataset: List of data points, each containing inputs, outputs, and \
        optional ground_truth
        max_workers: Maximum number of worker threads for parallel evaluation
        run_concurrently: Whether to run evaluations concurrently
        context: Evaluation context

    Returns:
        List of EvaluationResult objects
    """
    if not dataset:
        return []

    if run_concurrently and max_workers > 1 and len(dataset) > 1:
        # Run evaluations concurrently using ThreadPoolExecutor
        with ThreadPoolExecutor(max_workers=max_workers) as executor:
            # Submit evaluation tasks
            futures = []
            for data_point in dataset:
                inputs = data_point.get("inputs", {})
                outputs = data_point.get("outputs", {})
                ground_truth = data_point.get("ground_truth")

                # Create context for each thread
                ctx = contextvars.copy_context()
                future = executor.submit(
                    ctx.run,
                    functools.partial(
                        evaluate_with_evaluators,
                        evaluators=evaluators,
                        inputs=inputs,
                        outputs=outputs,
                        ground_truth=ground_truth,
                        context=context,
                        max_workers=1,  # Single evaluator per thread
                        run_concurrently=False,  # Sequential within thread
                    ),
                )
                futures.append(future)

            # Collect results
            results = []
            for future in futures:
                try:
                    result = future.result()
                    results.append(result)
                except Exception as e:
                    logger.warning("Batch evaluation failed: %s", e)
                    # Create empty result for failed evaluation
                    results.append(
                        EvaluationResult(
                            score=0.0,
                            metrics={},
                            metadata={
                                "inputs": {},
                                "outputs": {},
                                "ground_truth": {},
                                "context": context.__dict__ if context else None,
                            },
                        )
                    )

            return results
    else:
        # Run evaluations sequentially
        results = []
        for data_point in dataset:
            try:
                inputs = data_point.get("inputs", {})
                outputs = data_point.get("outputs", {})
                ground_truth = data_point.get("ground_truth")

                result = evaluate_with_evaluators(
                    evaluators=evaluators,
                    inputs=inputs,
                    outputs=outputs,
                    ground_truth=ground_truth,
                    context=context,
                    max_workers=1,
                    run_concurrently=False,
                )
                results.append(result)
            except Exception as e:
                logger.warning("Batch evaluation failed: %s", e)
                # Create empty result for failed evaluation
                results.append(
                    EvaluationResult(
                        score=0.0,
                        metrics={},
                        metadata={
                            "inputs": {},
                            "outputs": {},
                            "ground_truth": {},
                            "context": context.__dict__ if context else None,
                        },
                    )
                )

        return results

create_evaluation_run

create_evaluation_run(
    name: str,
    project: str,
    _results: List[EvaluationResult],
    metadata: Optional[Dict[str, Any]] = None,
    client: Optional[HoneyHive] = None,
) -> Optional[ExperimentResultSummary]

Create an evaluation run in HoneyHive.

Parameters:

Name Type Description Default
name str

Name of the evaluation run

required
project str

Project name

required
results

List of evaluation results

required
metadata Optional[Dict[str, Any]]

Additional metadata

None
client Optional[HoneyHive]

HoneyHive client instance

None

Returns:

Type Description
Optional[ExperimentResultSummary]

Created evaluation run or None if failed

Source code in src/honeyhive/evaluation/evaluators.py
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
def create_evaluation_run(
    name: str,
    project: str,
    _results: List[EvaluationResult],
    metadata: Optional[Dict[str, Any]] = None,
    client: Optional[HoneyHive] = None,
) -> Optional[ExperimentResultSummary]:
    """Create an evaluation run in HoneyHive.

    Args:
        name: Name of the evaluation run
        project: Project name
        results: List of evaluation results
        metadata: Additional metadata
        client: HoneyHive client instance

    Returns:
        Created evaluation run or None if failed
    """
    if client is None:
        try:
            import os

            api_key = os.getenv("HONEYHIVE_API_KEY") or os.getenv("HH_API_KEY")
            if not api_key:
                logger.warning("No API key found - set HONEYHIVE_API_KEY or HH_API_KEY")
                return None
            client = HoneyHive(api_key=api_key)
        except Exception as e:
            logger.warning("Could not create HoneyHive client: %s", e)
            return None

    try:
        # Aggregate results (commented out for future use)
        # total_score = sum(r.score for r in results)

        # Prepare run data - PostExperimentRunRequest expects specific fields
        # For now, we'll create a minimal request with required fields
        # Note: This is a simplified version - in production you'd want proper UUIDs
        try:
            # Create run request with minimal required data
            run_request = PostExperimentRunRequest(
                name=name,
                project=project,  # This should be a valid UUID string
                event_ids=[],  # Empty list for now - in production you'd want \
                # actual event IDs
                dataset_id=None,
                datapoint_ids=None,
                configuration=None,
                status=None,
                metadata=metadata or {},
            )
        except Exception as e:
            logger.warning("Could not create PostExperimentRunRequest: %s", e)
            # Fallback: return None instead of crashing
            return None

        # Submit to API (experiments API handles runs)
        response = client.experiments.create_run(run_request)

        logger.info(
            "Created evaluation run: %s",
            response.run_id if hasattr(response, "run_id") else "unknown",
        )
        return response

    except Exception as e:
        logger.error("Failed to create evaluation run: %s", e)
        return None