-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbenchmark.py
More file actions
81 lines (67 loc) · 2.84 KB
/
Copy pathbenchmark.py
File metadata and controls
81 lines (67 loc) · 2.84 KB
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
import os
import json
import time
import pandas as pd
from typing import List, Dict
from datasets import Dataset
from ragas import evaluate
from ragas.metrics import faithfulness, answer_relevancy, context_precision
# Import logic from server (simplified)
import server
def run_benchmark(questions: List[str], ground_truth: List[str] = None):
results_naive = []
results_advanced = []
print(f"🚀 Starting benchmark with {len(questions)} questions...")
for q in questions:
# Naive RAG
start_time = time.time()
retrieved_naive = server.retrieve(q, top_k=4)
context_naive = "\n".join([c["text"] for c in retrieved_naive])
# Simple query for naive (ignoring LLM call for speed if just measuring retrieval,
# but RAGAS needs answer, so we might need to mock or call)
# For this benchmark, we'll call the real server logic
resp_naive = server.query(server.QueryRequest(query=q, advanced=False))
results_naive.append({
"question": q,
"answer": resp_naive["answer"],
"contexts": [c["text"] for c in resp_naive["sources"]],
"time": time.time() - start_time
})
# Advanced RAG
start_time = time.time()
resp_adv = server.query(server.QueryRequest(query=q, advanced=True))
results_advanced.append({
"question": q,
"answer": resp_adv["answer"],
"contexts": [c["text"] for c in resp_adv["sources"]],
"time": time.time() - start_time
})
# Convert to Ragas format
ds_naive = Dataset.from_list(results_naive)
ds_adv = Dataset.from_list(results_advanced)
print("📊 Evaluating Naive RAG...")
score_naive = evaluate(ds_naive, metrics=[faithfulness, answer_relevancy, context_precision])
print("📊 Evaluating Advanced RAG...")
score_adv = evaluate(ds_adv, metrics=[faithfulness, answer_relevancy, context_precision])
return score_naive, score_adv
if __name__ == "__main__":
# Example questions
test_questions = [
"What is the main topic of the document?",
"Can you summarize the key findings?",
"Explain the methodology used in the text."
]
# Ensure some documents are loaded in server.DOCUMENTS for testing
# In a real scenario, you'd upload a specific test file first
if not server.DOCUMENTS:
print("⚠️ No documents found. Please upload a document to the server first.")
else:
sn, sa = run_benchmark(test_questions)
df = pd.DataFrame([
{"Method": "Naive RAG", **sn},
{"Method": "Advanced RAG", **sa}
])
print("\n🏆 Benchmark Results:")
print(df.to_markdown())
with open("benchmark_results.json", "w") as f:
json.dump({"naive": sn, "advanced": sa}, f, indent=2)