tahamajs's picture
download
raw
26.9 kB
#!/usr/bin/env python3
"""
Advanced Evaluation and Benchmarking with Gemini API
This module provides sophisticated evaluation and benchmarking systems for AI reasoning
"""
import os
import asyncio
import logging
from typing import List, Dict, Any, Optional, Union, Callable
from dataclasses import dataclass, field
from abc import ABC, abstractmethod
import json
import time
import numpy as np
from enum import Enum
from collections import defaultdict, deque
import statistics
from pathlib import Path
# LangChain imports
from langchain_core.prompts import PromptTemplate
from langchain_google_genai import ChatGoogleGenerativeAI
# Google Generative AI
import google.generativeai as genai
# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
class EvaluationMetric(Enum):
"""Evaluation metrics"""
ACCURACY = "accuracy"
COMPLETENESS = "completeness"
COHERENCE = "coherence"
RELEVANCE = "relevance"
CREATIVITY = "creativity"
EFFICIENCY = "efficiency"
ROBUSTNESS = "robustness"
class BenchmarkType(Enum):
"""Types of benchmarks"""
MATHEMATICAL = "mathematical"
LOGICAL = "logical"
CREATIVE = "creative"
ANALYTICAL = "analytical"
COMPREHENSIVE = "comprehensive"
@dataclass
class EvaluationResult:
"""Result of an evaluation"""
metric: EvaluationMetric
score: float
explanation: str
confidence: float = 0.5
timestamp: float = field(default_factory=time.time)
def to_dict(self) -> Dict[str, Any]:
"""Convert to dictionary"""
return {
"metric": self.metric.value,
"score": self.score,
"explanation": self.explanation,
"confidence": self.confidence,
"timestamp": self.timestamp,
}
@dataclass
class BenchmarkProblem:
"""Benchmark problem definition"""
problem_id: str
problem_text: str
problem_type: BenchmarkType
difficulty: float # 0.0 to 1.0
expected_answer: Optional[str] = None
evaluation_criteria: List[EvaluationMetric] = field(default_factory=list)
metadata: Dict[str, Any] = field(default_factory=dict)
def to_dict(self) -> Dict[str, Any]:
"""Convert to dictionary"""
return {
"problem_id": self.problem_id,
"problem_text": self.problem_text,
"problem_type": self.problem_type.value,
"difficulty": self.difficulty,
"expected_answer": self.expected_answer,
"evaluation_criteria": [
metric.value for metric in self.evaluation_criteria
],
"metadata": self.metadata,
}
@dataclass
class EvaluationConfig:
"""Configuration for evaluation system"""
api_key: str = field(default_factory=lambda: os.getenv("GEMINI_API_KEY", ""))
model: str = "gemini-1.5-flash"
temperature: float = 0.3 # Lower temperature for consistent evaluation
max_tokens: int = 2048
enable_detailed_evaluation: bool = True
enable_comparative_evaluation: bool = True
evaluation_threshold: float = 0.7
max_evaluation_time: int = 30
def __post_init__(self):
if not self.api_key:
raise ValueError("GEMINI_API_KEY environment variable must be set")
class MetricEvaluator:
"""Evaluates specific metrics"""
def __init__(self, config: EvaluationConfig):
self.config = config
self.llm = ChatGoogleGenerativeAI(
model=config.model,
google_api_key=config.api_key,
temperature=config.temperature,
max_output_tokens=config.max_tokens,
)
async def evaluate_metric(
self,
metric: EvaluationMetric,
problem: str,
solution: str,
expected_answer: str = None,
) -> EvaluationResult:
"""Evaluate a specific metric"""
try:
prompt = self._create_evaluation_prompt(
metric, problem, solution, expected_answer
)
response = await asyncio.to_thread(self.llm.invoke, prompt)
# Parse evaluation result
score, explanation, confidence = self._parse_evaluation_response(
response.content
)
return EvaluationResult(
metric=metric,
score=score,
explanation=explanation,
confidence=confidence,
)
except Exception as e:
logger.error(f"Metric evaluation failed: {e}")
return EvaluationResult(
metric=metric,
score=0.0,
explanation=f"Evaluation failed: {str(e)}",
confidence=0.0,
)
def _create_evaluation_prompt(
self,
metric: EvaluationMetric,
problem: str,
solution: str,
expected_answer: str = None,
) -> str:
"""Create evaluation prompt for specific metric"""
if metric == EvaluationMetric.ACCURACY:
return f"""
Evaluate the accuracy of this solution on a scale of 0.0 to 1.0:
Problem: {problem}
Solution: {solution}
Expected Answer: {expected_answer or "Not provided"}
Consider:
- Correctness of the answer
- Accuracy of calculations or reasoning
- Adherence to facts and logic
Provide:
1. Accuracy score (0.0 to 1.0)
2. Detailed explanation
3. Confidence in evaluation (0.0 to 1.0)
Format:
Score: X.X
Explanation: [detailed explanation]
Confidence: X.X
"""
elif metric == EvaluationMetric.COMPLETENESS:
return f"""
Evaluate the completeness of this solution on a scale of 0.0 to 1.0:
Problem: {problem}
Solution: {solution}
Consider:
- Whether all parts of the problem are addressed
- Completeness of the reasoning process
- Thoroughness of the answer
Provide:
1. Completeness score (0.0 to 1.0)
2. Detailed explanation
3. Confidence in evaluation (0.0 to 1.0)
Format:
Score: X.X
Explanation: [detailed explanation]
Confidence: X.X
"""
elif metric == EvaluationMetric.COHERENCE:
return f"""
Evaluate the coherence of this solution on a scale of 0.0 to 1.0:
Problem: {problem}
Solution: {solution}
Consider:
- Logical flow and structure
- Consistency of reasoning
- Clarity of presentation
Provide:
1. Coherence score (0.0 to 1.0)
2. Detailed explanation
3. Confidence in evaluation (0.0 to 1.0)
Format:
Score: X.X
Explanation: [detailed explanation]
Confidence: X.X
"""
elif metric == EvaluationMetric.RELEVANCE:
return f"""
Evaluate the relevance of this solution on a scale of 0.0 to 1.0:
Problem: {problem}
Solution: {solution}
Consider:
- Relevance to the problem
- Appropriateness of the approach
- Alignment with problem requirements
Provide:
1. Relevance score (0.0 to 1.0)
2. Detailed explanation
3. Confidence in evaluation (0.0 to 1.0)
Format:
Score: X.X
Explanation: [detailed explanation]
Confidence: X.X
"""
elif metric == EvaluationMetric.CREATIVITY:
return f"""
Evaluate the creativity of this solution on a scale of 0.0 to 1.0:
Problem: {problem}
Solution: {solution}
Consider:
- Originality of approach
- Innovative thinking
- Creative problem-solving
Provide:
1. Creativity score (0.0 to 1.0)
2. Detailed explanation
3. Confidence in evaluation (0.0 to 1.0)
Format:
Score: X.X
Explanation: [detailed explanation]
Confidence: X.X
"""
elif metric == EvaluationMetric.EFFICIENCY:
return f"""
Evaluate the efficiency of this solution on a scale of 0.0 to 1.0:
Problem: {problem}
Solution: {solution}
Consider:
- Efficiency of the approach
- Optimal use of resources
- Streamlined reasoning process
Provide:
1. Efficiency score (0.0 to 1.0)
2. Detailed explanation
3. Confidence in evaluation (0.0 to 1.0)
Format:
Score: X.X
Explanation: [detailed explanation]
Confidence: X.X
"""
elif metric == EvaluationMetric.ROBUSTNESS:
return f"""
Evaluate the robustness of this solution on a scale of 0.0 to 1.0:
Problem: {problem}
Solution: {solution}
Consider:
- Robustness to variations
- Handling of edge cases
- Reliability of the approach
Provide:
1. Robustness score (0.0 to 1.0)
2. Detailed explanation
3. Confidence in evaluation (0.0 to 1.0)
Format:
Score: X.X
Explanation: [detailed explanation]
Confidence: X.X
"""
else:
return f"Evaluate this solution: {solution}"
def _parse_evaluation_response(self, response: str) -> tuple:
"""Parse evaluation response"""
try:
lines = response.strip().split("\n")
score = 0.5
explanation = ""
confidence = 0.5
for line in lines:
line = line.strip()
if line.startswith("Score:"):
try:
score = float(line.split(":")[1].strip())
score = max(0.0, min(1.0, score))
except:
pass
elif line.startswith("Explanation:"):
explanation = line.split(":", 1)[1].strip()
elif line.startswith("Confidence:"):
try:
confidence = float(line.split(":")[1].strip())
confidence = max(0.0, min(1.0, confidence))
except:
pass
return score, explanation, confidence
except Exception as e:
logger.error(f"Evaluation parsing failed: {e}")
return 0.5, "Parsing failed", 0.5
class BenchmarkGenerator:
"""Generates benchmark problems"""
def __init__(self, config: EvaluationConfig):
self.config = config
self.llm = ChatGoogleGenerativeAI(
model=config.model,
google_api_key=config.api_key,
temperature=config.temperature,
max_output_tokens=config.max_tokens,
)
async def generate_benchmark_problems(
self, problem_type: BenchmarkType, num_problems: int = 5
) -> List[BenchmarkProblem]:
"""Generate benchmark problems of a specific type"""
try:
prompt = self._create_generation_prompt(problem_type, num_problems)
response = await asyncio.to_thread(self.llm.invoke, prompt)
# Parse generated problems
problems = self._parse_generated_problems(response.content, problem_type)
return problems[:num_problems]
except Exception as e:
logger.error(f"Benchmark generation failed: {e}")
return []
def _create_generation_prompt(
self, problem_type: BenchmarkType, num_problems: int
) -> str:
"""Create prompt for generating benchmark problems"""
if problem_type == BenchmarkType.MATHEMATICAL:
return f"""
Generate {num_problems} mathematical reasoning problems with varying difficulty levels.
Each problem should:
1. Require mathematical reasoning
2. Have a clear solution path
3. Test different mathematical concepts
4. Include difficulty rating (0.0 to 1.0)
Format each problem as:
Problem {i}: [problem text]
Difficulty: X.X
Expected Answer: [answer]
"""
elif problem_type == BenchmarkType.LOGICAL:
return f"""
Generate {num_problems} logical reasoning problems with varying difficulty levels.
Each problem should:
1. Require logical reasoning
2. Have clear logical steps
3. Test different logical concepts
4. Include difficulty rating (0.0 to 1.0)
Format each problem as:
Problem {i}: [problem text]
Difficulty: X.X
Expected Answer: [answer]
"""
elif problem_type == BenchmarkType.CREATIVE:
return f"""
Generate {num_problems} creative reasoning problems with varying difficulty levels.
Each problem should:
1. Require creative thinking
2. Have multiple possible solutions
3. Test creativity and innovation
4. Include difficulty rating (0.0 to 1.0)
Format each problem as:
Problem {i}: [problem text]
Difficulty: X.X
Expected Answer: [answer]
"""
elif problem_type == BenchmarkType.ANALYTICAL:
return f"""
Generate {num_problems} analytical reasoning problems with varying difficulty levels.
Each problem should:
1. Require analytical thinking
2. Have complex analysis requirements
3. Test analytical skills
4. Include difficulty rating (0.0 to 1.0)
Format each problem as:
Problem {i}: [problem text]
Difficulty: X.X
Expected Answer: [answer]
"""
else:
return f"Generate {num_problems} comprehensive reasoning problems."
def _parse_generated_problems(
self, response: str, problem_type: BenchmarkType
) -> List[BenchmarkProblem]:
"""Parse generated problems from response"""
problems = []
try:
# Split by problem markers
problem_sections = response.split("Problem ")
for i, section in enumerate(
problem_sections[1:], 1
): # Skip first empty section
lines = section.strip().split("\n")
if len(lines) < 3:
continue
# Extract problem text
problem_text = lines[0].strip()
# Extract difficulty
difficulty = 0.5
for line in lines:
if line.startswith("Difficulty:"):
try:
difficulty = float(line.split(":")[1].strip())
difficulty = max(0.0, min(1.0, difficulty))
except:
pass
# Extract expected answer
expected_answer = ""
for line in lines:
if line.startswith("Expected Answer:"):
expected_answer = line.split(":", 1)[1].strip()
# Create benchmark problem
problem = BenchmarkProblem(
problem_id=f"{problem_type.value}_{i}",
problem_text=problem_text,
problem_type=problem_type,
difficulty=difficulty,
expected_answer=expected_answer,
evaluation_criteria=[
EvaluationMetric.ACCURACY,
EvaluationMetric.COMPLETENESS,
],
)
problems.append(problem)
return problems
except Exception as e:
logger.error(f"Problem parsing failed: {e}")
return []
class AdvancedEvaluator:
"""Advanced evaluation system"""
def __init__(self, config: EvaluationConfig):
self.config = config
self.metric_evaluator = MetricEvaluator(config)
self.benchmark_generator = BenchmarkGenerator(config)
self.evaluation_history = []
logger.info("Advanced Evaluator initialized")
async def evaluate_solution(
self,
problem: str,
solution: str,
metrics: List[EvaluationMetric] = None,
expected_answer: str = None,
) -> Dict[str, Any]:
"""Evaluate a solution comprehensively"""
start_time = time.time()
try:
if metrics is None:
metrics = [
EvaluationMetric.ACCURACY,
EvaluationMetric.COMPLETENESS,
EvaluationMetric.COHERENCE,
EvaluationMetric.RELEVANCE,
]
# Evaluate each metric
evaluation_results = []
for metric in metrics:
result = await self.metric_evaluator.evaluate_metric(
metric, problem, solution, expected_answer
)
evaluation_results.append(result)
# Calculate overall score
overall_score = self._calculate_overall_score(evaluation_results)
# Create comprehensive evaluation
evaluation = {
"problem": problem,
"solution": solution,
"expected_answer": expected_answer,
"evaluation_results": [
result.to_dict() for result in evaluation_results
],
"overall_score": overall_score,
"evaluation_time": time.time() - start_time,
"success": True,
}
# Store in history
self.evaluation_history.append(evaluation)
return evaluation
except Exception as e:
logger.error(f"Solution evaluation failed: {e}")
return {
"problem": problem,
"solution": solution,
"error": str(e),
"evaluation_time": time.time() - start_time,
"success": False,
}
async def benchmark_system(
self, system_name: str, problem_type: BenchmarkType, num_problems: int = 5
) -> Dict[str, Any]:
"""Benchmark a system on specific problem type"""
start_time = time.time()
try:
# Generate benchmark problems
problems = await self.benchmark_generator.generate_benchmark_problems(
problem_type, num_problems
)
if not problems:
raise ValueError("Failed to generate benchmark problems")
# Evaluate system on each problem
benchmark_results = []
for problem in problems:
# This would typically call the system being benchmarked
# For now, we'll simulate a solution
simulated_solution = f"Simulated solution for {problem.problem_id}"
evaluation = await self.evaluate_solution(
problem.problem_text,
simulated_solution,
problem.evaluation_criteria,
problem.expected_answer,
)
benchmark_results.append(
{"problem": problem.to_dict(), "evaluation": evaluation}
)
# Calculate benchmark statistics
benchmark_stats = self._calculate_benchmark_stats(benchmark_results)
return {
"system_name": system_name,
"problem_type": problem_type.value,
"num_problems": num_problems,
"benchmark_results": benchmark_results,
"benchmark_stats": benchmark_stats,
"benchmark_time": time.time() - start_time,
"success": True,
}
except Exception as e:
logger.error(f"System benchmarking failed: {e}")
return {
"system_name": system_name,
"problem_type": problem_type.value,
"error": str(e),
"benchmark_time": time.time() - start_time,
"success": False,
}
async def compare_systems(
self, systems: List[str], problem_type: BenchmarkType, num_problems: int = 5
) -> Dict[str, Any]:
"""Compare multiple systems"""
start_time = time.time()
try:
comparison_results = {}
# Benchmark each system
for system_name in systems:
benchmark_result = await self.benchmark_system(
system_name, problem_type, num_problems
)
comparison_results[system_name] = benchmark_result
# Calculate comparison statistics
comparison_stats = self._calculate_comparison_stats(comparison_results)
return {
"systems": systems,
"problem_type": problem_type.value,
"comparison_results": comparison_results,
"comparison_stats": comparison_stats,
"comparison_time": time.time() - start_time,
"success": True,
}
except Exception as e:
logger.error(f"System comparison failed: {e}")
return {
"systems": systems,
"problem_type": problem_type.value,
"error": str(e),
"comparison_time": time.time() - start_time,
"success": False,
}
def _calculate_overall_score(
self, evaluation_results: List[EvaluationResult]
) -> float:
"""Calculate overall score from individual metric scores"""
if not evaluation_results:
return 0.0
# Weighted average based on confidence
total_weighted_score = 0.0
total_weight = 0.0
for result in evaluation_results:
weight = result.confidence
total_weighted_score += result.score * weight
total_weight += weight
if total_weight == 0:
return 0.0
return total_weighted_score / total_weight
def _calculate_benchmark_stats(
self, benchmark_results: List[Dict[str, Any]]
) -> Dict[str, Any]:
"""Calculate benchmark statistics"""
if not benchmark_results:
return {}
overall_scores = []
metric_scores = defaultdict(list)
for result in benchmark_results:
evaluation = result["evaluation"]
if evaluation["success"]:
overall_scores.append(evaluation["overall_score"])
for metric_result in evaluation["evaluation_results"]:
metric_scores[metric_result["metric"]].append(
metric_result["score"]
)
stats = {
"num_problems": len(benchmark_results),
"successful_evaluations": len(overall_scores),
"overall_score": {
"mean": statistics.mean(overall_scores) if overall_scores else 0.0,
"std": (
statistics.stdev(overall_scores) if len(overall_scores) > 1 else 0.0
),
"min": min(overall_scores) if overall_scores else 0.0,
"max": max(overall_scores) if overall_scores else 0.0,
},
}
# Add metric-specific statistics
for metric, scores in metric_scores.items():
stats[f"{metric}_score"] = {
"mean": statistics.mean(scores) if scores else 0.0,
"std": statistics.stdev(scores) if len(scores) > 1 else 0.0,
"min": min(scores) if scores else 0.0,
"max": max(scores) if scores else 0.0,
}
return stats
def _calculate_comparison_stats(
self, comparison_results: Dict[str, Any]
) -> Dict[str, Any]:
"""Calculate comparison statistics"""
stats = {
"systems_compared": len(comparison_results),
"system_rankings": {},
"best_system": None,
"performance_gaps": {},
}
# Calculate system rankings
system_scores = {}
for system_name, result in comparison_results.items():
if result["success"] and "benchmark_stats" in result:
overall_score = result["benchmark_stats"]["overall_score"]["mean"]
system_scores[system_name] = overall_score
# Rank systems
ranked_systems = sorted(system_scores.items(), key=lambda x: x[1], reverse=True)
stats["system_rankings"] = {
system: rank + 1 for rank, (system, _) in enumerate(ranked_systems)
}
if ranked_systems:
stats["best_system"] = ranked_systems[0][0]
# Calculate performance gaps
best_score = ranked_systems[0][1]
for system, score in ranked_systems[1:]:
stats["performance_gaps"][system] = best_score - score
return stats
def get_evaluation_stats(self) -> Dict[str, Any]:
"""Get evaluation system statistics"""
return {
"total_evaluations": len(self.evaluation_history),
"config": {
"model": self.config.model,
"temperature": self.config.temperature,
"enable_detailed_evaluation": self.config.enable_detailed_evaluation,
},
}
# Example usage and testing functions
async def test_evaluation_system():
"""Test the evaluation system"""
config = EvaluationConfig(
api_key=os.getenv("GEMINI_API_KEY", "your-api-key-here"),
model="gemini-1.5-flash",
temperature=0.3,
)
print("🧪 Testing Evaluation System")
print("=" * 50)
# Test evaluation system
print("\n1. Testing Solution Evaluation:")
evaluator = AdvancedEvaluator(config)
test_problem = "Solve the equation: 2x + 5 = 13"
test_solution = "To solve 2x + 5 = 13, I subtract 5 from both sides: 2x = 8. Then I divide both sides by 2: x = 4."
expected_answer = "x = 4"
evaluation_result = await evaluator.evaluate_solution(
test_problem, test_solution, expected_answer=expected_answer
)
print(f"Evaluation Success: {evaluation_result['success']}")
print(f"Overall Score: {evaluation_result['overall_score']:.3f}")
print(f"Evaluation Time: {evaluation_result['evaluation_time']:.2f}s")
# Test benchmark generation
print("\n2. Testing Benchmark Generation:")
problems = await evaluator.benchmark_generator.generate_benchmark_problems(
BenchmarkType.MATHEMATICAL, 3
)
print(f"Generated {len(problems)} benchmark problems")
for problem in problems:
print(
f" - {problem.problem_text[:50]}... (difficulty: {problem.difficulty:.2f})"
)
# Test system benchmarking
print("\n3. Testing System Benchmarking:")
benchmark_result = await evaluator.benchmark_system(
"Test System", BenchmarkType.MATHEMATICAL, 2
)
print(f"Benchmark Success: {benchmark_result['success']}")
if benchmark_result["success"]:
stats = benchmark_result["benchmark_stats"]
print(f"Overall Score: {stats['overall_score']['mean']:.3f}")
print(f"Successful Evaluations: {stats['successful_evaluations']}")
# Test system comparison
print("\n4. Testing System Comparison:")
comparison_result = await evaluator.compare_systems(
["System A", "System B"], BenchmarkType.MATHEMATICAL, 2
)
print(f"Comparison Success: {comparison_result['success']}")
if comparison_result["success"]:
stats = comparison_result["comparison_stats"]
print(f"Systems Compared: {stats['systems_compared']}")
print(f"Best System: {stats['best_system']}")
print("\n✅ Evaluation system test completed!")
if __name__ == "__main__":
# Run test if API key is available
if os.getenv("GEMINI_API_KEY"):
asyncio.run(test_evaluation_system())
else:
print("Please set GEMINI_API_KEY environment variable to test the system")

Xet Storage Details

Size:
26.9 kB
·
Xet hash:
721165ed93367f746e53b7292e6b4b421a0617ccf19753fe0b997f8f15267e7b

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.