|
| 1 | +"""Fixtures for AutoGen MCP 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 | + """AutoGen MCP agent URL from AUTOGEN_MCP_AGENT_URL env var or default localhost:8000.""" |
| 26 | + return os.environ.get("AUTOGEN_MCP_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 | + raise FileNotFoundError( |
| 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 | +def load_golden(category: str | None = None) -> list[dict[str, Any]]: |
| 59 | + """Load golden queries from the fixtures directory, optionally filtering by category.""" |
| 60 | + path = Path(__file__).parent / "fixtures" / "golden_queries.yaml" |
| 61 | + with open(path, encoding="utf-8") as f: |
| 62 | + data = yaml.safe_load(f) |
| 63 | + queries = data.get("queries", []) |
| 64 | + if category: |
| 65 | + queries = [q for q in queries if q.get("category") == category] |
| 66 | + return queries |
| 67 | + |
| 68 | + |
| 69 | +@pytest.fixture |
| 70 | +def known_tools() -> list[str]: |
| 71 | + """Tools available on the AutoGen MCP agent (excluding invoke_churn).""" |
| 72 | + return ["add", "sub"] |
| 73 | + |
| 74 | + |
| 75 | +@pytest.fixture |
| 76 | +def autogen_mcp_thresholds(eval_config: dict[str, Any]) -> dict[str, Any]: |
| 77 | + """Load the autogen_mcp section from the shared thresholds config.""" |
| 78 | + return eval_config["autogen_mcp"] |
| 79 | + |
| 80 | + |
| 81 | +@pytest.fixture |
| 82 | +def run_eval( |
| 83 | + agent_url: str, http_client: httpx.AsyncClient |
| 84 | +) -> Callable[..., Coroutine[Any, Any, TaskResult]]: |
| 85 | + """Run eval with automatic MLflow enrichment when available. |
| 86 | +
|
| 87 | + Overrides the root run_eval fixture to add MLflow trace data |
| 88 | + (tool calls, token usage) after each request. |
| 89 | + Always uses stream=False — the AutoGen MCP agent exposes tool_invocations |
| 90 | + in non-streaming JSON but not in standard SSE delta.tool_calls. |
| 91 | + """ |
| 92 | + mlflow = None |
| 93 | + if MLflowTraceClient is not None: |
| 94 | + tracking_uri = os.environ.get("MLFLOW_TRACKING_URI") |
| 95 | + experiment = os.environ.get("MLFLOW_EXPERIMENT_NAME") |
| 96 | + if tracking_uri and experiment: |
| 97 | + mlflow = MLflowTraceClient(tracking_uri, experiment) |
| 98 | + |
| 99 | + async def _run( |
| 100 | + query: str, |
| 101 | + expected_tools: list[str] | None = None, |
| 102 | + timeout_seconds: float = 30.0, |
| 103 | + max_tokens_budget: int | None = None, |
| 104 | + model: str | None = None, |
| 105 | + ) -> TaskResult: |
| 106 | + config = TaskConfig( |
| 107 | + agent_url=agent_url, |
| 108 | + query=query, |
| 109 | + expected_tools=expected_tools, |
| 110 | + timeout_seconds=timeout_seconds, |
| 111 | + max_tokens_budget=max_tokens_budget, |
| 112 | + model=model, |
| 113 | + stream=False, |
| 114 | + ) |
| 115 | + request_start_ms = int(time.time() * 1000) |
| 116 | + result = await run_task(config, client=http_client) |
| 117 | + |
| 118 | + if mlflow is not None and result.success: |
| 119 | + try: |
| 120 | + await asyncio.to_thread( |
| 121 | + mlflow.enrich_eval_result, result, since_ms=request_start_ms |
| 122 | + ) |
| 123 | + except Exception: |
| 124 | + logging.getLogger(__name__).debug( |
| 125 | + "MLflow enrichment failed — continuing without trace data", |
| 126 | + exc_info=True, |
| 127 | + ) |
| 128 | + |
| 129 | + return result |
| 130 | + |
| 131 | + return _run |
0 commit comments