Spaces:
Runtime error

BattleFiven's picture
deploy: round 6 save_intermediate light (sha 05316bb)
ed86a97
Raw History Blame Contribute Delete
16.7 kB
#!/usr/bin/env python3
"""
AI Tester Platform CLI
Main entry point for the command-line interface.
"""
from contextlib import contextmanager
from pathlib import Path
from typing import List, Optional
from uuid import UUID
import typer
from dotenv import load_dotenv
from rich.console import Console
from rich.panel import Panel
from rich.table import Table
# Load env vars
load_dotenv()
# Add src to path
import sys
sys.path.insert(0, str(Path(__file__).parent.parent))
from src.core import RAGEvaluator, TestEngine, ToneEvaluator, get_ai_client_from_env
from src.db import (
BotRepository,
PersonaRepository,
ScenarioRepository,
SessionRepository,
get_db,
init_db,
)
from src.models import Bot, Persona, Scenario, SessionStatus, TestSession
from src.utils.report_generator import ReportGenerator
app = typer.Typer(
name="ai-tester",
help="AI-powered testing platform for conversational chatbots",
rich_markup_mode="rich",
)
console = Console()
# Helper to get DB session
@contextmanager
def get_repo(repo_class):
"""Context manager for repositories."""
db = get_db()
with db.get_session() as session:
yield repo_class(session)
@app.callback()
def callback():
"""
πŸ€– AI Tester Platform - Test your conversational AI with simulated users.
Features:
- Create and manage bot configurations
- Define personas and test scenarios
- Run automated conversational tests
- Evaluate RAG faithfulness and tone-of-voice
- Generate detailed reports
"""
# Initialize database on first run
init_db()
# ==================== BOT COMMANDS ====================
bot_app = typer.Typer(help="Manage bot configurations")
app.add_typer(bot_app, name="bot")
@bot_app.command("create")
def bot_create(
name: str = typer.Argument(..., help="Bot name"),
url: str = typer.Argument(..., help="Bot URL"),
description: Optional[str] = typer.Option(None, "--description", "-d"),
):
"""Create a new bot configuration."""
with get_repo(BotRepository) as repo:
from src.models import RAGConfig, Selectors, ToneConfig
bot = Bot(
name=name,
url=url,
description=description,
selectors=Selectors(),
expected_tone=ToneConfig(),
rag_config=RAGConfig(),
)
created = repo.create(bot)
console.print(f"[green]βœ“ Created bot: {created.name} (ID: {created.id})[/green]")
@bot_app.command("list")
def bot_list():
"""List all configured bots."""
with get_repo(BotRepository) as repo:
bots = repo.list_all()
if not bots:
console.print("[yellow]No bots configured yet.[/yellow]")
return
table = Table(title="Configured Bots")
table.add_column("ID", style="dim")
table.add_column("Name", style="cyan")
table.add_column("URL")
table.add_column("Active", justify="center")
for bot in bots:
table.add_row(
str(bot.id)[:8],
bot.name,
str(bot.url)[:50],
"βœ“" if bot.is_active else "βœ—",
)
console.print(table)
@bot_app.command("show")
def bot_show(bot_id: str = typer.Argument(..., help="Bot ID")):
"""Show bot details."""
with get_repo(BotRepository) as repo:
bot = repo.get_by_id(UUID(bot_id))
if not bot:
console.print(f"[red]Bot not found: {bot_id}[/red]")
raise typer.Exit(1)
console.print(Panel(
f"[bold]{bot.name}[/bold]\n\n"
f"ID: {bot.id}\n"
f"URL: {bot.url}\n"
f"Description: {bot.description or 'N/A'}\n"
f"Active: {bot.is_active}\n\n"
f"Tone Config:\n"
f" - Formality: {bot.expected_tone.formality_level}/10\n"
f" - Emoji: {'Yes' if bot.expected_tone.use_emoji else 'No'}\n"
f" - Style: {bot.expected_tone.language_style}\n\n"
f"RAG Config:\n"
f" - Faithfulness threshold: {bot.rag_config.faithfulness_threshold}\n"
f" - Strict mode: {bot.rag_config.strict_mode}",
title="Bot Details"
))
# ==================== PERSONA COMMANDS ====================
persona_app = typer.Typer(help="Manage test personas")
app.add_typer(persona_app, name="persona")
@persona_app.command("create")
def persona_create(
name: str = typer.Argument(..., help="Persona name"),
mood: str = typer.Option("neutral", "--mood", "-m", help="Mood: friendly, angry, frustrated, etc"),
goal: str = typer.Option(..., "--goal", "-g", help="Persona's goal"),
background: Optional[str] = typer.Option(None, "--background", "-b"),
template: bool = typer.Option(False, "--template", "-t", help="Save as reusable template"),
):
"""Create a new test persona."""
with get_repo(PersonaRepository) as repo:
persona = Persona(
name=name,
mood=mood,
goal=goal,
background=background,
is_template=template,
)
created = repo.create(persona)
console.print(f"[green]βœ“ Created persona: {created.name} (ID: {created.id})[/green]")
@persona_app.command("list")
def persona_list(
templates_only: bool = typer.Option(False, "--templates", "-t"),
):
"""List personas."""
with get_repo(PersonaRepository) as repo:
personas = repo.list_all(templates_only=templates_only)
if not personas:
console.print("[yellow]No personas found.[/yellow]")
return
table = Table(title="Personas")
table.add_column("ID", style="dim")
table.add_column("Name", style="cyan")
table.add_column("Mood")
table.add_column("Template", justify="center")
for p in personas:
table.add_row(
str(p.id)[:8],
p.name,
p.mood,
"βœ“" if p.is_template else "",
)
console.print(table)
# ==================== SCENARIO COMMANDS ====================
scenario_app = typer.Typer(help="Manage test scenarios")
app.add_typer(scenario_app, name="scenario")
@scenario_app.command("create")
def scenario_create(
name: str = typer.Argument(..., help="Scenario name"),
steps_file: Optional[str] = typer.Option(None, "--steps-file", "-f", help="JSON file with steps"),
template: bool = typer.Option(False, "--template", "-t"),
):
"""Create a new test scenario."""
import json
with get_repo(ScenarioRepository) as repo:
if steps_file:
with open(steps_file) as f:
steps_data = json.load(f)
from src.models import Step
steps = [Step(**s) for s in steps_data]
else:
# Create default greeting scenario
from src.models import ActionType, Step
steps = [
Step(
step_id="greeting",
action_type=ActionType.SEND_MESSAGE,
content="Hello!",
expected_intent="greeting",
)
]
scenario = Scenario(
name=name,
steps=steps,
is_template=template,
)
created = repo.create(scenario)
console.print(f"[green]βœ“ Created scenario: {created.name} (ID: {created.id})[/green]")
@scenario_app.command("list")
def scenario_list():
"""List scenarios."""
with get_repo(ScenarioRepository) as repo:
scenarios = repo.list_all()
if not scenarios:
console.print("[yellow]No scenarios found.[/yellow]")
return
table = Table(title="Scenarios")
table.add_column("ID", style="dim")
table.add_column("Name", style="cyan")
table.add_column("Steps", justify="right")
table.add_column("Category")
for s in scenarios:
table.add_row(
str(s.id)[:8],
s.name,
str(len(s.steps)),
s.category or "-",
)
console.print(table)
# ==================== SESSION COMMANDS ====================
session_app = typer.Typer(help="Manage and run test sessions")
app.add_typer(session_app, name="session")
@session_app.command("create")
def session_create(
bot_id: str = typer.Argument(..., help="Bot ID to test"),
version: str = typer.Argument(..., help="Bot version (e.g., v1.2.3)"),
scenarios: List[str] = typer.Option(..., "--scenario", "-s", help="Scenario IDs to run"),
personas: List[str] = typer.Option(..., "--persona", "-p", help="Persona IDs to use"),
name: Optional[str] = typer.Option(None, "--name", "-n"),
):
"""Create a new test session."""
with get_repo(SessionRepository) as repo:
session = TestSession(
bot_id=UUID(bot_id),
bot_version=version,
session_name=name,
status=SessionStatus.PENDING,
)
created = repo.create_session(session)
# Add scenario-persona links
for scenario_id in scenarios:
for persona_id in personas:
from sqlalchemy import text
repo.db.execute(
text("INSERT INTO session_scenario_links (session_id, scenario_id, persona_id) VALUES (:sid, :scid, :pid)"),
{"sid": str(created.id), "scid": str(scenario_id), "pid": str(persona_id)},
)
console.print(f"[green]βœ“ Created session: {created.id}[/green]")
console.print(f" Bot: {bot_id} (v{version})")
console.print(f" Scenarios: {len(scenarios)}")
console.print(f" Personas: {len(personas)}")
console.print(f" Total tests: {len(scenarios) * len(personas)}")
@session_app.command("run")
def session_run(
session_id: str = typer.Argument(..., help="Session ID to run"),
headless: bool = typer.Option(False, "--headless", help="Run browser headless"),
):
"""Run a test session."""
# Setup
try:
ai_client = get_ai_client_from_env()
except ValueError as e:
console.print(f"[red]Error: {e}[/red]")
raise typer.Exit(1)
rag_eval = RAGEvaluator(ai_client)
tone_eval = ToneEvaluator(ai_client)
with get_repo(SessionRepository) as session_repo:
with get_repo(BotRepository) as bot_repo:
with get_repo(ScenarioRepository) as scenario_repo:
with get_repo(PersonaRepository) as persona_repo:
session = session_repo.get_session(UUID(session_id))
if not session:
console.print(f"[red]Session not found: {session_id}[/red]")
raise typer.Exit(1)
bot = bot_repo.get_by_id(session.bot_id)
if not bot:
console.print("[red]Bot not found[/red]")
raise typer.Exit(1)
# Get scenario-persona combinations
links = session_repo.list_session_links(UUID(session_id))
pairs = []
if links:
for link in links:
scenario = scenario_repo.get_by_id(UUID(link["scenario_id"]))
persona = persona_repo.get_by_id(UUID(link["persona_id"]))
if scenario and persona:
pairs.append((scenario, persona))
if not pairs:
scenarios = scenario_repo.list_all(bot_id=bot.id)
personas = persona_repo.list_all()
for scenario in scenarios:
for persona in personas:
pairs.append((scenario, persona))
engine = TestEngine(
ai_client=ai_client,
rag_evaluator=rag_eval,
tone_evaluator=tone_eval,
output_dir=f"./output/{session_id}",
)
# Run tests
total = len(pairs)
completed = 0
passed = 0
failed = 0
for scenario, persona in pairs:
console.print(f"\n[cyan]Running: {scenario.name} as {persona.name}[/cyan]")
result = engine.run_test(
bot=bot,
scenario=scenario,
persona=persona,
session=session,
headless=headless,
)
session_repo.add_result(result)
completed += 1
if result.status == "passed":
passed += 1
else:
failed += 1
status_color = "green" if result.status == "passed" else "red"
console.print(f"[{status_color}]Result: {result.status}[/{status_color}]")
# Update session status
session_repo.update_session(
UUID(session_id),
{
"status": "completed",
"total_tests": total,
"passed": passed,
"failed": failed,
"completed_at": datetime.now(),
}
)
console.print(f"\n[green]βœ“ Session completed: {completed}/{total} tests[/green]")
@session_app.command("list")
def session_list(
bot_id: Optional[str] = typer.Option(None, "--bot", "-b"),
):
"""List test sessions."""
with get_repo(SessionRepository) as repo:
bot_uuid = UUID(bot_id) if bot_id else None
sessions = repo.list_sessions(bot_uuid)
if not sessions:
console.print("[yellow]No sessions found.[/yellow]")
return
table = Table(title="Test Sessions")
table.add_column("ID", style="dim")
table.add_column("Name", style="cyan")
table.add_column("Version")
table.add_column("Status")
table.add_column("Results", justify="right")
table.add_column("Date")
for s in sessions:
status_color = {
"pending": "yellow",
"running": "blue",
"completed": "green",
"failed": "red",
}.get(s.status.value, "white")
table.add_row(
str(s.id)[:8],
s.session_name or "-",
s.bot_version,
f"[{status_color}]{s.status.value}[/{status_color}]",
f"{s.passed}/{s.total_tests}",
s.created_at.strftime("%Y-%m-%d %H:%M") if s.created_at else "-",
)
console.print(table)
@session_app.command("report")
def session_report(
session_id: str = typer.Argument(..., help="Session ID"),
format: str = typer.Option("markdown", "--format", "-f", help="Output format: json, markdown, html"),
output: Optional[str] = typer.Option(None, "--output", "-o", help="Output file"),
):
"""Generate session report."""
with get_repo(SessionRepository) as repo:
session = repo.get_session(UUID(session_id))
if not session:
console.print("[red]Session not found[/red]")
raise typer.Exit(1)
results = repo.get_session_results(UUID(session_id))
generator = ReportGenerator()
if format == "json":
report = generator.to_json(session, results)
elif format == "markdown":
report = generator.to_markdown(session, results)
else:
report = generator.to_html(session, results)
if output:
with open(output, "w") as f:
f.write(report)
console.print(f"[green]Report saved to: {output}[/green]")
else:
console.print(report)
if __name__ == "__main__":
from datetime import datetime
app()