Spaces:
Sleeping
Sleeping
File size: 9,757 Bytes
a686b1b |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 |
"""
Script de benchmarking para avaliar diferentes configuracoes de RAG.
Uso:
python scripts/benchmark.py
"""
import sys
import json
from pathlib import Path
from typing import List, Dict, Any
from datetime import datetime
import time
# Adicionar src ao path
sys.path.insert(0, str(Path(__file__).parent.parent))
from src.evaluation import RAGEvaluator, RAGEvaluationResult
from src.config import DATABASE_URL
from src.database import DatabaseManager
from src.embeddings import EmbeddingManager
from src.generation import GenerationManager
def load_test_dataset(dataset_path: str) -> List[Dict[str, Any]]:
"""Carrega dataset de teste."""
with open(dataset_path, 'r', encoding='utf-8') as f:
return json.load(f)
def run_rag_pipeline(
query: str,
top_k: int = 5,
use_reranking: bool = False,
use_hybrid: bool = False,
session_id: str = "benchmark"
) -> Dict[str, Any]:
"""
Executa pipeline RAG completo.
Returns:
Dict com response e contexts
"""
db = DatabaseManager(DATABASE_URL)
embedding_manager = EmbeddingManager()
generation_manager = GenerationManager()
# 1. Criar embedding
query_embedding = embedding_manager.encode(query)
# 2. Buscar contextos
if use_hybrid:
# Implementar hybrid search
contexts = db.search_similar(query_embedding, top_k=top_k, session_id=session_id)
else:
contexts = db.search_similar(query_embedding, top_k=top_k, session_id=session_id)
# 3. Reranking (se ativado)
if use_reranking and len(contexts) > 0:
# Implementar reranking
pass
# 4. Gerar resposta
context_texts = [ctx['content'] for ctx in contexts]
response = generation_manager.generate_response(query, context_texts)
return {
'response': response,
'contexts': context_texts
}
def benchmark_configurations(
test_cases: List[Dict[str, Any]],
configs: List[Dict[str, Any]]
) -> Dict[str, List[RAGEvaluationResult]]:
"""
Testa multiplas configuracoes.
Args:
test_cases: Casos de teste
configs: Lista de configuracoes para testar
Returns:
Dict com resultados por configuracao
"""
evaluator = RAGEvaluator(use_ragas=False) # Usar metricas simples
all_results = {}
for config in configs:
config_name = config['name']
print(f"\n{'='*60}")
print(f"Testando configuracao: {config_name}")
print(f"{'='*60}")
results = []
for i, test_case in enumerate(test_cases):
print(f" Caso {i+1}/{len(test_cases)}: {test_case['query'][:50]}...")
start_time = time.time()
# Executar RAG com configuracao
try:
rag_result = run_rag_pipeline(
query=test_case['query'],
top_k=config.get('top_k', 5),
use_reranking=config.get('use_reranking', False),
use_hybrid=config.get('use_hybrid', False)
)
# Avaliar resultado
eval_result = evaluator.evaluate_single(
query=test_case['query'],
response=rag_result['response'],
contexts=rag_result['contexts'],
ground_truth=test_case.get('ground_truth')
)
eval_result.response_time = time.time() - start_time
results.append(eval_result)
except Exception as e:
print(f" Erro: {e}")
continue
all_results[config_name] = results
return all_results
def generate_html_report(
all_results: Dict[str, List[RAGEvaluationResult]],
output_path: str
):
"""Gera relatorio HTML."""
evaluator = RAGEvaluator(use_ragas=False)
html = """
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>RAG Benchmark Report</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 20px;
background-color: #f5f5f5;
}
h1 {
color: #333;
}
.config {
background: white;
padding: 20px;
margin: 20px 0;
border-radius: 8px;
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}
table {
width: 100%;
border-collapse: collapse;
margin: 10px 0;
}
th, td {
padding: 12px;
text-align: left;
border-bottom: 1px solid #ddd;
}
th {
background-color: #4CAF50;
color: white;
}
.score-high {
color: green;
font-weight: bold;
}
.score-medium {
color: orange;
}
.score-low {
color: red;
font-weight: bold;
}
.worst-cases {
background: #fff3cd;
padding: 15px;
margin: 15px 0;
border-radius: 5px;
border-left: 4px solid #ffc107;
}
</style>
</head>
<body>
<h1>RAG Benchmark Report</h1>
<p>Data: """ + datetime.now().strftime("%Y-%m-%d %H:%M:%S") + """</p>
"""
for config_name, results in all_results.items():
if not results:
continue
report = evaluator.generate_report(results)
html += f"""
<div class="config">
<h2>{config_name}</h2>
<p>Total de casos: {report['total_cases']}</p>
<h3>Scores Medios</h3>
<table>
<tr>
<th>Metrica</th>
<th>Media</th>
<th>Min</th>
<th>Max</th>
</tr>
"""
for metric in ['faithfulness', 'answer_relevancy', 'context_precision', 'context_recall', 'overall']:
avg = report['average_scores'].get(metric, 0)
min_val = report['min_scores'].get(metric, 0) if metric != 'overall' else 0
max_val = report['max_scores'].get(metric, 0) if metric != 'overall' else 0
score_class = 'score-high' if avg >= 0.7 else ('score-medium' if avg >= 0.5 else 'score-low')
html += f"""
<tr>
<td>{metric.replace('_', ' ').title()}</td>
<td class="{score_class}">{avg:.3f}</td>
<td>{min_val:.3f}</td>
<td>{max_val:.3f}</td>
</tr>
"""
html += """
</table>
"""
# Piores casos
if 'worst_cases' in report:
html += """
<div class="worst-cases">
<h3>Top 5 Piores Casos (para analise)</h3>
<ul>
"""
for case in report['worst_cases']:
html += f"""
<li>
<strong>Query:</strong> {case['query']}<br>
<strong>Score:</strong> {case['score']:.3f}
</li>
"""
html += """
</ul>
</div>
"""
html += """
</div>
"""
html += """
</body>
</html>
"""
with open(output_path, 'w', encoding='utf-8') as f:
f.write(html)
print(f"\nRelatorio HTML gerado: {output_path}")
def main():
"""Funcao principal."""
print("RAG Benchmark")
print("="*60)
# Carregar dataset
dataset_path = Path(__file__).parent.parent / "data" / "evaluation" / "test_dataset.json"
if not dataset_path.exists():
print(f"Erro: Dataset nao encontrado em {dataset_path}")
return
test_cases = load_test_dataset(str(dataset_path))
print(f"Carregados {len(test_cases)} casos de teste\n")
# Configuracoes para testar
configs = [
{
'name': 'Baseline (top_k=5)',
'top_k': 5,
'use_reranking': False,
'use_hybrid': False
},
{
'name': 'Top_k=10',
'top_k': 10,
'use_reranking': False,
'use_hybrid': False
},
{
'name': 'Com Reranking',
'top_k': 10,
'use_reranking': True,
'use_hybrid': False
},
{
'name': 'Com Hybrid Search',
'top_k': 5,
'use_reranking': False,
'use_hybrid': True
},
{
'name': 'Tudo Ativado',
'top_k': 10,
'use_reranking': True,
'use_hybrid': True
}
]
# Executar benchmark
all_results = benchmark_configurations(test_cases, configs)
# Gerar relatorio
output_path = Path(__file__).parent.parent / "benchmark_report.html"
generate_html_report(all_results, str(output_path))
# Imprimir resumo
print("\n" + "="*60)
print("RESUMO")
print("="*60)
evaluator = RAGEvaluator(use_ragas=False)
for config_name, results in all_results.items():
if not results:
continue
report = evaluator.generate_report(results)
avg_overall = report['average_scores']['overall']
print(f"\n{config_name}:")
print(f" Overall Score: {avg_overall:.3f}")
print(f" Faithfulness: {report['average_scores']['faithfulness']:.3f}")
print(f" Answer Relevancy: {report['average_scores']['answer_relevancy']:.3f}")
if __name__ == "__main__":
main()
|