|
| 1 | +"""Fixtures for LangGraph Agentic RAG agent evals.""" |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +import asyncio |
| 6 | +import logging |
| 7 | +import os |
| 8 | +import time |
| 9 | +import warnings |
| 10 | +from pathlib import Path |
| 11 | +from typing import Any, AsyncGenerator, Callable, Coroutine |
| 12 | + |
| 13 | +import httpx |
| 14 | +import pytest |
| 15 | +import yaml |
| 16 | +from harness.runner import TaskConfig, TaskResult, run_task |
| 17 | + |
| 18 | +try: |
| 19 | + from harness.mlflow_client import MLflowTraceClient |
| 20 | +except ImportError: |
| 21 | + MLflowTraceClient = None # type: ignore[misc,assignment] |
| 22 | + |
| 23 | + |
| 24 | +RETRIEVER_EVIDENCE = [ |
| 25 | + "langchain", |
| 26 | + "langgraph", |
| 27 | + "milvus", |
| 28 | + "vector database", |
| 29 | + "embedding", |
| 30 | +] |
| 31 | + |
| 32 | + |
| 33 | +def _find_repo_root() -> Path: |
| 34 | + """Walk up from this file to find the repository root. |
| 35 | +
|
| 36 | + Uses the presence of tests/behavioral/configs/thresholds.yaml as |
| 37 | + the sentinel to distinguish the repo root from agent-level directories |
| 38 | + that also contain pyproject.toml and tests/behavioral/. |
| 39 | + """ |
| 40 | + path = Path(__file__).resolve().parent |
| 41 | + while path.parent != path: |
| 42 | + candidate = path / "tests" / "behavioral" / "configs" / "thresholds.yaml" |
| 43 | + if candidate.is_file(): |
| 44 | + return path |
| 45 | + path = path.parent |
| 46 | + raise FileNotFoundError( |
| 47 | + "Could not find repo root (no tests/behavioral/configs/thresholds.yaml)" |
| 48 | + ) |
| 49 | + |
| 50 | + |
| 51 | +def load_golden(category: str | None = None) -> list[dict[str, Any]]: |
| 52 | + """Load golden queries from the fixtures directory, optionally filtering by category.""" |
| 53 | + path = Path(__file__).parent / "fixtures" / "golden_queries.yaml" |
| 54 | + with open(path, encoding="utf-8") as f: |
| 55 | + data = yaml.safe_load(f) |
| 56 | + queries = data.get("queries", []) |
| 57 | + if category: |
| 58 | + queries = [q for q in queries if q.get("category") == category] |
| 59 | + return queries |
| 60 | + |
| 61 | + |
| 62 | +@pytest.fixture |
| 63 | +def agent_url() -> str: |
| 64 | + """Agentic RAG agent URL from env var or default localhost:8000.""" |
| 65 | + return os.environ.get("AGENTIC_RAG_AGENT_URL", "http://localhost:8000") |
| 66 | + |
| 67 | + |
| 68 | +@pytest.fixture |
| 69 | +async def http_client() -> AsyncGenerator[httpx.AsyncClient, None]: |
| 70 | + """Provide an async httpx client that is closed after the test.""" |
| 71 | + async with httpx.AsyncClient() as client: |
| 72 | + yield client |
| 73 | + |
| 74 | + |
| 75 | +@pytest.fixture |
| 76 | +def eval_config() -> dict[str, Any]: |
| 77 | + """Load threshold configuration from the shared configs directory.""" |
| 78 | + config_path = ( |
| 79 | + _find_repo_root() / "tests" / "behavioral" / "configs" / "thresholds.yaml" |
| 80 | + ) |
| 81 | + with open(config_path, encoding="utf-8") as f: |
| 82 | + return yaml.safe_load(f) |
| 83 | + |
| 84 | + |
| 85 | +@pytest.fixture |
| 86 | +def known_tools() -> list[str]: |
| 87 | + """Tools available on the LangGraph Agentic RAG agent.""" |
| 88 | + return ["retriever"] |
| 89 | + |
| 90 | + |
| 91 | +@pytest.fixture |
| 92 | +def agentic_rag_thresholds(eval_config: dict[str, Any]) -> dict[str, Any]: |
| 93 | + """Load the agentic_rag section from the shared thresholds config.""" |
| 94 | + return eval_config["agentic_rag"] |
| 95 | + |
| 96 | + |
| 97 | +@pytest.fixture |
| 98 | +def run_eval( |
| 99 | + agent_url: str, http_client: httpx.AsyncClient |
| 100 | +) -> Callable[..., Coroutine[Any, Any, TaskResult]]: |
| 101 | + """Run eval with automatic MLflow enrichment when available. |
| 102 | +
|
| 103 | + Always uses stream=False — the Agentic RAG agent does not expose |
| 104 | + tool_calls in the response context; MLflow traces are the only |
| 105 | + source for tool-call data. |
| 106 | + """ |
| 107 | + mlflow = None |
| 108 | + if MLflowTraceClient is not None: |
| 109 | + tracking_uri = os.environ.get("MLFLOW_TRACKING_URI") |
| 110 | + experiment = os.environ.get("MLFLOW_EXPERIMENT_NAME") |
| 111 | + if tracking_uri and experiment: |
| 112 | + mlflow = MLflowTraceClient(tracking_uri, experiment) |
| 113 | + |
| 114 | + async def _run( |
| 115 | + query: str, |
| 116 | + expected_tools: list[str] | None = None, |
| 117 | + timeout_seconds: float = 30.0, |
| 118 | + max_tokens_budget: int | None = None, |
| 119 | + model: str | None = None, |
| 120 | + stream: bool = False, |
| 121 | + ) -> TaskResult: |
| 122 | + config = TaskConfig( |
| 123 | + agent_url=agent_url, |
| 124 | + query=query, |
| 125 | + expected_tools=expected_tools, |
| 126 | + timeout_seconds=timeout_seconds, |
| 127 | + max_tokens_budget=max_tokens_budget, |
| 128 | + model=model, |
| 129 | + stream=False, |
| 130 | + ) |
| 131 | + request_start_ms = int(time.time() * 1000) |
| 132 | + result = await run_task(config, client=http_client) |
| 133 | + |
| 134 | + if mlflow is not None and result.success: |
| 135 | + try: |
| 136 | + await asyncio.to_thread( |
| 137 | + mlflow.enrich_eval_result, result, since_ms=request_start_ms |
| 138 | + ) |
| 139 | + except Exception: |
| 140 | + msg = "MLflow enrichment failed — tool scoring will degrade to content heuristics" |
| 141 | + logging.getLogger(__name__).warning(msg, exc_info=True) |
| 142 | + warnings.warn(msg, stacklevel=2) |
| 143 | + |
| 144 | + return result |
| 145 | + |
| 146 | + return _run |
0 commit comments