Initial commit
Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
This commit is contained in:
commit
4ecf7b351d
143 files changed
+24156
No files matched your search
@@ -0,0 +1,189 @@
|
||||
"""
|
||||
Example usage of RAG Evaluation Framework - Phase 2
|
||||
Demonstrates evaluation execution with mock RAG system
|
||||
"""
|
||||
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
# Add parent directory to path for imports
|
||||
sys.path.insert(0, str(Path(__file__).parent.parent))
|
||||
|
||||
from rag_evaluation.core.config import Config
|
||||
from rag_evaluation.testset.generator import TestsetGenerator
|
||||
from rag_evaluation.storage.database import DatabaseManager
|
||||
from rag_evaluation.evaluation import (
|
||||
MockRAGRetriever,
|
||||
MockRAGGenerator,
|
||||
RAGEvaluationAdapter,
|
||||
EvaluationExecutor
|
||||
)
|
||||
|
||||
|
||||
def main():
|
||||
"""Main example function for Phase 2"""
|
||||
|
||||
print("=" * 60)
|
||||
print("RAG Evaluation Framework - Phase 2 Example")
|
||||
print("=" * 60)
|
||||
|
||||
# 1. Load configuration
|
||||
print("\n[1/6] Loading configuration...")
|
||||
|
||||
# Try to load config.yaml first, fallback to config.example.yaml
|
||||
config_file = "config.yaml"
|
||||
if not Path(config_file).exists():
|
||||
if Path("config.example.yaml").exists():
|
||||
print(" Note: config.yaml not found, using config.example.yaml")
|
||||
config_file = "config.example.yaml"
|
||||
else:
|
||||
raise FileNotFoundError(
|
||||
"Configuration file not found. "
|
||||
"Please create config.yaml from config.example.yaml"
|
||||
)
|
||||
|
||||
config = Config.from_file(config_file)
|
||||
print("✓ Configuration loaded")
|
||||
|
||||
# 2. Initialize database
|
||||
print("\n[2/6] Initializing database...")
|
||||
db_manager = DatabaseManager(config.database)
|
||||
|
||||
try:
|
||||
schema_file = Path(__file__).parent / "storage" / "schema.sql"
|
||||
db_manager.init_schema(str(schema_file))
|
||||
print("✓ Database schema initialized")
|
||||
except Exception as e:
|
||||
print(f"⚠ Database may already be initialized: {e}")
|
||||
|
||||
# 3. Generate or load testset
|
||||
print("\n[3/6] Generating testset...")
|
||||
generator = TestsetGenerator(config)
|
||||
|
||||
# Create sample documents
|
||||
sample_dir = Path("./data/sample_docs")
|
||||
sample_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
sample_file = sample_dir / "rag_guide.txt"
|
||||
with open(sample_file, 'w', encoding='utf-8') as f:
|
||||
f.write("""
|
||||
# RAG System Guide
|
||||
|
||||
## What is RAG?
|
||||
RAG (Retrieval-Augmented Generation) combines information retrieval with text generation.
|
||||
It retrieves relevant documents and uses them to generate accurate answers.
|
||||
|
||||
## Key Components
|
||||
1. Retriever: Finds relevant documents from a knowledge base
|
||||
2. Generator: Creates answers based on retrieved documents
|
||||
3. Knowledge Base: Collection of documents to search
|
||||
|
||||
## Evaluation Metrics
|
||||
- Context Recall: How well relevant documents are retrieved
|
||||
- Context Precision: How precise the retrieved documents are
|
||||
- Faithfulness: Whether answers are faithful to the context
|
||||
- Answer Relevancy: How relevant answers are to questions
|
||||
- Correctness: How correct answers are compared to ground truth
|
||||
""")
|
||||
|
||||
knowledge_base_id = "kb-phase2-demo"
|
||||
testset = generator.generate(
|
||||
knowledge_base_id=knowledge_base_id,
|
||||
file_paths=[str(sample_file)],
|
||||
test_size=5, # Small testset for demo
|
||||
name="Phase 2 Demo Testset"
|
||||
)
|
||||
|
||||
testset_file = generator.save_testset(testset)
|
||||
print(f"✓ Testset generated: {testset['id']}")
|
||||
print(f" - Questions: {len(testset['questions'])}")
|
||||
print(f" - Saved to: {testset_file}")
|
||||
|
||||
# 4. Set up RAG system (using mock for demo)
|
||||
print("\n[4/6] Setting up RAG system...")
|
||||
|
||||
# Create mock RAG components
|
||||
mock_documents = [
|
||||
"RAG combines retrieval and generation for better answers.",
|
||||
"The retriever finds relevant documents from the knowledge base.",
|
||||
"The generator creates answers based on retrieved context.",
|
||||
"Evaluation metrics measure both retrieval and generation quality.",
|
||||
"Context recall measures how well relevant documents are retrieved."
|
||||
]
|
||||
|
||||
retriever = MockRAGRetriever(documents=mock_documents)
|
||||
generator = MockRAGGenerator()
|
||||
rag_adapter = RAGEvaluationAdapter(retriever, generator)
|
||||
|
||||
print("✓ Mock RAG system initialized")
|
||||
print(" - Retriever: MockRAGRetriever")
|
||||
print(" - Generator: MockRAGGenerator")
|
||||
|
||||
# 5. Execute evaluation
|
||||
print("\n[5/6] Executing evaluation...")
|
||||
|
||||
executor = EvaluationExecutor(
|
||||
config=config,
|
||||
rag_adapter=rag_adapter,
|
||||
db_manager=db_manager
|
||||
)
|
||||
|
||||
evaluation_id = executor.execute_evaluation(
|
||||
testset_id=testset['id'],
|
||||
knowledge_base_id=knowledge_base_id,
|
||||
testset=testset
|
||||
)
|
||||
|
||||
print(f"✓ Evaluation completed: {evaluation_id}")
|
||||
|
||||
# 6. Display results
|
||||
print("\n[6/6] Evaluation Results")
|
||||
print("-" * 60)
|
||||
|
||||
# Get summary
|
||||
summary = executor.get_evaluation_summary(evaluation_id)
|
||||
|
||||
print(f"\n📊 Overall Score: {summary['overall_score']:.2f}/100")
|
||||
print(f"\n📈 Retrieval Metrics:")
|
||||
print(f" - Context Recall: {summary['avg_context_recall']:.3f}")
|
||||
print(f" - Context Precision: {summary['avg_context_precision']:.3f}")
|
||||
print(f" - MRR: {summary['avg_mrr']:.3f}")
|
||||
print(f" - NDCG: {summary['avg_ndcg']:.3f}")
|
||||
|
||||
print(f"\n📝 Generation Metrics:")
|
||||
print(f" - Faithfulness: {summary['avg_faithfulness']:.3f}")
|
||||
print(f" - Answer Relevancy: {summary['avg_answer_relevancy']:.3f}")
|
||||
print(f" - Correctness: {summary['avg_correctness']:.3f}")
|
||||
|
||||
print(f"\n📋 Statistics:")
|
||||
print(f" - Total Questions: {summary['total_questions']}")
|
||||
print(f" - Failed Questions: {summary['failed_questions']}")
|
||||
|
||||
# Get detailed results
|
||||
results = executor.get_evaluation_results(evaluation_id)
|
||||
|
||||
print(f"\n🔍 Sample Question Results:")
|
||||
for i, result in enumerate(results[:2], 1): # Show first 2
|
||||
print(f"\n Question {i}: {result['question_text'][:60]}...")
|
||||
print(f" Recall: {result['context_recall']:.3f} | "
|
||||
f"Precision: {result['context_precision']:.3f} | "
|
||||
f"Faithfulness: {result['faithfulness']:.3f}")
|
||||
|
||||
print("\n" + "=" * 60)
|
||||
print("✅ Phase 2 Example Completed Successfully!")
|
||||
print("=" * 60)
|
||||
|
||||
print("\n📚 Next Steps:")
|
||||
print("1. Replace MockRAG with your actual RAG system")
|
||||
print("2. Use HTTPRAGRetriever/Generator for HTTP APIs")
|
||||
print("3. Integrate real RAGAS metrics for better accuracy")
|
||||
print("4. Move to Phase 3 for report generation")
|
||||
|
||||
print(f"\n💾 Data saved to database:")
|
||||
print(f" - Evaluation ID: {evaluation_id}")
|
||||
print(f" - Testset ID: {testset['id']}")
|
||||
print(f" - Results: {len(results)} questions evaluated")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in new issue
Block a user