|
| 1 | +"""Fixtures for CrewAI Websearch agent evals.""" |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +import asyncio |
| 6 | +import logging |
| 7 | +import os |
| 8 | +import time |
| 9 | +from pathlib import Path |
| 10 | +from typing import Any, AsyncGenerator, Callable, Coroutine |
| 11 | + |
| 12 | +import httpx |
| 13 | +import pytest |
| 14 | +import yaml |
| 15 | +from harness.runner import TaskConfig, TaskResult, run_task |
| 16 | + |
| 17 | +try: |
| 18 | + from harness.mlflow_client import MLflowTraceClient |
| 19 | +except ImportError: |
| 20 | + MLflowTraceClient = None # type: ignore[misc,assignment] |
| 21 | + |
| 22 | + |
| 23 | +@pytest.fixture |
| 24 | +def agent_url() -> str: |
| 25 | + """CrewAI Websearch agent URL from env var or default localhost:8000.""" |
| 26 | + return os.environ.get("CREWAI_WEBSEARCH_AGENT_URL", "http://localhost:8000") |
| 27 | + |
| 28 | + |
| 29 | +@pytest.fixture |
| 30 | +async def http_client() -> AsyncGenerator[httpx.AsyncClient, None]: |
| 31 | + """Provide an async httpx client that is closed after the test.""" |
| 32 | + async with httpx.AsyncClient() as client: |
| 33 | + yield client |
| 34 | + |
| 35 | + |
| 36 | +def _find_repo_root() -> Path: |
| 37 | + """Walk up from this file to find the repository root.""" |
| 38 | + path = Path(__file__).resolve().parent |
| 39 | + while path.parent != path: |
| 40 | + if (path / "tests" / "behavioral" / "configs" / "thresholds.yaml").is_file(): |
| 41 | + return path |
| 42 | + path = path.parent |
| 43 | + pytest.skip( |
| 44 | + "Could not find repo root (no tests/behavioral/configs/thresholds.yaml)" |
| 45 | + ) |
| 46 | + |
| 47 | + |
| 48 | +@pytest.fixture |
| 49 | +def eval_config() -> dict[str, Any]: |
| 50 | + """Load threshold configuration from the shared configs directory.""" |
| 51 | + config_path = ( |
| 52 | + _find_repo_root() / "tests" / "behavioral" / "configs" / "thresholds.yaml" |
| 53 | + ) |
| 54 | + with open(config_path, encoding="utf-8") as f: |
| 55 | + return yaml.safe_load(f) |
| 56 | + |
| 57 | + |
| 58 | +SEARCH_EVIDENCE = ["openshift ai"] |
| 59 | + |
| 60 | + |
| 61 | +def load_golden(category: str | None = None) -> list[dict[str, Any]]: |
| 62 | + """Load golden queries from the fixtures directory, optionally filtering by category.""" |
| 63 | + path = Path(__file__).parent / "fixtures" / "golden_queries.yaml" |
| 64 | + with open(path, encoding="utf-8") as f: |
| 65 | + data = yaml.safe_load(f) |
| 66 | + queries = data.get("queries", []) |
| 67 | + if category: |
| 68 | + queries = [q for q in queries if q.get("category") == category] |
| 69 | + return queries |
| 70 | + |
| 71 | + |
| 72 | +@pytest.fixture |
| 73 | +def known_tools() -> list[str]: |
| 74 | + """Tools available on the CrewAI Websearch agent.""" |
| 75 | + return ["Web Search"] |
| 76 | + |
| 77 | + |
| 78 | +@pytest.fixture |
| 79 | +def crewai_websearch_thresholds(eval_config: dict[str, Any]) -> dict[str, Any]: |
| 80 | + """Load the crewai_websearch section from the shared thresholds config.""" |
| 81 | + return eval_config["crewai_websearch"] |
| 82 | + |
| 83 | + |
| 84 | +@pytest.fixture |
| 85 | +def run_eval( |
| 86 | + agent_url: str, http_client: httpx.AsyncClient |
| 87 | +) -> Callable[..., Coroutine[Any, Any, TaskResult]]: |
| 88 | + """Run eval with automatic MLflow enrichment when available. |
| 89 | +
|
| 90 | + MLflow trace enrichment is the primary mechanism for extracting |
| 91 | + tool_calls — CrewAI does not expose them in the HTTP response body. |
| 92 | + The MLflowTraceClient pulls SpanType.TOOL spans from traces into |
| 93 | + TaskResult.tool_calls, enabling full scorer coverage. |
| 94 | + """ |
| 95 | + mlflow = None |
| 96 | + if MLflowTraceClient is not None: |
| 97 | + tracking_uri = os.environ.get("MLFLOW_TRACKING_URI") |
| 98 | + experiment = os.environ.get("MLFLOW_EXPERIMENT_NAME") |
| 99 | + if tracking_uri and experiment: |
| 100 | + mlflow = MLflowTraceClient(tracking_uri, experiment) |
| 101 | + |
| 102 | + async def _run( |
| 103 | + query: str, |
| 104 | + expected_tools: list[str] | None = None, |
| 105 | + timeout_seconds: float = 30.0, |
| 106 | + max_tokens_budget: int | None = None, |
| 107 | + model: str | None = None, |
| 108 | + stream: bool = False, |
| 109 | + ) -> TaskResult: |
| 110 | + config = TaskConfig( |
| 111 | + agent_url=agent_url, |
| 112 | + query=query, |
| 113 | + expected_tools=expected_tools, |
| 114 | + timeout_seconds=timeout_seconds, |
| 115 | + max_tokens_budget=max_tokens_budget, |
| 116 | + model=model, |
| 117 | + stream=stream, |
| 118 | + ) |
| 119 | + request_start_ms = int(time.time() * 1000) |
| 120 | + result = await run_task(config, client=http_client) |
| 121 | + |
| 122 | + if mlflow is not None and result.success: |
| 123 | + try: |
| 124 | + await asyncio.to_thread( |
| 125 | + mlflow.enrich_eval_result, result, since_ms=request_start_ms |
| 126 | + ) |
| 127 | + except Exception: |
| 128 | + logging.getLogger(__name__).debug( |
| 129 | + "MLflow enrichment failed — continuing without trace data", |
| 130 | + exc_info=True, |
| 131 | + ) |
| 132 | + |
| 133 | + return result |
| 134 | + |
| 135 | + return _run |
0 commit comments