File size: 7,372 Bytes
478aa65 | 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 | import os
import json
import asyncio
import random
import pandas as pd
import nest_asyncio
from llama_index.core import (
VectorStoreIndex,
Settings,
Document,
)
from llama_index.core.node_parser import SentenceSplitter
from llama_index.core.prompts import PromptTemplate
from llama_index.llms.ollama import Ollama
from llama_index.embeddings.huggingface import HuggingFaceEmbedding
nest_asyncio.apply()
GROUND_TRUTH_PATH = "retrieval_ground_truth_pairs_30.json"
async def generate_query_for_node(llm, node_text):
"""
Generate one realistic user query from a counseling document.
"""
prompt = PromptTemplate(
"""
You are creating a retrieval evaluation dataset for a mental well-being RAG system.
Given the counseling interaction below, write ONE realistic user query that someone might ask
if they needed this kind of counseling support.
Rules:
- Write only the user query.
- Do not answer the query.
- Keep it natural and concise.
- Do not mention that this is based on a document.
Counseling interaction:
{node_text}
User query:
"""
)
response = await llm.apredict(
prompt,
node_text=node_text,
)
return response.strip()
async def main():
# ==========================================
# 1. MODEL CONFIGURATION
# ==========================================
print("Initializing models...")
llm = Ollama(
model="llama3:latest",
request_timeout=600.0,
)
embed_model = HuggingFaceEmbedding(
model_name="BAAI/bge-small-en-v1.5"
)
Settings.llm = llm
Settings.embed_model = embed_model
# ==========================================
# 2. LOAD DATASET FROM JSONL FILE
# ==========================================
json_path = "data/combined_dataset.json"
if not os.path.exists(json_path):
print(f"Error: {json_path} not found.")
return
print(f"Loading dataset from {json_path}...")
raw_data = []
with open(json_path, "r", encoding="utf-8") as f:
for line in f:
if line.strip():
raw_data.append(json.loads(line))
print(f"Loaded {len(raw_data)} total records.")
# ==========================================
# 3. RANDOM SAMPLING
# ==========================================
sample_size = min(30, len(raw_data))
random.seed(42)
sample_data = random.sample(raw_data, sample_size)
print(f"Randomly sampled {sample_size} records.")
# ==========================================
# 4. CREATE DOCUMENTS
# ==========================================
documents = []
for i, entry in enumerate(sample_data):
context = entry.get("Context", "")
response = entry.get("Response", "")
text_content = (
f"User: {context}\n\n"
f"Therapist: {response}"
)
if text_content.strip():
documents.append(
Document(
text=text_content,
metadata={
"sample_id": i
}
)
)
print(f"Prepared {len(documents)} documents.")
if len(documents) == 0:
print("Error: No valid documents were created. Check dataset keys.")
return
# ==========================================
# 5. CREATE NODES
# ==========================================
print("Creating nodes...")
parser = SentenceSplitter(
chunk_size=768,
chunk_overlap=100,
)
nodes = parser.get_nodes_from_documents(documents)
print(f"Generated {len(nodes)} nodes.")
if len(nodes) == 0:
print("Error: No nodes were created.")
return
# ==========================================
# 6. BUILD VECTOR INDEX
# ==========================================
print("Building vector index...")
index = VectorStoreIndex(nodes)
retriever = index.as_retriever(
similarity_top_k=5
)
# ==========================================
# 7. GENERATE OR LOAD SYNTHETIC GROUND TRUTH
# ==========================================
if os.path.exists(GROUND_TRUTH_PATH):
print(f"Loading existing ground truth from {GROUND_TRUTH_PATH}...")
with open(GROUND_TRUTH_PATH, "r", encoding="utf-8") as f:
qa_pairs = json.load(f)
else:
print("Generating synthetic retrieval queries...")
qa_pairs = []
for idx, node in enumerate(nodes):
print(f"Generating query {idx + 1}/{len(nodes)}...")
node_text = node.get_content()
query = await generate_query_for_node(
llm=llm,
node_text=node_text,
)
qa_pairs.append(
{
"query_id": idx,
"query": query,
"expected_node_id": node.node_id,
"source_text": node_text,
}
)
with open(GROUND_TRUTH_PATH, "w", encoding="utf-8") as f:
json.dump(
qa_pairs,
f,
indent=2,
ensure_ascii=False,
)
print(f"Saved {GROUND_TRUTH_PATH}")
# ==========================================
# 8. MANUAL RETRIEVAL EVALUATION
# ==========================================
print("Running retrieval evaluation...")
results = []
for pair in qa_pairs:
query = pair["query"]
expected_node_id = pair["expected_node_id"]
retrieved_nodes = await retriever.aretrieve(query)
retrieved_ids = [
item.node.node_id
for item in retrieved_nodes
]
hit = 0
reciprocal_rank = 0.0
rank = None
if expected_node_id in retrieved_ids:
hit = 1
rank = retrieved_ids.index(expected_node_id) + 1
reciprocal_rank = 1.0 / rank
results.append(
{
"query_id": pair["query_id"],
"query": query,
"expected_node_id": expected_node_id,
"retrieved_node_ids": retrieved_ids,
"hit_rate@5": hit,
"mrr@5": reciprocal_rank,
"rank": rank,
}
)
# ==========================================
# 9. COMPUTE METRICS
# ==========================================
df = pd.DataFrame(results)
hit_rate = df["hit_rate@5"].mean()
mrr = df["mrr@5"].mean()
df.to_csv(
"retrieval_eval_results.csv",
index=False,
)
# ==========================================
# 10. FINAL RESULTS
# ==========================================
print("\n" + "=" * 50)
print(" RAG RETRIEVAL PERFORMANCE")
print("=" * 50)
print(f"Dataset Source: {json_path}")
print("Embedding Model: BAAI/bge-small-en-v1.5")
print(f"Documents Used: {len(documents)}")
print(f"Nodes Used: {len(nodes)}")
print(f"Total Queries: {len(qa_pairs)}")
print("-" * 50)
print(f"Hit Rate @ 5: {hit_rate:.4f}")
print(f"MRR @ 5: {mrr:.4f}")
print("=" * 50)
print("Evaluation complete!")
print("Detailed results saved to retrieval_eval_results.csv")
if __name__ == "__main__":
asyncio.run(main()) |