Spaces:
Runtime error
Runtime error
Download src/api/manual_test_runner.py from BattleFiven/ai-tester-platform: direct link, hf CLI and curl.
- Browser
- Download file 17.4 kB
-
https://huggingface.co/spaces/BattleFiven/ai-tester-platform/resolve/main/src/api/manual_test_runner.py
- Command line
-
hf download hf://spaces/BattleFiven/ai-tester-platform/src/api/manual_test_runner.py
-
curl -L -o manual_test_runner.py https://huggingface.co/spaces/BattleFiven/ai-tester-platform/resolve/main/src/api/manual_test_runner.py
17.4 kB
| """ | |
| Manual Test Runner - For interactive user testing with metric tracking. | |
| User interacts directly with the bot, system tracks metrics in real-time. | |
| """ | |
| import json | |
| import threading | |
| import time | |
| from datetime import datetime | |
| from pathlib import Path | |
| from typing import Any, Dict, List, Optional | |
| from uuid import UUID, uuid4 | |
| from rich.console import Console | |
| from src.api.session_runner import session_event_bus | |
| from src.core.ai_client import get_ai_client_from_env | |
| from src.core.browser_controller import BrowserController | |
| from src.core.turn_evaluator import TurnEvaluator | |
| from src.db import BotRepository, SessionRepository, get_db | |
| from src.models import SessionStatus | |
| console = Console() | |
| class ManualTestRunner: | |
| """Runner for manual interactive tests with real-time metric tracking.""" | |
| def __init__(self): | |
| self.active_sessions: Dict[str, Any] = {} # session_id -> session data | |
| self.lock = threading.Lock() | |
| self._evaluator = None | |
| def evaluator(self): | |
| """Lazy initialization of dialogic turn evaluator (uses dedicated judge if configured).""" | |
| if self._evaluator is None: | |
| from src.core.ai_client import get_evaluator_client_from_env | |
| self._evaluator = TurnEvaluator(get_evaluator_client_from_env()) | |
| return self._evaluator | |
| def start(self, session_id: str, headless: bool = False) -> bool: | |
| """Start a manual test session.""" | |
| with self.lock: | |
| if session_id in self.active_sessions: | |
| return False # Already running | |
| # Get session and bot info | |
| db = get_db() | |
| with db.get_session() as session: | |
| repo = SessionRepository(session) | |
| bot_repo = BotRepository(session) | |
| test_session = repo.get_session(UUID(session_id)) | |
| if not test_session: | |
| console.print(f"[red]Session {session_id} not found[/red]") | |
| return False | |
| bot = bot_repo.get_by_id(test_session.bot_id) | |
| if not bot: | |
| console.print(f"[red]Bot for session {session_id} not found[/red]") | |
| return False | |
| # Initialize browser | |
| output_dir = Path("./output") / session_id | |
| output_dir.mkdir(parents=True, exist_ok=True) | |
| browser = BrowserController( | |
| selectors=bot.selectors.model_dump(), | |
| output_dir=str(output_dir), | |
| headless=headless, | |
| slow_mo=0, | |
| ) | |
| if not browser.start(str(bot.url)): | |
| console.print("[red]Failed to start browser for manual test[/red]") | |
| return False | |
| # Click "New Chat" if configured | |
| if bot.auto_click_new_chat: | |
| clicked = browser.click_new_chat() | |
| if clicked: | |
| browser.wait(1.0) | |
| # Store session data | |
| self.active_sessions[session_id] = { | |
| "browser": browser, | |
| "session": test_session, | |
| "bot": bot, | |
| "output_dir": output_dir, | |
| "interactions": [], | |
| "metrics": [], | |
| "start_time": datetime.now(), | |
| "stop_requested": False, | |
| } | |
| # Note: Automatic tracking disabled due to Playwright thread restrictions | |
| # Frontend should poll /api/sessions/{id}/manual/messages endpoint | |
| # Emit start event | |
| self._emit(session_id, { | |
| "type": "status", | |
| "status": "running", | |
| "message": "Manual test started. Interact with the browser.", | |
| "mode": "manual", | |
| }) | |
| console.print(f"[green]✓ Manual test started: {session_id}[/green]") | |
| return True | |
| def stop(self, session_id: str) -> bool: | |
| """Stop a manual test session and finalize.""" | |
| with self.lock: | |
| if session_id not in self.active_sessions: | |
| return False | |
| session_data = self.active_sessions[session_id] | |
| session_data["stop_requested"] = True | |
| # Finalize metrics | |
| self._finalize_metrics(session_id) | |
| # Cleanup browser | |
| browser = session_data.get("browser") | |
| if browser: | |
| browser.capture_screenshot("final") | |
| browser.cleanup() | |
| # Update database | |
| db = get_db() | |
| with db.get_session() as db_session: | |
| repo = SessionRepository(db_session) | |
| repo.update_session(UUID(session_id), { | |
| "status": SessionStatus.COMPLETED.value, | |
| "completed_at": datetime.now(), | |
| }) | |
| db_session.commit() | |
| # Emit completion | |
| self._emit(session_id, { | |
| "type": "status", | |
| "status": "completed", | |
| "message": "Manual test completed", | |
| "interactions_count": len(session_data["interactions"]), | |
| }) | |
| # Remove from active | |
| del self.active_sessions[session_id] | |
| console.print(f"[green]✓ Manual test stopped: {session_id}[/green]") | |
| return True | |
| def record_interaction(self, session_id: str, interaction_type: str, content: str) -> bool: | |
| """Record a manual interaction (user message or bot response).""" | |
| with self.lock: | |
| if session_id not in self.active_sessions: | |
| return False | |
| session_data = self.active_sessions[session_id] | |
| interaction = { | |
| "id": str(uuid4()), | |
| "timestamp": datetime.now().isoformat(), | |
| "type": interaction_type, # 'user' or 'bot' | |
| "content": content, | |
| "turn": len(session_data["interactions"]) // 2 + 1, | |
| } | |
| session_data["interactions"].append(interaction) | |
| # Emit event | |
| self._emit(session_id, { | |
| "type": "chat", | |
| "sender": interaction_type, | |
| "text": content, | |
| "turn": interaction["turn"], | |
| }) | |
| # If bot message, evaluate it | |
| if interaction_type == "bot": | |
| self._evaluate_response(session_id, content) | |
| console.print(f"[dim]Recorded {interaction_type} message: {content[:50]}...[/dim]") | |
| return True | |
| def get_messages(self, session_id: str) -> List[Dict[str, Any]]: | |
| """Get current chat messages from browser page. Called by API endpoint.""" | |
| with self.lock: | |
| if session_id not in self.active_sessions: | |
| return [] | |
| session_data = self.active_sessions[session_id] | |
| browser = session_data.get("browser") | |
| if not browser or not browser.page: | |
| return [] | |
| try: | |
| messages = browser.get_chat_messages() | |
| if messages: | |
| console.print(f"[dim]Found {len(messages)} messages in browser[/dim]") | |
| for i, m in enumerate(messages[-3:]): | |
| console.print(f" [{i}] {m.get('sender', '?')}: {m.get('text', '')[:40]}...") | |
| return messages if messages else [] | |
| except Exception as e: | |
| console.print(f"[yellow]Error getting messages: {e}[/yellow]") | |
| return [] | |
| def capture_screenshot(self, session_id: str) -> Optional[str]: | |
| """Capture screenshot of browser page.""" | |
| with self.lock: | |
| if session_id not in self.active_sessions: | |
| return None | |
| session_data = self.active_sessions[session_id] | |
| browser = session_data.get("browser") | |
| if not browser or not browser.page: | |
| return None | |
| try: | |
| return browser.capture_screenshot("manual_test") | |
| except Exception as e: | |
| console.print(f"[yellow]Screenshot error: {e}[/yellow]") | |
| return None | |
| def _tracking_loop(self, session_id: str): | |
| """Background loop to detect messages automatically.""" | |
| last_seen_messages = [] # Track last seen messages to detect new ones | |
| while True: | |
| with self.lock: | |
| if session_id not in self.active_sessions: | |
| break | |
| session_data = self.active_sessions[session_id] | |
| if session_data.get("stop_requested"): | |
| break | |
| browser = session_data.get("browser") | |
| if not browser or not browser.page: | |
| time.sleep(1) | |
| continue | |
| # Try to detect new messages | |
| try: | |
| current_messages = browser.get_chat_messages() | |
| if current_messages: | |
| # Find new messages by comparing with last seen | |
| new_messages = [] | |
| for msg in current_messages: | |
| msg_id = f"{msg.get('sender', 'unknown')}:{msg.get('text', '')[:50]}" | |
| if msg_id not in [f"{m.get('sender', 'unknown')}:{m.get('text', '')[:50]}" for m in last_seen_messages]: | |
| new_messages.append(msg) | |
| # Process new messages | |
| for msg in new_messages: | |
| sender = msg.get("sender", "unknown") | |
| text = msg.get("text", "").strip() | |
| if not text: | |
| continue | |
| # Check if already recorded | |
| already_recorded = any( | |
| i["content"] == text and i["type"] == sender | |
| for i in session_data["interactions"][-10:] | |
| ) | |
| if not already_recorded: | |
| # Auto-record the message | |
| interaction = { | |
| "id": str(uuid4()), | |
| "timestamp": datetime.now().isoformat(), | |
| "type": sender, | |
| "content": text, | |
| "turn": len(session_data["interactions"]) // 2 + 1, | |
| } | |
| session_data["interactions"].append(interaction) | |
| # Emit event for UI | |
| self._emit(session_id, { | |
| "type": "chat", | |
| "sender": sender, | |
| "text": text, | |
| "turn": interaction["turn"], | |
| "auto_detected": True, | |
| }) | |
| console.print(f"[dim]Auto-recorded {sender} message: {text[:50]}...[/dim]") | |
| # If bot message, evaluate it | |
| if sender == "bot": | |
| self._evaluate_response(session_id, text) | |
| # Update last seen messages (keep last 20) | |
| last_seen_messages = current_messages[-20:] | |
| except Exception as e: | |
| console.print(f"[yellow]Tracking loop error: {e}[/yellow]") | |
| time.sleep(1.5) # Check every 1.5 seconds | |
| def _evaluate_response(self, session_id: str, bot_response: str): | |
| """Evaluate a bot response using 5 dimensions.""" | |
| session_data = self.active_sessions[session_id] | |
| # Get last user message for context | |
| user_messages = [i for i in session_data["interactions"] if i["type"] == "user"] | |
| last_user_msg = user_messages[-1]["content"] if user_messages else "" | |
| # Get knowledge boundary if available | |
| knowledge = "" | |
| bot = session_data["bot"] | |
| if bot.knowledge_boundary_url: | |
| from src.core.knowledge_boundary import fetch_duolly_boundary | |
| boundary = fetch_duolly_boundary(str(bot.knowledge_boundary_url)) | |
| if boundary: | |
| knowledge = boundary.to_prompt_context() | |
| # Evaluate using the dialogic TurnEvaluator (AIS + intent). | |
| try: | |
| evaluation = self.evaluator.evaluate( | |
| user_query=last_user_msg, | |
| bot_response=bot_response, | |
| knowledge_boundary_text=knowledge or "", | |
| ) | |
| metric = { | |
| "turn": len(session_data["interactions"]) // 2, | |
| "user_message": last_user_msg, | |
| "bot_response": bot_response, | |
| "ais_label": evaluation.ais_label, | |
| "ais_reasoning": evaluation.ais_reasoning, | |
| "intent_label": evaluation.intent_label, | |
| "response_type": evaluation.response_type, | |
| "expected_behavior": evaluation.expected_behavior, | |
| "claims": [c.to_dict() for c in evaluation.claims], | |
| "timestamp": datetime.now().isoformat(), | |
| } | |
| session_data["metrics"].append(metric) | |
| # Emit metrics | |
| self._emit(session_id, { | |
| "type": "metrics", | |
| "metric": metric, | |
| }) | |
| except Exception as e: | |
| console.print(f"[yellow]Evaluation error: {e}[/yellow]") | |
| def _finalize_metrics(self, session_id: str): | |
| """Generate final report with all metrics.""" | |
| session_data = self.active_sessions[session_id] | |
| if not session_data["metrics"]: | |
| return | |
| # Calculate averages | |
| avg_scores = { | |
| "factuality": sum(m["scores"]["factuality"] for m in session_data["metrics"]) / len(session_data["metrics"]), | |
| "relevance": sum(m["scores"]["relevance"] for m in session_data["metrics"]) / len(session_data["metrics"]), | |
| "usefulness": sum(m["scores"]["usefulness"] for m in session_data["metrics"]) / len(session_data["metrics"]), | |
| "coherence": sum(m["scores"]["coherence"] for m in session_data["metrics"]) / len(session_data["metrics"]), | |
| "formatting": sum(m["scores"]["formatting"] for m in session_data["metrics"]) / len(session_data["metrics"]), | |
| "composite": sum(m["scores"]["composite"] for m in session_data["metrics"]) / len(session_data["metrics"]), | |
| } | |
| # Save report | |
| report = { | |
| "session_id": session_id, | |
| "mode": "manual", | |
| "start_time": session_data["start_time"].isoformat(), | |
| "end_time": datetime.now().isoformat(), | |
| "total_interactions": len(session_data["interactions"]), | |
| "average_scores": avg_scores, | |
| "interactions": session_data["interactions"], | |
| "metrics": session_data["metrics"], | |
| } | |
| output_path = session_data["output_dir"] / f"manual_test_{session_id}_report.json" | |
| with open(output_path, "w") as f: | |
| json.dump(report, f, indent=2) | |
| self._emit(session_id, { | |
| "type": "report", | |
| "report_path": str(output_path), | |
| "average_scores": avg_scores, | |
| }) | |
| console.print(f"[green]✓ Report saved: {output_path}[/green]") | |
| def _emit(self, session_id: str, event: Dict[str, Any]): | |
| """Emit event via event bus.""" | |
| try: | |
| # publish is not a coroutine, call directly | |
| session_event_bus.publish(session_id, event) | |
| except Exception as e: | |
| console.print(f"[yellow]Emit error: {e}[/yellow]") | |
| def get_status(self, session_id: str) -> Optional[Dict[str, Any]]: | |
| """Get current status of a manual test session.""" | |
| with self.lock: | |
| if session_id not in self.active_sessions: | |
| return None | |
| session_data = self.active_sessions[session_id] | |
| return { | |
| "running": True, | |
| "interactions_count": len(session_data["interactions"]), | |
| "metrics_count": len(session_data["metrics"]), | |
| "duration_seconds": (datetime.now() - session_data["start_time"]).total_seconds(), | |
| } | |
| # Global instance | |
| manual_test_runner = ManualTestRunner() | |