Spaces:
Runtime error

ai-tester-platform / src /core /knowledge_boundary.py
BattleFiven's picture
deploy: round 6 save_intermediate light (sha 05316bb)
ed86a97
Raw History Blame Contribute Delete
15.8 kB
"""
Knowledge Boundary Manager - Gestisce i limiti di conoscenza di Duolly.
Questo modulo si occupa di:
1. Fetchare la guida dei limiti da URL
2. Parsare e strutturare il contenuto
3. Fornire il contesto all'AI di valutazione
4. Validare che le risposte di Duolly rispettino i limiti
"""
import json
import os
import re
from dataclasses import dataclass, field
from datetime import datetime
from pathlib import Path
from typing import Dict, List, Optional
import requests
from rich.console import Console
console = Console()
@dataclass
class KnowledgeRule:
"""Singola regola dei limiti di conoscenza."""
category: str # es: "booking", "pricing", "general_info"
rule_type: str # "CAN_DO", "CANNOT_DO", "MUST_DO", "LIMITATION"
description: str
examples: List[str] = field(default_factory=list)
exceptions: List[str] = field(default_factory=list)
@dataclass
class KnowledgeBoundary:
"""Limite di conoscenza completo di Duolly."""
source_url: str
fetched_at: datetime
content_raw: str
# Strutturato
what_can_do: List[KnowledgeRule] = field(default_factory=list)
what_cannot_do: List[KnowledgeRule] = field(default_factory=list)
limitations: List[KnowledgeRule] = field(default_factory=list)
scope: str = "" # Descrizione generale dello scope
def to_prompt_context(self) -> str:
"""Converte in formato per il prompt dell'AI."""
lines = []
lines.append("=" * 60)
lines.append("DUOLLY KNOWLEDGE BOUNDARIES - COSA PUÒ/NON PUÒ FARE")
lines.append("=" * 60)
if self.scope:
lines.append(f"\nSCOPE GENERALE:\n{self.scope}\n")
if self.what_can_do:
lines.append("\n✅ COSA DUOLLY PUÒ FARE:")
for rule in self.what_can_do:
lines.append(f" • {rule.description}")
if rule.examples:
lines.append(f" Esempi: {', '.join(rule.examples[:2])}")
if self.what_cannot_do:
lines.append("\n❌ COSA DUOLLY NON PUÒ FARE:")
for rule in self.what_cannot_do:
lines.append(f" • {rule.description}")
if rule.examples:
lines.append(f" Esempi: {', '.join(rule.examples[:2])}")
if self.limitations:
lines.append("\n⚠️ LIMITAZIONI NOTE:")
for rule in self.limitations:
lines.append(f" • {rule.description}")
lines.append("\n" + "=" * 60)
lines.append("IMPORTANTE: Valuta se Duolly rispetta questi limiti!")
lines.append("=" * 60)
return "\n".join(lines)
def check_response_compliance(self, bot_response: str) -> List[Dict[str, any]]:
"""
Controlla se una risposta rispetta i limiti.
Returns:
Lista di violation trovate
"""
violations = []
response_lower = bot_response.lower()
# Controlla CANNOT_DO rules
for rule in self.what_cannot_do:
# Cerca indicatori che Duolly stia facendo qualcosa che non dovrebbe
indicators = [desc.lower() for desc in [rule.description] + rule.examples]
for indicator in indicators:
# Estrai parole chiave significative
keywords = [w for w in indicator.split() if len(w) > 4]
if any(kw in response_lower for kw in keywords[:3]):
violations.append({
"type": "BOUNDARY_VIOLATION",
"rule": rule.description,
"severity": "HIGH",
"message": f"Duolly potrebbe aver violato: {rule.description}"
})
return violations
class KnowledgeBoundaryManager:
"""
Gestisce il fetch e la cache dei limiti di conoscenza.
"""
def __init__(self, cache_dir: Optional[str] = None):
base_data_dir = Path(str(os.getenv("AI_TESTER_DATA_DIR", "./data") or "./data"))
resolved_cache_dir = Path(cache_dir) if cache_dir else (base_data_dir / "knowledge_boundaries")
self.cache_dir = resolved_cache_dir
self.cache_dir.mkdir(parents=True, exist_ok=True)
self._boundary_cache: Dict[str, KnowledgeBoundary] = {}
def fetch_boundary(self, url: str, force_refresh: bool = False) -> Optional[KnowledgeBoundary]:
"""
Fetcha la guida dei limiti da URL.
Args:
url: URL della guida
force_refresh: Se True, ignora la cache
Returns:
KnowledgeBoundary o None se errore
"""
# Controlla cache
if not force_refresh and url in self._boundary_cache:
return self._boundary_cache[url]
# Prova a leggere da file cache
cache_file = self._get_cache_file(url)
if not force_refresh and cache_file.exists():
try:
boundary = self._load_from_cache(cache_file)
self._boundary_cache[url] = boundary
console.print(f"[dim]Loaded knowledge boundary from cache: {url}[/dim]")
return boundary
except Exception as e:
console.print(f"[yellow]Cache load failed: {e}[/yellow]")
# Fetch da URL
try:
console.print(f"[dim]Fetching knowledge boundary from: {url}[/dim]")
response = requests.get(url, timeout=30, headers={
'User-Agent': 'AI-Tester-Bot/1.0'
})
response.raise_for_status()
content = response.text
boundary = self._parse_boundary(url, content)
# Salva in cache
self._save_to_cache(cache_file, boundary)
self._boundary_cache[url] = boundary
console.print(f"[green]✓ Knowledge boundary fetched and cached ({len(content)} chars)[/green]")
return boundary
except Exception as e:
console.print(f"[red]Failed to fetch knowledge boundary: {e}[/red]")
return None
def _parse_boundary(self, url: str, content: str) -> KnowledgeBoundary:
"""
Parsa il contenuto della guida in struttura KnowledgeBoundary.
Supporta vari formati:
- Markdown con sezioni
- JSON strutturato
- Testo semplice con pattern
"""
KnowledgeBoundary(
source_url=url,
fetched_at=datetime.now(),
content_raw=content
)
# Prova a parsare come JSON
try:
import json
data = json.loads(content)
return self._parse_json_boundary(url, data)
except json.JSONDecodeError:
pass
# Parsa come Markdown/testo
return self._parse_text_boundary(url, content)
def _parse_json_boundary(self, url: str, data: dict) -> KnowledgeBoundary:
"""Parsa formato JSON strutturato."""
boundary = KnowledgeBoundary(
source_url=url,
fetched_at=datetime.now(),
content_raw=json.dumps(data)
)
boundary.scope = data.get("scope", "")
# Parse CAN_DO
for item in data.get("can_do", []):
boundary.what_can_do.append(KnowledgeRule(
category=item.get("category", "general"),
rule_type="CAN_DO",
description=item.get("description", ""),
examples=item.get("examples", []),
exceptions=item.get("exceptions", [])
))
# Parse CANNOT_DO
for item in data.get("cannot_do", []):
boundary.what_cannot_do.append(KnowledgeRule(
category=item.get("category", "general"),
rule_type="CANNOT_DO",
description=item.get("description", ""),
examples=item.get("examples", []),
exceptions=item.get("exceptions", [])
))
# Parse LIMITATIONS
for item in data.get("limitations", []):
boundary.limitations.append(KnowledgeRule(
category=item.get("category", "general"),
rule_type="LIMITATION",
description=item.get("description", ""),
examples=item.get("examples", [])
))
return boundary
def _parse_text_boundary(self, url: str, content: str) -> KnowledgeBoundary:
"""Parsa formato testo/Markdown."""
boundary = KnowledgeBoundary(
source_url=url,
fetched_at=datetime.now(),
content_raw=content
)
lines = content.split('\n')
current_section = None
current_category = "general"
for line in lines:
line = line.strip()
if not line:
continue
# Identifica sezioni
lower_line = line.lower()
if any(x in lower_line for x in ['# scope', '# ambito', '## scope']):
current_section = "SCOPE"
continue
if any(x in lower_line for x in ['# può fare', '# can do', '# cosa può', '## può']):
current_section = "CAN_DO"
continue
if any(x in lower_line for x in ['# non può', '# cannot', '# cosa non può', '## non può']):
current_section = "CANNOT_DO"
continue
if any(x in lower_line for x in ['# limitazion', '# limitation', '## limitazion']):
current_section = "LIMITATIONS"
continue
# Estrai contenuto
if line.startswith('- ') or line.startswith('* ') or re.match(r'^\d+\.', line):
description = re.sub(r'^[-*\d.\s]+', '', line)
if current_section == "SCOPE":
boundary.scope += " " + description
elif current_section == "CAN_DO":
boundary.what_can_do.append(KnowledgeRule(
category=current_category,
rule_type="CAN_DO",
description=description
))
elif current_section == "CANNOT_DO":
boundary.what_cannot_do.append(KnowledgeRule(
category=current_category,
rule_type="CANNOT_DO",
description=description
))
elif current_section == "LIMITATIONS":
boundary.limitations.append(KnowledgeRule(
category=current_category,
rule_type="LIMITATION",
description=description
))
# Pulizia scope
boundary.scope = boundary.scope.strip()
# Se non abbiamo trovato struttura, crea una regola generica
if not boundary.what_can_do and not boundary.what_cannot_do:
boundary.what_can_do.append(KnowledgeRule(
category="general",
rule_type="CAN_DO",
description="Fornire informazioni turistiche generali"
))
boundary.limitations.append(KnowledgeRule(
category="general",
rule_type="LIMITATION",
description=f"Riferirsi alla guida completa: {url}"
))
return boundary
def _get_cache_file(self, url: str) -> Path:
"""Genera path file cache da URL."""
import hashlib
# MD5 used here as a stable short digest for cache filenames, NOT a
# security primitive. `usedforsecurity=False` documents the intent
# and silences bandit B324.
url_hash = hashlib.md5(url.encode(), usedforsecurity=False).hexdigest()[:16]
return self.cache_dir / f"boundary_{url_hash}.json"
def _save_to_cache(self, cache_file: Path, boundary: KnowledgeBoundary):
"""Salva boundary in cache."""
import json
data = {
"source_url": boundary.source_url,
"fetched_at": boundary.fetched_at.isoformat(),
"content_raw": boundary.content_raw,
"scope": boundary.scope,
"what_can_do": [
{
"category": r.category,
"description": r.description,
"examples": r.examples,
"exceptions": r.exceptions
}
for r in boundary.what_can_do
],
"what_cannot_do": [
{
"category": r.category,
"description": r.description,
"examples": r.examples,
"exceptions": r.exceptions
}
for r in boundary.what_cannot_do
],
"limitations": [
{
"category": r.category,
"description": r.description,
"examples": r.examples
}
for r in boundary.limitations
]
}
with open(cache_file, 'w') as f:
json.dump(data, f, indent=2, ensure_ascii=False)
def _load_from_cache(self, cache_file: Path) -> KnowledgeBoundary:
"""Carica boundary da cache."""
import json
with open(cache_file, 'r') as f:
data = json.load(f)
boundary = KnowledgeBoundary(
source_url=data["source_url"],
fetched_at=datetime.fromisoformat(data["fetched_at"]),
content_raw=data["content_raw"],
scope=data.get("scope", "")
)
for item in data.get("what_can_do", []):
boundary.what_can_do.append(KnowledgeRule(**item))
for item in data.get("what_cannot_do", []):
boundary.what_cannot_do.append(KnowledgeRule(**item))
for item in data.get("limitations", []):
boundary.limitations.append(KnowledgeRule(**item))
return boundary
def clear_cache(self, url: Optional[str] = None):
"""Pulisce la cache."""
if url:
cache_file = self._get_cache_file(url)
if cache_file.exists():
cache_file.unlink()
if url in self._boundary_cache:
del self._boundary_cache[url]
else:
# Pulisci tutto
for f in self.cache_dir.glob("boundary_*.json"):
f.unlink()
self._boundary_cache.clear()
# Singleton per uso globale
_boundary_manager: Optional[KnowledgeBoundaryManager] = None
def get_boundary_manager() -> KnowledgeBoundaryManager:
"""Ottiene l'istanza singleton del boundary manager."""
global _boundary_manager
if _boundary_manager is None:
_boundary_manager = KnowledgeBoundaryManager()
return _boundary_manager
def fetch_duolly_boundary(url: Optional[str] = None) -> Optional[KnowledgeBoundary]:
"""
Fetcha i limiti di Duolly.
Args:
url: URL della guida, se None cerca in env var
Returns:
KnowledgeBoundary o None
"""
import os
if url is None:
url = os.getenv("DUOLLY_KNOWLEDGE_BOUNDARY_URL")
if not url:
return None
manager = get_boundary_manager()
return manager.fetch_boundary(url)