|
| 1 | +import json |
| 2 | +import logging |
| 3 | +from typing import List, Type |
| 4 | + |
| 5 | +from crewai.tools import BaseTool, EnvVar |
| 6 | +from pydantic import BaseModel, Field |
| 7 | + |
| 8 | +logger = logging.getLogger(__file__) |
| 9 | + |
| 10 | +_EXAMPLES = ( |
| 11 | + "backtest -> {'sr': 0.12, 'T': 250, 'n_trials': 100}; " |
| 12 | + "model_gap -> {'n': 2000, 'p1': 0.85, 'p2': 0.80}; " |
| 13 | + "subset_win -> {'p': 0.03, 'n_tests': 20}; " |
| 14 | + "judge_bias -> {'wins': 68, 'n': 100}" |
| 15 | +) |
| 16 | + |
| 17 | + |
| 18 | +class NumGuardToolInput(BaseModel): |
| 19 | + kind: str = Field( |
| 20 | + ..., |
| 21 | + description="The claim to check: 'backtest' (Deflated Sharpe Ratio), 'model_gap' (accuracy gap " |
| 22 | + "power), 'subset_win' (multiple-testing correction), or 'judge_bias' (LLM-judge preference).", |
| 23 | + ) |
| 24 | + params: dict = Field( |
| 25 | + ..., |
| 26 | + description=f"Inputs for the check. Examples: {_EXAMPLES}.", |
| 27 | + ) |
| 28 | + |
| 29 | + |
| 30 | +class NumGuardTool(BaseTool): |
| 31 | + """Verify a number before an agent asserts it. |
| 32 | +
|
| 33 | + Routes a numeric claim to the statistical check that most directly tests it and returns whether it survives |
| 34 | + plus an honest verdict — so an agent can gate a backtest Sharpe, an A/B accuracy gap, a cherry-picked subset |
| 35 | + win, or an LLM-judge preference before reporting it as real. Backed by the open-source ``numguard`` library |
| 36 | + (Deflated Sharpe Ratio + eval-integrity statistics). |
| 37 | + """ |
| 38 | + |
| 39 | + name: str = "NumGuard Number Verifier" |
| 40 | + description: str = ( |
| 41 | + "Verify a statistical claim before asserting it. Give it a 'kind' (backtest / model_gap / subset_win / " |
| 42 | + "judge_bias) and 'params'; it returns whether the number survives its check and the honest verdict to " |
| 43 | + "report instead. Use it before you state a backtest Sharpe, an A/B result, a subset win, or a judge " |
| 44 | + "preference as a fact." |
| 45 | + ) |
| 46 | + args_schema: Type[BaseModel] = NumGuardToolInput |
| 47 | + package_dependencies: List[str] = ["numguard"] |
| 48 | + env_vars: List[EnvVar] = [] |
| 49 | + |
| 50 | + def _run(self, kind: str, params: dict) -> str: |
| 51 | + try: |
| 52 | + from numguard.guard import check |
| 53 | + except ImportError: |
| 54 | + return "numguard is not installed. Run: pip install numguard" |
| 55 | + try: |
| 56 | + verdict = check(kind, **(params or {})) |
| 57 | + except Exception as e: |
| 58 | + logger.error(f"NumGuardTool error: {e}") |
| 59 | + return f"Could not verify claim '{kind}': {e}" |
| 60 | + survives = bool(verdict.get("survives")) |
| 61 | + line = verdict.get("verdict") or ("survives" if survives else "flagged") |
| 62 | + return json.dumps({"survives": survives, "verdict": line, "detail": verdict}, default=str) |
0 commit comments