Repository navigation
Expand file tree
/
Copy pathjudge.py
More file actions
232 lines (184 loc) · 8.85 KB
/
Copy pathjudge.py
File metadata and controls
232 lines (184 loc) · 8.85 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
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
# ===================================================================
# LLM as a judge to evaluate answers from different RAG systems
#
# Analyzes QA.json dataset produced by compare.py
# Produces evaluation_results.json with scores and reasoning
# ===================================================================
import json
import os
import sys
from tqdm import tqdm
from langchain_openai import AzureChatOpenAI
from dotenv import load_dotenv
# Load environment variables from std_rag .env
load_dotenv(os.path.abspath(os.path.join(os.path.dirname(__file__), '../std_rag/.env')))
DATASET_NAME = 'QA.json'
AZURE_ENDPOINT = os.getenv("AZURE_ENDPOINT")
AZURE_DEPLOYMENT = os.getenv("AZURE_DEPLOYMENT")
AZURE_API_VERSION = os.getenv("AZURE_API_VERSION")
AZURE_API_KEY = os.getenv("AZURE_API_KEY")
if not AZURE_API_KEY:
print("[ERROR] AZURE_API_KEY not found. Please check ../std_rag/.env")
sys.exit(1)
def main():
# Initialize LLM
llm = AzureChatOpenAI(
azure_endpoint=AZURE_ENDPOINT,
azure_deployment=AZURE_DEPLOYMENT,
api_version=AZURE_API_VERSION,
api_key=AZURE_API_KEY,
temperature=0
)
# Load dataset
dataset_path = os.path.join(os.path.dirname(__file__), DATASET_NAME)
try:
with open(dataset_path, 'r', encoding='utf-8') as f:
dataset = json.load(f)
except FileNotFoundError:
print(f"[ERROR] dataset.json not found at {dataset_path}")
return
results = []
scores = {
"std_rag": 0,
"std_rag_simple": 0,
"graph_rag_open": 0,
"graph_rag_strict": 0,
"tie": 0
}
for entry in tqdm(dataset, desc="Evaluating answers"):
question = entry["question"]
ans_std = entry["std_rag"].get("answer", "No answer")
ans_open = entry["graph_rag_open"].get("answer", "No answer")
ans_strict = entry["graph_rag_strict"].get("answer", "No answer")
# Extract input tokens for each system
tokens_std = entry["std_rag"].get("input_tokens", 0)
tokens_simple = entry["std_rag_simple"].get("input_tokens", 0)
tokens_open = entry["graph_rag_open"].get("input_tokens", 0)
tokens_strict = entry["graph_rag_strict"].get("input_tokens", 0)
# Extract retrieval context metadata for Standard RAG (Custom)
std_retrieval_meta = entry["std_rag"].get("retrieval_context", {})
mentioned_files = std_retrieval_meta.get("mentioned_files", [])
relevant_titles = std_retrieval_meta.get("relevant_titles", [])
std_extra_info = ""
if mentioned_files:
std_extra_info += f"\n [Router: File identificati: {', '.join(mentioned_files)}]"
if relevant_titles:
std_extra_info += f"\n [Router: Titoli identificati: {', '.join(relevant_titles)}]"
# Build context for Standard RAG (Custom)
std_source_docs = entry["std_rag"].get("source_documents", [])
std_context = "\n\n".join([
f"SOURCE: {doc['filename']} (Page {doc['page']})\nCONTENT:\n{doc['content']}"
for doc in std_source_docs
]) if std_source_docs else ""
# Extract context and meta for Standard RAG (Simple)
simple_retrieval_meta = entry["std_rag_simple"].get("retrieval_context", {})
simple_mentioned_files = simple_retrieval_meta.get("mentioned_files", [])
simple_extra_info = ""
if simple_mentioned_files:
simple_extra_info += f"\n [Router: File identificati: {', '.join(simple_mentioned_files)}]"
simple_source_docs = entry["std_rag_simple"].get("source_documents", [])
simple_context = "\n\n".join([
f"SOURCE: {doc['filename']} (Page {doc['page']})\nCONTENT:\n{doc['content']}"
for doc in simple_source_docs
]) if simple_source_docs else ""
# Extract context for GraphRAG systems (already formatted)
open_context = entry["graph_rag_open"].get("context", "")
strict_context = entry["graph_rag_strict"].get("context", "")
# Evaluation prompt
prompt = f"""
Sei un giudice imparziale esperto in valutazione di sistemi RAG (Retrieval Augmented Generation) basati su documenti aziendali.
Il tuo compito è valutare QUATTRO risposte fornite da quattro diversi sistemi RAG alla stessa domanda.
Valuta le risposte basandoti su:
**QUALITÀ DELLA RISPOSTA** (80%):
1. Accuratezza: Le informazioni sono corrette?
2. Completezza: La risposta è esaustiva?
3. Rilevanza: Risponde esattamente alla domanda?
4. Chiarezza: È ben scritta e comprensibile?
**QUALITÀ DEL RETRIEVAL** (20%):
5. Pertinenza del context: I documenti recuperati sono rilevanti per la domanda?
6. Precisione: Ha recuperato informazioni strettamente non necessarie o totalmente fuori tema?
7. Completezza del context: Il context contiene tutte le info necessarie per rispondere?
8. Efficienza: Il sistema ha utilizzato il minimo numero di token possibile pur mantenendo abbastanza contesto?
Restituisci SOLO un JSON con il seguente formato:
{{
"best_model": "A" | "B" | "C" | "D" | "Tie",
"reasoning": "Spiegazione breve che considera ANCHE la qualità del retrieval, non solo della risposta finale",
"retrieval_quality": {{
"A": "poor" | "fair" | "good" | "excellent",
"B": "poor" | "fair" | "good" | "excellent",
"C": "poor" | "fair" | "good" | "excellent",
"D": "poor" | "fair" | "good" | "excellent"
}}
}}
Non aggiungere altro testo.
Usa Tie solo se le risposte sono uguali.
# Domanda: {question}
### SISTEMA A: ###
Risposta: {entry['std_rag_simple'].get('answer', 'No answer')}
Input tokens utilizzati: {tokens_simple}
Context recuperato:
{simple_extra_info} {simple_context if simple_context else "[Nessun context disponibile]"}
### SISTEMA B: ###
Risposta: {ans_std}
Input tokens utilizzati: {tokens_std}
Context recuperato:
{std_extra_info} {std_context if std_context else "[Nessun context disponibile]"}
### SISTEMA C: ###
Risposta: {ans_open}
Input tokens utilizzati: {tokens_open}
Context recuperato:
{open_context if open_context else "[Nessun context disponibile]"}
### SISTEMA D: ###
Risposta: {ans_strict}
Input tokens utilizzati: {tokens_strict}
Context recuperato:
{strict_context if strict_context else "[Nessun context disponibile]"}
# Rispondi con il JSON richiesto:
"""
try:
response = llm.invoke(prompt)
content = response.content.strip()
# Clean markdown code blocks if present
if content.startswith("```json"):
content = content[7:]
if content.endswith("```"):
content = content[:-3]
content = content.strip()
eval_result = json.loads(content)
best = eval_result.get("best_model", "Tie")
if best == "A":
scores["std_rag_simple"] += 1
elif best == "B":
scores["std_rag"] += 1
elif best == "C":
scores["graph_rag_open"] += 1
elif best == "D":
scores["graph_rag_strict"] += 1
else:
scores["tie"] += 1
# Add token information to evaluation
eval_result["input_tokens"] = {
"std_rag": tokens_std,
"std_rag_simple": tokens_simple,
"graph_rag_open": tokens_open,
"graph_rag_strict": tokens_strict
}
entry["evaluation"] = eval_result
results.append(entry)
except Exception as e:
print(f"Error evaluating question '{question}': {e}")
entry["evaluation"] = {"error": str(e)}
results.append(entry)
# Save evaluation results
results_path = os.path.join(os.path.dirname(__file__), 'evaluation_results.json')
with open(results_path, 'w', encoding='utf-8') as f:
json.dump(results, f, indent=4, ensure_ascii=False)
print("\nEvaluation Complete!")
print("Scores:")
print(f"Standard RAG (Simple): {scores['std_rag_simple']}")
print(f"Standard RAG (Custom): {scores['std_rag']}")
print(f"GraphRAG Open: {scores['graph_rag_open']}")
print(f"GraphRAG Strict: {scores['graph_rag_strict']}")
print(f"Ties: {scores['tie']}")
if __name__ == "__main__":
main()