Spaces:
Runtime error
Runtime error
Download src/cli/runner.py from BattleFiven/ai-tester-platform: direct link, hf CLI and curl.
- Browser
- Download file 16.5 kB
-
https://huggingface.co/spaces/BattleFiven/ai-tester-platform/resolve/main/src/cli/runner.py
- Command line
-
hf download hf://spaces/BattleFiven/ai-tester-platform/src/cli/runner.py
-
curl -L -o runner.py https://huggingface.co/spaces/BattleFiven/ai-tester-platform/resolve/main/src/cli/runner.py
16.5 kB
| #!/usr/bin/env python3 | |
| """Local runner CLI. | |
| Runs Playwright locally but persists results to a cloud backend (FastAPI + Supabase). | |
| This keeps secrets (OpenAI key, DB password, Supabase service role) server-side. | |
| """ | |
| from __future__ import annotations | |
| import json | |
| import mimetypes | |
| import os | |
| from pathlib import Path | |
| from typing import Any, Callable, Dict, List, Optional | |
| import httpx | |
| import typer | |
| from rich.console import Console | |
| from src.core.ai_client import AIClient, get_effective_session_prompt | |
| from src.core.rag_evaluator import RAGEvaluator | |
| from src.core.test_engine import TestEngine | |
| from src.core.tone_evaluator import ToneEvaluator | |
| from src.core.turn_evaluator import TurnEvaluator | |
| from src.models import Bot, Persona, Scenario, TestResult, TestSession | |
| from src.utils.env import env_bool | |
| app = typer.Typer(help="Run test sessions locally and push results to the cloud backend.") | |
| console = Console() | |
| def _normalize_backend_url(url: str) -> str: | |
| url = (url or "").strip() | |
| if not url: | |
| raise typer.BadParameter("Missing backend URL") | |
| if not url.startswith("http://") and not url.startswith("https://"): | |
| url = "https://" + url | |
| return url.rstrip("/") | |
| def _auth_headers(token: str) -> Dict[str, str]: | |
| token = (token or "").strip() | |
| if not token: | |
| raise typer.BadParameter("Missing auth token (Supabase access_token)") | |
| return {"Authorization": f"Bearer {token}"} | |
| def _build_models(payload: dict) -> tuple[TestSession, Bot, List[Scenario], List[Persona], List[dict]]: | |
| session = TestSession(**(payload.get("session") or {})) | |
| bot = Bot(**(payload.get("bot") or {})) | |
| scenarios = [Scenario(**s) for s in (payload.get("scenarios") or [])] | |
| personas = [Persona(**p) for p in (payload.get("personas") or [])] | |
| links = payload.get("links") or [] | |
| if not isinstance(links, list): | |
| links = [] | |
| return session, bot, scenarios, personas, links | |
| def _group_by_persona( | |
| scenarios: List[Scenario], | |
| personas: List[Persona], | |
| links: List[dict], | |
| ) -> Dict[str, dict]: | |
| scenarios_by_id = {str(s.id): s for s in scenarios} | |
| personas_by_id = {str(p.id): p for p in personas} | |
| groups: Dict[str, dict] = {} | |
| seen = set() | |
| for link in links: | |
| scenario_id = str(link.get("scenario_id") or "") | |
| persona_id = str(link.get("persona_id") or "") | |
| if not scenario_id or not persona_id: | |
| continue | |
| key = (scenario_id, persona_id) | |
| if key in seen: | |
| continue | |
| seen.add(key) | |
| scenario = scenarios_by_id.get(scenario_id) | |
| persona = personas_by_id.get(persona_id) | |
| if not scenario or not persona: | |
| continue | |
| groups.setdefault(persona_id, {"persona": persona, "scenarios": []})["scenarios"].append(scenario) | |
| return groups | |
| def _scenario_goal_text(scenario: Scenario) -> str: | |
| description = str(getattr(scenario, "description", "") or "").strip() | |
| if description: | |
| return description | |
| success_criteria = getattr(scenario, "success_criteria", None) | |
| expected_intent = ( | |
| str(getattr(success_criteria, "expected_intent", "") or "").strip() | |
| if success_criteria | |
| else "" | |
| ) | |
| if expected_intent: | |
| return expected_intent | |
| return f"Complete scenario '{scenario.name}'." | |
| def _build_group_prompt(persona: Persona, scenarios: List[Scenario]) -> str: | |
| overview = [] | |
| for idx, scenario in enumerate(list(scenarios or [])[:12], start=1): | |
| overview.append(f"{idx}. {scenario.name}: {_scenario_goal_text(scenario)}") | |
| if len(scenarios or []) > 12: | |
| overview.append(f"... plus {len(scenarios) - 12} additional scenario(s) in this run.") | |
| return AIClient.build_persona_system_prompt(persona=persona, scenario_overview=overview) | |
| def _upload_screenshot( | |
| client: httpx.Client, | |
| session_id: str, | |
| *, | |
| path: str, | |
| result_id: str, | |
| label: str, | |
| ) -> Optional[str]: | |
| p = Path(path) | |
| if not p.exists() or not p.is_file(): | |
| return None | |
| # Live preview is overwritten constantly; never persist it. | |
| if p.name.lower().startswith("live."): | |
| return None | |
| mime = mimetypes.guess_type(str(p))[0] or "application/octet-stream" | |
| with p.open("rb") as f: | |
| files = {"file": (p.name, f, mime)} | |
| r = client.post( | |
| f"/api/sessions/{session_id}/local/upload-screenshot", | |
| params={"result_id": result_id, "label": label}, | |
| files=files, | |
| timeout=120.0, | |
| ) | |
| r.raise_for_status() | |
| data = r.json() or {} | |
| ref = data.get("ref") | |
| return str(ref) if ref else None | |
| def _replace_screenshots_with_refs( | |
| client: httpx.Client, | |
| session_id: str, | |
| result: TestResult, | |
| ) -> None: | |
| result_id = str(result.id) | |
| # result.screenshot_urls | |
| new_urls: List[str] = [] | |
| for raw in (result.screenshot_urls or []): | |
| if not raw: | |
| continue | |
| ref = _upload_screenshot( | |
| client, | |
| session_id, | |
| path=str(raw), | |
| result_id=result_id, | |
| label=Path(str(raw)).stem or "evidence", | |
| ) | |
| if ref: | |
| new_urls.append(ref) | |
| result.screenshot_urls = new_urls | |
| # steps_results[*].screenshot | |
| for step in (result.steps_results or []): | |
| if not isinstance(step, dict): | |
| continue | |
| raw = step.get("screenshot") | |
| if not raw: | |
| continue | |
| label = str(step.get("step_id") or Path(str(raw)).stem or "turn") | |
| ref = _upload_screenshot(client, session_id, path=str(raw), result_id=result_id, label=label) | |
| if ref: | |
| step["screenshot"] = ref | |
| else: | |
| step.pop("screenshot", None) | |
| # scenario_results[*].turns[*].screenshot | |
| scenario_map = result.scenario_results if isinstance(result.scenario_results, dict) else {} | |
| for scenario in scenario_map.values(): | |
| if not isinstance(scenario, dict): | |
| continue | |
| turns = scenario.get("turns") | |
| if not isinstance(turns, list): | |
| continue | |
| for turn in turns: | |
| if not isinstance(turn, dict): | |
| continue | |
| raw = turn.get("screenshot") | |
| if not raw: | |
| continue | |
| label = str(turn.get("step_id") or turn.get("turn") or Path(str(raw)).stem or "turn") | |
| ref = _upload_screenshot(client, session_id, path=str(raw), result_id=result_id, label=label) | |
| if ref: | |
| turn["screenshot"] = ref | |
| else: | |
| turn.pop("screenshot", None) | |
| # conversation_log (optional) | |
| if result.conversation_log: | |
| try: | |
| data = json.loads(result.conversation_log) | |
| except Exception: | |
| data = None | |
| if isinstance(data, list): | |
| changed = False | |
| for turn in data: | |
| if not isinstance(turn, dict) or not turn.get("screenshot"): | |
| continue | |
| raw = turn.get("screenshot") | |
| ref = _upload_screenshot( | |
| client, | |
| session_id, | |
| path=str(raw), | |
| result_id=result_id, | |
| label=str(turn.get("step_id") or turn.get("turn") or Path(str(raw)).stem or "turn"), | |
| ) | |
| if ref: | |
| turn["screenshot"] = ref | |
| changed = True | |
| else: | |
| turn.pop("screenshot", None) | |
| changed = True | |
| if changed: | |
| result.conversation_log = json.dumps(data, ensure_ascii=False, default=str) | |
| def run_session_local( | |
| *, | |
| session_id: str, | |
| backend_url: str, | |
| token: str, | |
| headless: bool = False, | |
| output_dir: str = "./output/local_runner", | |
| event_handler: Optional[Callable[[Dict[str, Any]], None]] = None, | |
| stop_requested: Optional[Callable[[], bool]] = None, | |
| ): | |
| """Run a cloud-created session locally and ingest results back into the cloud.""" | |
| def _emit(event: Dict[str, Any]) -> None: | |
| if not event_handler: | |
| return | |
| try: | |
| event_handler(dict(event)) | |
| except Exception: | |
| # Do not break execution because of UI/event bridge issues. | |
| pass | |
| backend = _normalize_backend_url(backend_url) | |
| headers = _auth_headers(token) | |
| # Fetch run configuration | |
| console.print(f"[dim]Fetching run config from {backend}...[/dim]") | |
| _emit({"type": "log", "level": "info", "message": f"Fetching run config from {backend}..."}) | |
| with httpx.Client(base_url=backend, headers=headers, timeout=60.0) as client: | |
| r = client.get(f"/api/sessions/{session_id}/run-config") | |
| r.raise_for_status() | |
| payload = r.json() or {} | |
| session, bot, scenarios, personas, links = _build_models(payload) | |
| groups = _group_by_persona(scenarios, personas, links) | |
| if not groups: | |
| raise typer.Exit("No runnable scenario/persona links found for this session.") | |
| # AI proxy: use server-side keys, but pass the user's JWT as the bearer token. | |
| ai = AIClient( | |
| api_key=token, | |
| base_url=f"{backend}/api/ai/openai/v1", | |
| model=os.getenv("OPENAI_MODEL", "gpt-4.1-mini"), | |
| temperature=float(os.getenv("OPENAI_TEMPERATURE", "0.2")), | |
| max_tokens=int(os.getenv("OPENAI_MAX_TOKENS", "1000")), | |
| timeout=int(os.getenv("OPENAI_TIMEOUT", "60")), | |
| ) | |
| rag = RAGEvaluator(ai) | |
| tone = ToneEvaluator(ai) | |
| turn_eval_enabled = env_bool("ENABLE_TURN_EVALUATOR", True) | |
| turn_eval = None | |
| if turn_eval_enabled: | |
| from src.core.ai_client import get_evaluator_client_from_env | |
| evaluator_ai = get_evaluator_client_from_env() | |
| turn_eval = TurnEvaluator(evaluator_ai) | |
| out_root = Path(output_dir) / str(session.id) | |
| out_root.mkdir(parents=True, exist_ok=True) | |
| engine = TestEngine( | |
| ai_client=ai, | |
| rag_evaluator=rag, | |
| tone_evaluator=tone, | |
| turn_evaluator=turn_eval, | |
| output_dir=str(out_root), | |
| event_handler=_emit, | |
| stop_requested=stop_requested, | |
| max_messages=(session.max_turns or session.max_messages), | |
| persona_system_prompt_override=get_effective_session_prompt( | |
| getattr(session, "config", None) | |
| ), | |
| ) | |
| base_prompt_override = engine.persona_system_prompt_override | |
| results: List[TestResult] = [] | |
| messages_sent_total = 0 | |
| collected_errors: List[str] = [] | |
| total_tests = sum(len(g.get("scenarios", [])) for g in groups.values()) | |
| _emit({"type": "status", "status": "running", "total_tests": total_tests}) | |
| _emit({"type": "log", "level": "info", "message": f"Starting session with {total_tests} test(s)."}) | |
| local_stop_requested = False | |
| for group in groups.values(): | |
| if stop_requested and stop_requested(): | |
| local_stop_requested = True | |
| _emit({"type": "log", "level": "warning", "message": "Stop requested by operator. Finalizing partial results..."}) | |
| break | |
| persona: Persona = group["persona"] | |
| scenario_list: List[Scenario] = group["scenarios"] | |
| engine.persona_system_prompt_override = ( | |
| base_prompt_override or _build_group_prompt(persona, scenario_list) | |
| ) | |
| console.print(f"\n[cyan]Running {len(scenario_list)} scenario(s) as {persona.name}[/cyan]") | |
| _emit({ | |
| "type": "progress", | |
| "scenario": f"{len(scenario_list)} scenarios", | |
| "persona": persona.name, | |
| }) | |
| _emit({"type": "log", "level": "info", "message": f"Running {len(scenario_list)} scenario(s) as {persona.name}"}) | |
| result = engine.run_multi_scenario_test( | |
| bot=bot, | |
| scenarios=scenario_list, | |
| persona=persona, | |
| session=session, | |
| headless=headless, | |
| ) | |
| messages_sent_total += int(getattr(engine, "messages_sent_count", 0) or 0) | |
| result_status = str(getattr(result, "status", "")).strip().lower() | |
| if result_status in {"error", "failed", "cancelled", "stopped"}: | |
| err = str(getattr(result, "error_message", "") or getattr(result, "failure_reason", "") or "").strip() | |
| if err: | |
| collected_errors.append(err) | |
| if result_status == "stopped": | |
| local_stop_requested = True | |
| # Upload screenshots and replace paths with sb:// refs. | |
| _replace_screenshots_with_refs(client, session_id, result) | |
| results.append(result) | |
| if local_stop_requested: | |
| _emit({"type": "log", "level": "warning", "message": "Session interrupted manually. Uploading partial results..."}) | |
| break | |
| if not results: | |
| stop_message = "Stopped before any scenario turn was recorded." | |
| _emit({"type": "log", "level": "warning", "message": stop_message}) | |
| try: | |
| client.post(f"/api/sessions/{session_id}/stop", timeout=30.0) | |
| current = client.get(f"/api/sessions/{session_id}", timeout=30.0) | |
| current.raise_for_status() | |
| updated = current.json() or {} | |
| except Exception: | |
| updated = { | |
| "status": "cancelled", | |
| "passed": 0, | |
| "failed": 0, | |
| "error_message": stop_message, | |
| } | |
| _emit({ | |
| "type": "status", | |
| "status": str(updated.get("status") or "cancelled"), | |
| "passed": int(updated.get("passed") or 0), | |
| "failed": int(updated.get("failed") or 0), | |
| "message": updated.get("error_message") or stop_message, | |
| }) | |
| return updated | |
| ingest_payload = { | |
| "results": [r.model_dump(mode="json") for r in results], | |
| "messages_sent": messages_sent_total, | |
| } | |
| if local_stop_requested: | |
| ingest_payload["status"] = "manual_completed" | |
| if collected_errors: | |
| unique_errors = list(dict.fromkeys(collected_errors)) | |
| ingest_payload["error_message"] = " | ".join(unique_errors)[:1800] | |
| console.print("\n[dim]Ingesting results into cloud...[/dim]") | |
| _emit({"type": "log", "level": "info", "message": "Ingesting results into cloud..."}) | |
| r = client.post(f"/api/sessions/{session_id}/local/ingest", json=ingest_payload, timeout=120.0) | |
| r.raise_for_status() | |
| updated = r.json() or {} | |
| # Ensure caller receives an explicit failure reason when present on results. | |
| if not updated.get("error_message") and collected_errors: | |
| unique_errors = list(dict.fromkeys(collected_errors)) | |
| updated["error_message"] = " | ".join(unique_errors)[:1800] | |
| console.print("[green]✓ Completed local run and ingested results.[/green]") | |
| console.print(f"[dim]Session status: {updated.get('status')} | passed={updated.get('passed')} failed={updated.get('failed')}[/dim]") | |
| if updated.get("error_message"): | |
| console.print(f"[yellow]Session detail: {updated.get('error_message')}[/yellow]") | |
| _emit({ | |
| "type": "status", | |
| "status": str(updated.get("status") or "completed"), | |
| "passed": int(updated.get("passed") or 0), | |
| "failed": int(updated.get("failed") or 0), | |
| "message": updated.get("error_message") or "Local runner completed", | |
| }) | |
| return updated | |
| def run_session( | |
| session_id: str = typer.Argument(..., help="Test session ID (UUID)"), | |
| backend_url: str = typer.Option(..., "--backend-url", envvar="AI_TESTER_BACKEND_URL"), | |
| token: str = typer.Option(..., "--token", envvar="AI_TESTER_AUTH_TOKEN"), | |
| headless: bool = typer.Option(False, "--headless", help="Run browser headless (default: false)"), | |
| output_dir: str = typer.Option("./output/local_runner", "--output-dir"), | |
| ): | |
| """CLI entrypoint for local run + ingest.""" | |
| run_session_local( | |
| session_id=session_id, | |
| backend_url=backend_url, | |
| token=token, | |
| headless=headless, | |
| output_dir=output_dir, | |
| ) | |
| if __name__ == "__main__": | |
| app() | |