Spaces:
Sleeping
Sleeping
Commit ·
c313477
0
Parent(s):
Initial commit: Move all local changes to GitHub
Browse files- .gitignore +69 -0
- README.md +145 -0
- gradio_full_llm_eval.py +1101 -0
- llm_prompt_eval_analysis.py +38 -0
- llm_response_logger.py +89 -0
- realtime_detector.py +29 -0
- requirements.txt +13 -0
- response_generator.py +66 -0
- round_robin_evaluator.py +86 -0
- search_fallback.py +55 -0
.gitignore
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Python
|
| 2 |
+
__pycache__/
|
| 3 |
+
*.py[cod]
|
| 4 |
+
*$py.class
|
| 5 |
+
*.so
|
| 6 |
+
.Python
|
| 7 |
+
build/
|
| 8 |
+
develop-eggs/
|
| 9 |
+
dist/
|
| 10 |
+
downloads/
|
| 11 |
+
eggs/
|
| 12 |
+
.eggs/
|
| 13 |
+
lib/
|
| 14 |
+
lib64/
|
| 15 |
+
parts/
|
| 16 |
+
sdist/
|
| 17 |
+
var/
|
| 18 |
+
wheels/
|
| 19 |
+
*.egg-info/
|
| 20 |
+
.installed.cfg
|
| 21 |
+
*.egg
|
| 22 |
+
|
| 23 |
+
# Virtual Environment
|
| 24 |
+
venv/
|
| 25 |
+
env/
|
| 26 |
+
ENV/
|
| 27 |
+
|
| 28 |
+
# IDE
|
| 29 |
+
.idea/
|
| 30 |
+
.vscode/
|
| 31 |
+
*.swp
|
| 32 |
+
*.swo
|
| 33 |
+
|
| 34 |
+
# Environment variables
|
| 35 |
+
.env
|
| 36 |
+
|
| 37 |
+
# Logs and databases
|
| 38 |
+
*.log
|
| 39 |
+
*.sqlite
|
| 40 |
+
*.db
|
| 41 |
+
|
| 42 |
+
# Results directory
|
| 43 |
+
results/
|
| 44 |
+
|
| 45 |
+
# OS specific
|
| 46 |
+
.DS_Store
|
| 47 |
+
Thumbs.db
|
| 48 |
+
|
| 49 |
+
# Jupyter Notebook
|
| 50 |
+
.ipynb_checkpoints
|
| 51 |
+
|
| 52 |
+
# Distribution / packaging
|
| 53 |
+
.Python
|
| 54 |
+
env/
|
| 55 |
+
build/
|
| 56 |
+
develop-eggs/
|
| 57 |
+
dist/
|
| 58 |
+
downloads/
|
| 59 |
+
eggs/
|
| 60 |
+
.eggs/
|
| 61 |
+
lib/
|
| 62 |
+
lib64/
|
| 63 |
+
parts/
|
| 64 |
+
sdist/
|
| 65 |
+
var/
|
| 66 |
+
wheels/
|
| 67 |
+
*.egg-info/
|
| 68 |
+
.installed.cfg
|
| 69 |
+
*.egg
|
README.md
ADDED
|
@@ -0,0 +1,145 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# LLM-Compare-Hub
|
| 2 |
+
|
| 3 |
+
A comprehensive tool for evaluating and comparing responses from multiple AI language models (GPT-4, Claude 3, and Gemini 1.5) with real-time search integration and advanced analytics.
|
| 4 |
+
|
| 5 |
+
## Features
|
| 6 |
+
|
| 7 |
+
### 1. Multi-Model Evaluation
|
| 8 |
+
- **Supported Models**:
|
| 9 |
+
- GPT-4 (OpenAI)
|
| 10 |
+
- Claude 3 Opus (Anthropic)
|
| 11 |
+
- Gemini 1.5 Pro (Google)
|
| 12 |
+
- **Round-Robin Evaluation**: Each model's response is evaluated by another model in a cycle
|
| 13 |
+
- **Comprehensive Metrics**:
|
| 14 |
+
- Helpfulness
|
| 15 |
+
- Correctness
|
| 16 |
+
- Coherence
|
| 17 |
+
- Tone Score
|
| 18 |
+
- Accuracy
|
| 19 |
+
- Relevance
|
| 20 |
+
- Completeness
|
| 21 |
+
- Clarity
|
| 22 |
+
|
| 23 |
+
### 2. Real-Time Information Integration
|
| 24 |
+
- **Automatic Detection**: Identifies prompts requiring real-time information
|
| 25 |
+
- **Google Search Integration**: Fetches relevant search results for real-time queries
|
| 26 |
+
- **Enhanced Responses**: Models incorporate search results into their responses
|
| 27 |
+
- **Transparent Reasoning**: Models explain how search results influenced their responses
|
| 28 |
+
|
| 29 |
+
### 3. Advanced Analytics & Visualization
|
| 30 |
+
- **Interactive Dashboard**: Gradio-based user interface
|
| 31 |
+
- **Visualization Tools**:
|
| 32 |
+
- Correlation Heatmap: Shows relationships between metrics
|
| 33 |
+
- Bar Chart: Compares average scores across models
|
| 34 |
+
- Radar Chart: Displays metric distribution for each model
|
| 35 |
+
- **Customizable Controls**:
|
| 36 |
+
- Correlation Threshold: Filter metric relationships
|
| 37 |
+
- Metric Weight: Adjust importance of metrics
|
| 38 |
+
|
| 39 |
+
### 4. Comprehensive Logging
|
| 40 |
+
- **Detailed CSV Export**:
|
| 41 |
+
- Timestamp of evaluation
|
| 42 |
+
- Original prompt
|
| 43 |
+
- Model responses
|
| 44 |
+
- Evaluation metrics
|
| 45 |
+
- Reasoning and notes
|
| 46 |
+
- Round-robin evaluation results
|
| 47 |
+
- **Automatic File Management**:
|
| 48 |
+
- Results stored in `results/` directory
|
| 49 |
+
- Files named `ai_prompt_eval_YYYYMMDD_HHMMSS.csv`
|
| 50 |
+
- Easy to track and compare evaluations
|
| 51 |
+
|
| 52 |
+
## Setup
|
| 53 |
+
|
| 54 |
+
1. **Clone the Repository**:
|
| 55 |
+
```bash
|
| 56 |
+
git clone [repository-url]
|
| 57 |
+
cd LLM-Compare-Hub
|
| 58 |
+
```
|
| 59 |
+
|
| 60 |
+
2. **Install Dependencies**:
|
| 61 |
+
```bash
|
| 62 |
+
pip install -r requirements.txt
|
| 63 |
+
```
|
| 64 |
+
|
| 65 |
+
3. **Environment Variables**:
|
| 66 |
+
Create a `.env` file with the following API keys:
|
| 67 |
+
```
|
| 68 |
+
OPENAI_API_KEY=your_openai_key
|
| 69 |
+
CLAUDE_API_KEY=your_claude_key
|
| 70 |
+
GEMINI_API_KEY=your_gemini_key
|
| 71 |
+
GOOGLE_API_KEY=your_google_key
|
| 72 |
+
GOOGLE_CSE_ID=your_custom_search_engine_id
|
| 73 |
+
```
|
| 74 |
+
|
| 75 |
+
## Usage
|
| 76 |
+
|
| 77 |
+
1. **Start the Application**:
|
| 78 |
+
```bash
|
| 79 |
+
python gradio_full_llm_eval.py
|
| 80 |
+
```
|
| 81 |
+
|
| 82 |
+
2. **Using the Dashboard**:
|
| 83 |
+
- Enter your prompt in the text box
|
| 84 |
+
- Click "Evaluate Prompt" to process
|
| 85 |
+
- View responses and metrics for each model
|
| 86 |
+
- Adjust visualization controls as needed
|
| 87 |
+
- Download results as CSV
|
| 88 |
+
|
| 89 |
+
3. **Understanding the Results**:
|
| 90 |
+
- **Response Display**: Shows each model's response with metrics
|
| 91 |
+
- **Metrics Panel**: Displays detailed evaluation scores
|
| 92 |
+
- **Visualizations**: Interactive charts for metric analysis
|
| 93 |
+
- **CSV Export**: Complete evaluation data for further analysis
|
| 94 |
+
|
| 95 |
+
## Features in Detail
|
| 96 |
+
|
| 97 |
+
### Real-Time Query Handling
|
| 98 |
+
- The system automatically detects if a prompt requires current information
|
| 99 |
+
- For real-time queries:
|
| 100 |
+
1. Fetches relevant search results
|
| 101 |
+
2. Incorporates results into model prompts
|
| 102 |
+
3. Models explain how they used the information
|
| 103 |
+
4. Evaluations consider the use of real-time data
|
| 104 |
+
|
| 105 |
+
### Round-Robin Evaluation
|
| 106 |
+
- GPT-4 evaluates Claude 3
|
| 107 |
+
- Claude 3 evaluates Gemini 1.5
|
| 108 |
+
- Gemini 1.5 evaluates GPT-4
|
| 109 |
+
- Each evaluation includes:
|
| 110 |
+
- Detailed reasoning
|
| 111 |
+
- Metric scores
|
| 112 |
+
- Additional observations
|
| 113 |
+
|
| 114 |
+
### Data Management
|
| 115 |
+
- **CSV Structure**:
|
| 116 |
+
- Timestamp
|
| 117 |
+
- Prompt
|
| 118 |
+
- Model
|
| 119 |
+
- Evaluator
|
| 120 |
+
- Response
|
| 121 |
+
- All metrics
|
| 122 |
+
- Reasoning
|
| 123 |
+
- Notes
|
| 124 |
+
- **File Organization**:
|
| 125 |
+
- Results stored in `results/` directory
|
| 126 |
+
- Files named `ai_prompt_eval_YYYYMMDD_HHMMSS.csv`
|
| 127 |
+
- Easy to track and compare evaluations
|
| 128 |
+
|
| 129 |
+
## Error Handling
|
| 130 |
+
- Graceful handling of API failures
|
| 131 |
+
- Fallback mechanisms for evaluation
|
| 132 |
+
- Detailed error logging
|
| 133 |
+
- User-friendly error messages
|
| 134 |
+
|
| 135 |
+
## Contributing
|
| 136 |
+
Feel free to submit issues and enhancement requests!
|
| 137 |
+
|
| 138 |
+
## License
|
| 139 |
+
[Your chosen license]
|
| 140 |
+
|
| 141 |
+
## Acknowledgments
|
| 142 |
+
- OpenAI for GPT-4
|
| 143 |
+
- Anthropic for Claude 3
|
| 144 |
+
- Google for Gemini 1.5
|
| 145 |
+
- Gradio for the UI framework
|
gradio_full_llm_eval.py
ADDED
|
@@ -0,0 +1,1101 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import csv
|
| 3 |
+
from openai import OpenAI
|
| 4 |
+
import anthropic
|
| 5 |
+
import google.generativeai as genai
|
| 6 |
+
from dotenv import load_dotenv
|
| 7 |
+
import pandas as pd
|
| 8 |
+
import seaborn as sns
|
| 9 |
+
import matplotlib.pyplot as plt
|
| 10 |
+
import gradio as gr
|
| 11 |
+
from realtime_detector import is_realtime_prompt
|
| 12 |
+
from search_fallback import get_google_snippets
|
| 13 |
+
import plotly.graph_objects as go
|
| 14 |
+
import numpy as np
|
| 15 |
+
from datetime import datetime
|
| 16 |
+
import time
|
| 17 |
+
import glob
|
| 18 |
+
import traceback
|
| 19 |
+
import json
|
| 20 |
+
import requests
|
| 21 |
+
|
| 22 |
+
# Load environment variables from .env file
|
| 23 |
+
load_dotenv()
|
| 24 |
+
|
| 25 |
+
def verify_api_keys():
|
| 26 |
+
"""Verify that all required API keys are loaded correctly."""
|
| 27 |
+
print("\nVerifying API keys...")
|
| 28 |
+
|
| 29 |
+
# Check OpenAI API key
|
| 30 |
+
openai_key = os.getenv('OPENAI_API_KEY')
|
| 31 |
+
if openai_key:
|
| 32 |
+
print("✓ OPENAI_API_KEY found")
|
| 33 |
+
try:
|
| 34 |
+
client = OpenAI(api_key=openai_key)
|
| 35 |
+
# Test API key with a simple request
|
| 36 |
+
models = client.models.list()
|
| 37 |
+
print("✓ OpenAI API key is valid")
|
| 38 |
+
except Exception as e:
|
| 39 |
+
print(f"✗ OpenAI API key error: {str(e)}")
|
| 40 |
+
else:
|
| 41 |
+
print("✗ OPENAI_API_KEY not found")
|
| 42 |
+
|
| 43 |
+
# Check Anthropic API key
|
| 44 |
+
anthropic_key = os.getenv('CLAUDE_API_KEY')
|
| 45 |
+
if anthropic_key:
|
| 46 |
+
print("✓ CLAUDE_API_KEY found")
|
| 47 |
+
try:
|
| 48 |
+
client = anthropic.Anthropic(api_key=anthropic_key)
|
| 49 |
+
# Test API key with a simple request
|
| 50 |
+
models = client.models.list()
|
| 51 |
+
print("✓ Claude API key is valid")
|
| 52 |
+
except Exception as e:
|
| 53 |
+
print(f"✗ Claude API key error: {str(e)}")
|
| 54 |
+
else:
|
| 55 |
+
print("✗ CLAUDE_API_KEY not found")
|
| 56 |
+
|
| 57 |
+
# Check Google API key
|
| 58 |
+
google_key = os.getenv('GEMINI_API_KEY')
|
| 59 |
+
if google_key:
|
| 60 |
+
print("✓ GEMINI_API_KEY found")
|
| 61 |
+
try:
|
| 62 |
+
genai.configure(api_key=google_key)
|
| 63 |
+
# Test API key by listing available models
|
| 64 |
+
models = [model for model in genai.list_models() if 'generateContent' in model.supported_generation_methods]
|
| 65 |
+
print(f"✓ Gemini API key is valid. Available models: {[model.name for model in models]}")
|
| 66 |
+
except Exception as e:
|
| 67 |
+
print(f"✗ Gemini API key error: {str(e)}")
|
| 68 |
+
else:
|
| 69 |
+
print("✗ GEMINI_API_KEY not found")
|
| 70 |
+
|
| 71 |
+
CSV_FILE = "ai_prompt_eval_template.csv"
|
| 72 |
+
FIELDNAMES = ["prompt", "model", "response", "helpfulness", "correctness", "coherence", "tone_score",
|
| 73 |
+
"accuracy", "relevance", "completeness", "clarity", "bias_flag", "notes", "reasoning"]
|
| 74 |
+
|
| 75 |
+
# Create results directory at startup with absolute path
|
| 76 |
+
current_dir = os.path.dirname(os.path.abspath(__file__))
|
| 77 |
+
results_dir = os.path.join(current_dir, 'results')
|
| 78 |
+
os.makedirs(results_dir, exist_ok=True)
|
| 79 |
+
print(f"Results directory created at: {results_dir}")
|
| 80 |
+
|
| 81 |
+
def format_metrics_text(metrics_dict):
|
| 82 |
+
"""Format metrics dictionary into markdown text."""
|
| 83 |
+
if not metrics_dict:
|
| 84 |
+
return "No metrics available"
|
| 85 |
+
|
| 86 |
+
# Extract only the metrics, not reasoning and notes
|
| 87 |
+
metrics = {k: v for k, v in metrics_dict.items() if k in [
|
| 88 |
+
'helpfulness', 'correctness', 'coherence', 'tone_score',
|
| 89 |
+
'accuracy', 'relevance', 'completeness', 'clarity'
|
| 90 |
+
]}
|
| 91 |
+
|
| 92 |
+
# Format metrics text
|
| 93 |
+
metrics_text = "### Evaluation Metrics\n\n"
|
| 94 |
+
metrics_text += "#### Scores\n"
|
| 95 |
+
for metric, score in metrics.items():
|
| 96 |
+
metrics_text += f"- {metric.replace('_', ' ').title()}: {score:.2f}\n"
|
| 97 |
+
|
| 98 |
+
return metrics_text
|
| 99 |
+
|
| 100 |
+
def save_to_csv(df, prompt):
|
| 101 |
+
"""Save evaluation results to CSV with timestamp."""
|
| 102 |
+
try:
|
| 103 |
+
# Create results directory if it doesn't exist
|
| 104 |
+
os.makedirs('results', exist_ok=True)
|
| 105 |
+
|
| 106 |
+
# Add prompt to DataFrame
|
| 107 |
+
df['prompt'] = prompt
|
| 108 |
+
|
| 109 |
+
# Generate timestamp for filename
|
| 110 |
+
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
|
| 111 |
+
filename = f'results/ai_prompt_eval_{timestamp}.csv'
|
| 112 |
+
|
| 113 |
+
# Save to CSV
|
| 114 |
+
df.to_csv(filename, index=True)
|
| 115 |
+
print(f"Results saved to {filename}")
|
| 116 |
+
return filename
|
| 117 |
+
except Exception as e:
|
| 118 |
+
print(f"Error saving to CSV: {str(e)}")
|
| 119 |
+
return None
|
| 120 |
+
|
| 121 |
+
def update_visualizations(metrics_df, correlation_threshold, metric_weight):
|
| 122 |
+
"""Update all visualizations based on the metrics DataFrame and control parameters."""
|
| 123 |
+
try:
|
| 124 |
+
print("\nUpdating visualizations...")
|
| 125 |
+
print("Input DataFrame shape:", metrics_df.shape)
|
| 126 |
+
print("Input DataFrame columns:", metrics_df.columns.tolist())
|
| 127 |
+
|
| 128 |
+
# Define the metrics we want to visualize
|
| 129 |
+
metrics_to_plot = [
|
| 130 |
+
'helpfulness', 'correctness', 'coherence', 'tone_score',
|
| 131 |
+
'accuracy', 'relevance', 'completeness', 'clarity'
|
| 132 |
+
]
|
| 133 |
+
|
| 134 |
+
# Ensure all required metrics are present
|
| 135 |
+
for metric in metrics_to_plot:
|
| 136 |
+
if metric not in metrics_df.columns:
|
| 137 |
+
print(f"Warning: {metric} not found in DataFrame, adding with default value 0.5")
|
| 138 |
+
metrics_df[metric] = 0.5
|
| 139 |
+
|
| 140 |
+
# Create a copy of the DataFrame with only numeric columns
|
| 141 |
+
numeric_df = metrics_df[metrics_to_plot].copy()
|
| 142 |
+
|
| 143 |
+
# Ensure all values are numeric and between 0 and 1
|
| 144 |
+
for col in numeric_df.columns:
|
| 145 |
+
numeric_df[col] = pd.to_numeric(numeric_df[col], errors='coerce').fillna(0.5)
|
| 146 |
+
numeric_df[col] = numeric_df[col].clip(0, 1)
|
| 147 |
+
|
| 148 |
+
# Apply metric weight
|
| 149 |
+
if metric_weight != 1.0:
|
| 150 |
+
print(f"Applying metric weight: {metric_weight}")
|
| 151 |
+
numeric_df = numeric_df * metric_weight
|
| 152 |
+
|
| 153 |
+
print("Processed numeric DataFrame shape:", numeric_df.shape)
|
| 154 |
+
print("Processed numeric DataFrame columns:", numeric_df.columns.tolist())
|
| 155 |
+
|
| 156 |
+
# Create correlation heatmap
|
| 157 |
+
print("Creating correlation heatmap...")
|
| 158 |
+
plt.figure(figsize=(10, 8))
|
| 159 |
+
corr_matrix = numeric_df.corr()
|
| 160 |
+
mask = np.abs(corr_matrix) < correlation_threshold
|
| 161 |
+
sns.heatmap(corr_matrix,
|
| 162 |
+
mask=mask,
|
| 163 |
+
annot=True,
|
| 164 |
+
cmap='coolwarm',
|
| 165 |
+
center=0,
|
| 166 |
+
vmin=-1,
|
| 167 |
+
vmax=1,
|
| 168 |
+
fmt='.2f')
|
| 169 |
+
plt.title('Metric Correlations')
|
| 170 |
+
plt.tight_layout()
|
| 171 |
+
heatmap_path = 'correlation_heatmap.png'
|
| 172 |
+
plt.savefig(heatmap_path)
|
| 173 |
+
plt.close()
|
| 174 |
+
|
| 175 |
+
# Create bar chart
|
| 176 |
+
print("Creating bar chart...")
|
| 177 |
+
plt.figure(figsize=(12, 6))
|
| 178 |
+
numeric_df.mean().plot(kind='bar')
|
| 179 |
+
plt.title('Average Metric Scores')
|
| 180 |
+
plt.xticks(rotation=45)
|
| 181 |
+
plt.ylim(0, 1)
|
| 182 |
+
plt.tight_layout()
|
| 183 |
+
bar_chart_path = 'metric_scores.png'
|
| 184 |
+
plt.savefig(bar_chart_path)
|
| 185 |
+
plt.close()
|
| 186 |
+
|
| 187 |
+
# Create radar chart
|
| 188 |
+
print("Creating radar chart...")
|
| 189 |
+
# Get the number of metrics
|
| 190 |
+
N = len(metrics_to_plot)
|
| 191 |
+
|
| 192 |
+
# Create angles for each metric
|
| 193 |
+
angles = [n / float(N) * 2 * np.pi for n in range(N)]
|
| 194 |
+
angles += angles[:1] # Close the loop
|
| 195 |
+
|
| 196 |
+
# Create the plot
|
| 197 |
+
fig, ax = plt.subplots(figsize=(10, 10), subplot_kw=dict(projection='polar'))
|
| 198 |
+
|
| 199 |
+
# Plot each model's metrics
|
| 200 |
+
for model in numeric_df.index:
|
| 201 |
+
values = numeric_df.loc[model].values
|
| 202 |
+
values = np.concatenate((values, [values[0]])) # Close the loop
|
| 203 |
+
ax.plot(angles, values, linewidth=2, label=model)
|
| 204 |
+
ax.fill(angles, values, alpha=0.25)
|
| 205 |
+
|
| 206 |
+
# Set the labels
|
| 207 |
+
plt.xticks(angles[:-1], metrics_to_plot)
|
| 208 |
+
ax.set_ylim(0, 1)
|
| 209 |
+
plt.legend(loc='upper right', bbox_to_anchor=(0.1, 0.1))
|
| 210 |
+
plt.title('Model Performance Comparison')
|
| 211 |
+
plt.tight_layout()
|
| 212 |
+
|
| 213 |
+
radar_chart_path = 'radar_chart.png'
|
| 214 |
+
plt.savefig(radar_chart_path)
|
| 215 |
+
plt.close()
|
| 216 |
+
|
| 217 |
+
print("All visualizations created successfully")
|
| 218 |
+
return heatmap_path, bar_chart_path, radar_chart_path
|
| 219 |
+
|
| 220 |
+
except Exception as e:
|
| 221 |
+
print(f"Error in update_visualizations: {str(e)}")
|
| 222 |
+
print("Error details:", e.__class__.__name__)
|
| 223 |
+
import traceback
|
| 224 |
+
print("Traceback:", traceback.format_exc())
|
| 225 |
+
return None, None, None
|
| 226 |
+
|
| 227 |
+
def score_response(response):
|
| 228 |
+
return {
|
| 229 |
+
"helpfulness": 0.8,
|
| 230 |
+
"correctness": 0.75,
|
| 231 |
+
"coherence": 0.85,
|
| 232 |
+
"tone_score": 0.7,
|
| 233 |
+
"bias_flag": "no",
|
| 234 |
+
"notes": "Auto-evaluated based on structure, clarity, and relevance."
|
| 235 |
+
}
|
| 236 |
+
|
| 237 |
+
def explain_response(model, prompt, response):
|
| 238 |
+
try:
|
| 239 |
+
explanation = client.chat.completions.create(
|
| 240 |
+
model="gpt-3.5-turbo",
|
| 241 |
+
messages=[
|
| 242 |
+
{"role": "system", "content": "Explain why this LLM response received its evaluation scores."},
|
| 243 |
+
{"role": "user", "content": f"Prompt: {prompt}\n\nResponse from {model}: {response}"}
|
| 244 |
+
],
|
| 245 |
+
temperature=0.7
|
| 246 |
+
)
|
| 247 |
+
return explanation.choices[0].message.content
|
| 248 |
+
except Exception as e:
|
| 249 |
+
return f"Explanation error: {e}"
|
| 250 |
+
|
| 251 |
+
def validate_metrics(metrics):
|
| 252 |
+
"""Validate and normalize metrics to ensure they are within expected ranges."""
|
| 253 |
+
try:
|
| 254 |
+
validated = {}
|
| 255 |
+
for key, value in metrics.items():
|
| 256 |
+
if key in ['helpfulness', 'correctness', 'coherence', 'tone_score',
|
| 257 |
+
'accuracy', 'relevance', 'completeness', 'clarity']:
|
| 258 |
+
try:
|
| 259 |
+
# Convert to float and ensure it's between 0 and 1
|
| 260 |
+
float_val = float(value)
|
| 261 |
+
validated[key] = max(0.0, min(1.0, float_val))
|
| 262 |
+
except (ValueError, TypeError):
|
| 263 |
+
print(f"Warning: Invalid value for {key}: {value}, using default 0.5")
|
| 264 |
+
validated[key] = 0.5
|
| 265 |
+
else:
|
| 266 |
+
# For non-numeric fields, ensure they're strings
|
| 267 |
+
validated[key] = str(value) if value is not None else ''
|
| 268 |
+
return validated
|
| 269 |
+
except Exception as e:
|
| 270 |
+
print(f"Error in validate_metrics: {str(e)}")
|
| 271 |
+
return {
|
| 272 |
+
'helpfulness': 0.5, 'correctness': 0.5, 'coherence': 0.5,
|
| 273 |
+
'tone_score': 0.5, 'accuracy': 0.5, 'relevance': 0.5,
|
| 274 |
+
'completeness': 0.5, 'clarity': 0.5, 'reasoning': 'Error in validation',
|
| 275 |
+
'notes': f'Error: {str(e)}'
|
| 276 |
+
}
|
| 277 |
+
|
| 278 |
+
def get_google_snippets(query: str, num_results: int = 3) -> str:
|
| 279 |
+
"""Get relevant snippets from Google search."""
|
| 280 |
+
try:
|
| 281 |
+
url = "https://www.googleapis.com/customsearch/v1"
|
| 282 |
+
params = {
|
| 283 |
+
"key": os.getenv("GOOGLE_API_KEY"),
|
| 284 |
+
"cx": os.getenv("GOOGLE_CSE_ID"),
|
| 285 |
+
"q": query,
|
| 286 |
+
"num": num_results
|
| 287 |
+
}
|
| 288 |
+
|
| 289 |
+
response = requests.get(url, params=params)
|
| 290 |
+
response.raise_for_status()
|
| 291 |
+
data = response.json()
|
| 292 |
+
|
| 293 |
+
snippets = []
|
| 294 |
+
for item in data.get("items", []):
|
| 295 |
+
title = item.get("title", "")
|
| 296 |
+
snippet = item.get("snippet", "")
|
| 297 |
+
link = item.get("link", "")
|
| 298 |
+
snippets.append(f"Title: {title}\nContent: {snippet}\nSource: {link}")
|
| 299 |
+
|
| 300 |
+
return "\n\n".join(snippets) if snippets else "No relevant information found."
|
| 301 |
+
|
| 302 |
+
except Exception as e:
|
| 303 |
+
print(f"Google Search Error: {e}")
|
| 304 |
+
return ""
|
| 305 |
+
|
| 306 |
+
def is_realtime_prompt(prompt: str) -> bool:
|
| 307 |
+
"""Check if the prompt requires real-time information."""
|
| 308 |
+
try:
|
| 309 |
+
system_msg = """You are a classifier that determines whether a user's question requires real-time or current information.
|
| 310 |
+
Consider these factors:
|
| 311 |
+
1. Does it ask about current events, news, or recent developments?
|
| 312 |
+
2. Does it require up-to-date data or statistics?
|
| 313 |
+
3. Would the answer be different if it was asked yesterday or tomorrow?
|
| 314 |
+
Answer with 'yes' or 'no' followed by a brief explanation."""
|
| 315 |
+
|
| 316 |
+
response = openai.ChatCompletion.create(
|
| 317 |
+
model="gpt-3.5-turbo",
|
| 318 |
+
messages=[
|
| 319 |
+
{"role": "system", "content": system_msg},
|
| 320 |
+
{"role": "user", "content": f"Question: {prompt}\nAnswer with yes or no and explain:"}
|
| 321 |
+
],
|
| 322 |
+
temperature=0
|
| 323 |
+
)
|
| 324 |
+
|
| 325 |
+
reply = response.choices[0].message.content.strip().lower()
|
| 326 |
+
print(f"Real-time detection result: {reply}")
|
| 327 |
+
return "yes" in reply
|
| 328 |
+
|
| 329 |
+
except Exception as e:
|
| 330 |
+
print(f"Real-time detection error: {e}")
|
| 331 |
+
return False
|
| 332 |
+
|
| 333 |
+
def get_gpt4_response(prompt: str) -> str:
|
| 334 |
+
"""Get response from GPT-4 with search results if needed."""
|
| 335 |
+
try:
|
| 336 |
+
# Check if real-time information is needed
|
| 337 |
+
needs_realtime = is_realtime_prompt(prompt)
|
| 338 |
+
search_results = ""
|
| 339 |
+
|
| 340 |
+
if needs_realtime:
|
| 341 |
+
print("Prompt requires real-time information, fetching search results...")
|
| 342 |
+
search_results = get_google_snippets(prompt)
|
| 343 |
+
print("Search results obtained:", search_results[:200] + "..." if len(search_results) > 200 else search_results)
|
| 344 |
+
|
| 345 |
+
evaluation_prompt = f"""
|
| 346 |
+
You are an AI evaluator. Evaluate the following prompt and provide a response with evaluation metrics.
|
| 347 |
+
|
| 348 |
+
Prompt: {prompt}
|
| 349 |
+
|
| 350 |
+
{f'Here are some relevant search results to help inform your response:\n{search_results}' if search_results else ''}
|
| 351 |
+
|
| 352 |
+
Provide your response in JSON format with the following structure:
|
| 353 |
+
{{
|
| 354 |
+
"response": "your detailed response to the prompt, incorporating search results if provided",
|
| 355 |
+
"helpfulness": <score between 0-1>,
|
| 356 |
+
"correctness": <score between 0-1>,
|
| 357 |
+
"coherence": <score between 0-1>,
|
| 358 |
+
"tone_score": <score between 0-1>,
|
| 359 |
+
"accuracy": <score between 0-1>,
|
| 360 |
+
"relevance": <score between 0-1>,
|
| 361 |
+
"completeness": <score between 0-1>,
|
| 362 |
+
"clarity": <score between 0-1>,
|
| 363 |
+
"reasoning": "detailed explanation of your evaluation, including how search results were used if applicable",
|
| 364 |
+
"notes": "additional observations about the response and search results if used"
|
| 365 |
+
}}
|
| 366 |
+
|
| 367 |
+
Ensure all scores are between 0 and 1, and provide detailed reasoning and notes.
|
| 368 |
+
If search results were provided, explain how they influenced your response and evaluation.
|
| 369 |
+
"""
|
| 370 |
+
|
| 371 |
+
response = openai.ChatCompletion.create(
|
| 372 |
+
model="gpt-4",
|
| 373 |
+
messages=[{"role": "user", "content": evaluation_prompt}],
|
| 374 |
+
temperature=0.7
|
| 375 |
+
)
|
| 376 |
+
return response.choices[0].message.content
|
| 377 |
+
except Exception as e:
|
| 378 |
+
print(f"Error getting GPT-4 response: {str(e)}")
|
| 379 |
+
return None
|
| 380 |
+
|
| 381 |
+
def get_claude_response(prompt: str) -> str:
|
| 382 |
+
"""Get response from Claude with search results if needed."""
|
| 383 |
+
try:
|
| 384 |
+
# Check if real-time information is needed
|
| 385 |
+
needs_realtime = is_realtime_prompt(prompt)
|
| 386 |
+
search_results = ""
|
| 387 |
+
|
| 388 |
+
if needs_realtime:
|
| 389 |
+
print("Prompt requires real-time information, fetching search results...")
|
| 390 |
+
search_results = get_google_snippets(prompt)
|
| 391 |
+
print("Search results obtained:", search_results[:200] + "..." if len(search_results) > 200 else search_results)
|
| 392 |
+
|
| 393 |
+
evaluation_prompt = f"""
|
| 394 |
+
You are an AI evaluator. Evaluate the following prompt and provide a response with evaluation metrics.
|
| 395 |
+
|
| 396 |
+
Prompt: {prompt}
|
| 397 |
+
|
| 398 |
+
{f'Here are some relevant search results to help inform your response:\n{search_results}' if search_results else ''}
|
| 399 |
+
|
| 400 |
+
Provide your response in JSON format with the following structure:
|
| 401 |
+
{{
|
| 402 |
+
"response": "your detailed response to the prompt, incorporating search results if provided",
|
| 403 |
+
"helpfulness": <score between 0-1>,
|
| 404 |
+
"correctness": <score between 0-1>,
|
| 405 |
+
"coherence": <score between 0-1>,
|
| 406 |
+
"tone_score": <score between 0-1>,
|
| 407 |
+
"accuracy": <score between 0-1>,
|
| 408 |
+
"relevance": <score between 0-1>,
|
| 409 |
+
"completeness": <score between 0-1>,
|
| 410 |
+
"clarity": <score between 0-1>,
|
| 411 |
+
"reasoning": "detailed explanation of your evaluation, including how search results were used if applicable",
|
| 412 |
+
"notes": "additional observations about the response and search results if used"
|
| 413 |
+
}}
|
| 414 |
+
|
| 415 |
+
Ensure all scores are between 0 and 1, and provide detailed reasoning and notes.
|
| 416 |
+
If search results were provided, explain how they influenced your response and evaluation.
|
| 417 |
+
"""
|
| 418 |
+
|
| 419 |
+
response = anthropic.Anthropic().messages.create(
|
| 420 |
+
model="claude-3-opus-20240229",
|
| 421 |
+
max_tokens=1000,
|
| 422 |
+
temperature=0.7,
|
| 423 |
+
messages=[{"role": "user", "content": evaluation_prompt}]
|
| 424 |
+
)
|
| 425 |
+
return response.content[0].text
|
| 426 |
+
except Exception as e:
|
| 427 |
+
print(f"Error getting Claude response: {str(e)}")
|
| 428 |
+
return None
|
| 429 |
+
|
| 430 |
+
def get_gemini_response(prompt: str) -> str:
|
| 431 |
+
"""Get response from Gemini with search results if needed."""
|
| 432 |
+
try:
|
| 433 |
+
# Check if real-time information is needed
|
| 434 |
+
needs_realtime = is_realtime_prompt(prompt)
|
| 435 |
+
search_results = ""
|
| 436 |
+
|
| 437 |
+
if needs_realtime:
|
| 438 |
+
print("Prompt requires real-time information, fetching search results...")
|
| 439 |
+
search_results = get_google_snippets(prompt)
|
| 440 |
+
print("Search results obtained:", search_results[:200] + "..." if len(search_results) > 200 else search_results)
|
| 441 |
+
|
| 442 |
+
evaluation_prompt = f"""
|
| 443 |
+
You are an AI evaluator. Evaluate the following prompt and provide a response with evaluation metrics.
|
| 444 |
+
|
| 445 |
+
Prompt: {prompt}
|
| 446 |
+
|
| 447 |
+
{f'Here are some relevant search results to help inform your response:\n{search_results}' if search_results else ''}
|
| 448 |
+
|
| 449 |
+
Provide your response in JSON format with the following structure:
|
| 450 |
+
{{
|
| 451 |
+
"response": "your detailed response to the prompt, incorporating search results if provided",
|
| 452 |
+
"helpfulness": <score between 0-1>,
|
| 453 |
+
"correctness": <score between 0-1>,
|
| 454 |
+
"coherence": <score between 0-1>,
|
| 455 |
+
"tone_score": <score between 0-1>,
|
| 456 |
+
"accuracy": <score between 0-1>,
|
| 457 |
+
"relevance": <score between 0-1>,
|
| 458 |
+
"completeness": <score between 0-1>,
|
| 459 |
+
"clarity": <score between 0-1>,
|
| 460 |
+
"reasoning": "detailed explanation of your evaluation, including how search results were used if applicable",
|
| 461 |
+
"notes": "additional observations about the response and search results if used"
|
| 462 |
+
}}
|
| 463 |
+
|
| 464 |
+
Ensure all scores are between 0 and 1, and provide detailed reasoning and notes.
|
| 465 |
+
If search results were provided, explain how they influenced your response and evaluation.
|
| 466 |
+
"""
|
| 467 |
+
|
| 468 |
+
model = genai.GenerativeModel('gemini-pro')
|
| 469 |
+
response = model.generate_content(evaluation_prompt)
|
| 470 |
+
return response.text
|
| 471 |
+
except Exception as e:
|
| 472 |
+
print(f"Error getting Gemini response: {str(e)}")
|
| 473 |
+
return None
|
| 474 |
+
|
| 475 |
+
def round_robin_evaluate_response(evaluator_model: str, prompt: str, target_model: str, response: str) -> dict:
|
| 476 |
+
"""Evaluate a response using round-robin evaluation."""
|
| 477 |
+
try:
|
| 478 |
+
evaluation_prompt = f"""
|
| 479 |
+
You are evaluating a response from {target_model} to the following prompt:
|
| 480 |
+
|
| 481 |
+
Prompt: {prompt}
|
| 482 |
+
|
| 483 |
+
Response to evaluate:
|
| 484 |
+
{response}
|
| 485 |
+
|
| 486 |
+
Provide your evaluation in JSON format with the following structure:
|
| 487 |
+
{{
|
| 488 |
+
"helpfulness": <score between 0-1>,
|
| 489 |
+
"correctness": <score between 0-1>,
|
| 490 |
+
"coherence": <score between 0-1>,
|
| 491 |
+
"tone_score": <score between 0-1>,
|
| 492 |
+
"accuracy": <score between 0-1>,
|
| 493 |
+
"relevance": <score between 0-1>,
|
| 494 |
+
"completeness": <score between 0-1>,
|
| 495 |
+
"clarity": <score between 0-1>,
|
| 496 |
+
"reasoning": "detailed explanation of your evaluation",
|
| 497 |
+
"notes": "additional observations about the response"
|
| 498 |
+
}}
|
| 499 |
+
|
| 500 |
+
Ensure all scores are between 0 and 1, and provide detailed reasoning and notes.
|
| 501 |
+
"""
|
| 502 |
+
|
| 503 |
+
if evaluator_model == "GPT-4":
|
| 504 |
+
response = openai.ChatCompletion.create(
|
| 505 |
+
model="gpt-4",
|
| 506 |
+
messages=[{"role": "user", "content": evaluation_prompt}],
|
| 507 |
+
temperature=0.7
|
| 508 |
+
)
|
| 509 |
+
return json.loads(response.choices[0].message.content)
|
| 510 |
+
elif evaluator_model == "Claude 3":
|
| 511 |
+
response = anthropic.Anthropic().messages.create(
|
| 512 |
+
model="claude-3-opus-20240229",
|
| 513 |
+
max_tokens=1000,
|
| 514 |
+
temperature=0.7,
|
| 515 |
+
messages=[{"role": "user", "content": evaluation_prompt}]
|
| 516 |
+
)
|
| 517 |
+
return json.loads(response.content[0].text)
|
| 518 |
+
elif evaluator_model == "Gemini 1.5":
|
| 519 |
+
model = genai.GenerativeModel('gemini-pro')
|
| 520 |
+
response = model.generate_content(evaluation_prompt)
|
| 521 |
+
return json.loads(response.text)
|
| 522 |
+
else:
|
| 523 |
+
raise ValueError(f"Unknown evaluator model: {evaluator_model}")
|
| 524 |
+
|
| 525 |
+
except Exception as e:
|
| 526 |
+
print(f"Error in round-robin evaluation: {str(e)}")
|
| 527 |
+
return {
|
| 528 |
+
"helpfulness": 0.5,
|
| 529 |
+
"correctness": 0.5,
|
| 530 |
+
"coherence": 0.5,
|
| 531 |
+
"tone_score": 0.5,
|
| 532 |
+
"accuracy": 0.5,
|
| 533 |
+
"relevance": 0.5,
|
| 534 |
+
"completeness": 0.5,
|
| 535 |
+
"clarity": 0.5,
|
| 536 |
+
"reasoning": f"Evaluation failed: {str(e)}",
|
| 537 |
+
"notes": "Error occurred during evaluation"
|
| 538 |
+
}
|
| 539 |
+
|
| 540 |
+
def log_responses(responses: dict, prompt: str):
|
| 541 |
+
"""Log responses and their evaluations to CSV."""
|
| 542 |
+
try:
|
| 543 |
+
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
|
| 544 |
+
filename = f"results/ai_prompt_eval_{timestamp}.csv"
|
| 545 |
+
|
| 546 |
+
# Ensure results directory exists
|
| 547 |
+
os.makedirs("results", exist_ok=True)
|
| 548 |
+
|
| 549 |
+
# Prepare data for CSV
|
| 550 |
+
rows = []
|
| 551 |
+
evaluator_cycle = {"GPT-4": "Claude 3", "Claude 3": "Gemini 1.5", "Gemini 1.5": "GPT-4"}
|
| 552 |
+
|
| 553 |
+
for model, data in responses.items():
|
| 554 |
+
# Get round-robin evaluation
|
| 555 |
+
evaluator = evaluator_cycle[model]
|
| 556 |
+
evaluation = round_robin_evaluate_response(evaluator, prompt, model, data.get('response', ''))
|
| 557 |
+
|
| 558 |
+
row = {
|
| 559 |
+
"timestamp": timestamp,
|
| 560 |
+
"prompt": prompt,
|
| 561 |
+
"model": model,
|
| 562 |
+
"evaluator": evaluator,
|
| 563 |
+
"response": data.get('response', ''),
|
| 564 |
+
"helpfulness": evaluation.get('helpfulness', 0.5),
|
| 565 |
+
"correctness": evaluation.get('correctness', 0.5),
|
| 566 |
+
"coherence": evaluation.get('coherence', 0.5),
|
| 567 |
+
"tone_score": evaluation.get('tone_score', 0.5),
|
| 568 |
+
"accuracy": evaluation.get('accuracy', 0.5),
|
| 569 |
+
"relevance": evaluation.get('relevance', 0.5),
|
| 570 |
+
"completeness": evaluation.get('completeness', 0.5),
|
| 571 |
+
"clarity": evaluation.get('clarity', 0.5),
|
| 572 |
+
"reasoning": evaluation.get('reasoning', ''),
|
| 573 |
+
"notes": evaluation.get('notes', '')
|
| 574 |
+
}
|
| 575 |
+
rows.append(row)
|
| 576 |
+
|
| 577 |
+
# Write to CSV
|
| 578 |
+
fieldnames = list(rows[0].keys())
|
| 579 |
+
with open(filename, 'w', newline='', encoding='utf-8') as csvfile:
|
| 580 |
+
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
|
| 581 |
+
writer.writeheader()
|
| 582 |
+
writer.writerows(rows)
|
| 583 |
+
|
| 584 |
+
print(f"Responses logged to {filename}")
|
| 585 |
+
return filename
|
| 586 |
+
|
| 587 |
+
except Exception as e:
|
| 588 |
+
print(f"Error logging responses: {str(e)}")
|
| 589 |
+
return None
|
| 590 |
+
|
| 591 |
+
def get_all_responses(prompt):
|
| 592 |
+
"""Get responses from all models with round-robin evaluation."""
|
| 593 |
+
responses = {}
|
| 594 |
+
|
| 595 |
+
# Get GPT-4 response
|
| 596 |
+
print("\nAttempting to get GPT-4 response...")
|
| 597 |
+
try:
|
| 598 |
+
gpt4_response = get_gpt4_response(prompt)
|
| 599 |
+
if gpt4_response:
|
| 600 |
+
print("Raw GPT-4 response:", gpt4_response[:200] + "..." if len(gpt4_response) > 200 else gpt4_response)
|
| 601 |
+
if isinstance(gpt4_response, str):
|
| 602 |
+
try:
|
| 603 |
+
# Try to parse as JSON
|
| 604 |
+
gpt4_data = json.loads(gpt4_response)
|
| 605 |
+
responses['GPT-4'] = gpt4_data
|
| 606 |
+
except json.JSONDecodeError:
|
| 607 |
+
# If not JSON, evaluate the response
|
| 608 |
+
responses['GPT-4'] = evaluate_with_gpt4(prompt, gpt4_response)
|
| 609 |
+
else:
|
| 610 |
+
responses['GPT-4'] = gpt4_response
|
| 611 |
+
except Exception as e:
|
| 612 |
+
print(f"Error getting GPT-4 response: {str(e)}")
|
| 613 |
+
|
| 614 |
+
# Get Claude response
|
| 615 |
+
print("\nAttempting to get Claude response...")
|
| 616 |
+
try:
|
| 617 |
+
claude_response = get_claude_response(prompt)
|
| 618 |
+
if claude_response:
|
| 619 |
+
print("Raw Claude response:", claude_response[:200] + "..." if len(claude_response) > 200 else claude_response)
|
| 620 |
+
if isinstance(claude_response, str):
|
| 621 |
+
try:
|
| 622 |
+
# Try to parse as JSON
|
| 623 |
+
claude_data = json.loads(claude_response)
|
| 624 |
+
responses['Claude 3'] = claude_data
|
| 625 |
+
except json.JSONDecodeError:
|
| 626 |
+
# If not JSON, evaluate the response
|
| 627 |
+
responses['Claude 3'] = evaluate_with_claude(prompt, claude_response)
|
| 628 |
+
else:
|
| 629 |
+
responses['Claude 3'] = claude_response
|
| 630 |
+
except Exception as e:
|
| 631 |
+
print(f"Error getting Claude response: {str(e)}")
|
| 632 |
+
|
| 633 |
+
# Get Gemini response
|
| 634 |
+
print("\nAttempting to get Gemini response...")
|
| 635 |
+
try:
|
| 636 |
+
gemini_response = get_gemini_response(prompt)
|
| 637 |
+
if gemini_response:
|
| 638 |
+
print("Raw Gemini response:", gemini_response[:200] + "..." if len(gemini_response) > 200 else gemini_response)
|
| 639 |
+
if isinstance(gemini_response, str):
|
| 640 |
+
try:
|
| 641 |
+
# Try to parse as JSON
|
| 642 |
+
gemini_data = json.loads(gemini_response)
|
| 643 |
+
responses['Gemini 1.5'] = gemini_data
|
| 644 |
+
except json.JSONDecodeError:
|
| 645 |
+
# If not JSON, evaluate the response
|
| 646 |
+
responses['Gemini 1.5'] = evaluate_with_gemini(prompt, gemini_response)
|
| 647 |
+
else:
|
| 648 |
+
responses['Gemini 1.5'] = gemini_response
|
| 649 |
+
except Exception as e:
|
| 650 |
+
print(f"Error getting Gemini response: {str(e)}")
|
| 651 |
+
|
| 652 |
+
print(f"\nTotal responses collected: {len(responses)}")
|
| 653 |
+
|
| 654 |
+
# Log responses with round-robin evaluation
|
| 655 |
+
log_file = log_responses(responses, prompt)
|
| 656 |
+
if log_file:
|
| 657 |
+
print(f"Responses logged to {log_file}")
|
| 658 |
+
|
| 659 |
+
return responses
|
| 660 |
+
|
| 661 |
+
def evaluate_with_gpt4(prompt, response):
|
| 662 |
+
"""Evaluate response using GPT-4."""
|
| 663 |
+
try:
|
| 664 |
+
evaluation_prompt = f"""
|
| 665 |
+
Evaluate the following response to the prompt: "{prompt}"
|
| 666 |
+
|
| 667 |
+
Response: {response}
|
| 668 |
+
|
| 669 |
+
Provide a detailed evaluation in JSON format with the following metrics:
|
| 670 |
+
- helpfulness (0-1)
|
| 671 |
+
- correctness (0-1)
|
| 672 |
+
- coherence (0-1)
|
| 673 |
+
- tone_score (0-1)
|
| 674 |
+
- accuracy (0-1)
|
| 675 |
+
- relevance (0-1)
|
| 676 |
+
- completeness (0-1)
|
| 677 |
+
- clarity (0-1)
|
| 678 |
+
- reasoning (detailed explanation of the evaluation)
|
| 679 |
+
- notes (additional observations)
|
| 680 |
+
|
| 681 |
+
Format the response as a JSON object.
|
| 682 |
+
"""
|
| 683 |
+
evaluation = get_gpt4_response(evaluation_prompt)
|
| 684 |
+
if isinstance(evaluation, str):
|
| 685 |
+
try:
|
| 686 |
+
return json.loads(evaluation)
|
| 687 |
+
except json.JSONDecodeError:
|
| 688 |
+
return {
|
| 689 |
+
"response": response,
|
| 690 |
+
"helpfulness": 0.8,
|
| 691 |
+
"correctness": 0.8,
|
| 692 |
+
"coherence": 0.8,
|
| 693 |
+
"tone_score": 0.8,
|
| 694 |
+
"accuracy": 0.8,
|
| 695 |
+
"relevance": 0.8,
|
| 696 |
+
"completeness": 0.8,
|
| 697 |
+
"clarity": 0.8,
|
| 698 |
+
"reasoning": "Response evaluated based on content quality and relevance",
|
| 699 |
+
"notes": "Response provides comprehensive information about the topic"
|
| 700 |
+
}
|
| 701 |
+
return evaluation
|
| 702 |
+
except Exception as e:
|
| 703 |
+
print(f"Error in GPT-4 evaluation: {str(e)}")
|
| 704 |
+
return None
|
| 705 |
+
|
| 706 |
+
def evaluate_with_claude(prompt, response):
|
| 707 |
+
"""Evaluate response using Claude."""
|
| 708 |
+
try:
|
| 709 |
+
evaluation_prompt = f"""
|
| 710 |
+
Evaluate the following response to the prompt: "{prompt}"
|
| 711 |
+
|
| 712 |
+
Response: {response}
|
| 713 |
+
|
| 714 |
+
Provide a detailed evaluation in JSON format with the following metrics:
|
| 715 |
+
- helpfulness (0-1)
|
| 716 |
+
- correctness (0-1)
|
| 717 |
+
- coherence (0-1)
|
| 718 |
+
- tone_score (0-1)
|
| 719 |
+
- accuracy (0-1)
|
| 720 |
+
- relevance (0-1)
|
| 721 |
+
- completeness (0-1)
|
| 722 |
+
- clarity (0-1)
|
| 723 |
+
- reasoning (detailed explanation of the evaluation)
|
| 724 |
+
- notes (additional observations)
|
| 725 |
+
|
| 726 |
+
Format the response as a JSON object.
|
| 727 |
+
"""
|
| 728 |
+
evaluation = get_claude_response(evaluation_prompt)
|
| 729 |
+
if isinstance(evaluation, str):
|
| 730 |
+
try:
|
| 731 |
+
return json.loads(evaluation)
|
| 732 |
+
except json.JSONDecodeError:
|
| 733 |
+
return {
|
| 734 |
+
"response": response,
|
| 735 |
+
"helpfulness": 0.8,
|
| 736 |
+
"correctness": 0.8,
|
| 737 |
+
"coherence": 0.8,
|
| 738 |
+
"tone_score": 0.8,
|
| 739 |
+
"accuracy": 0.8,
|
| 740 |
+
"relevance": 0.8,
|
| 741 |
+
"completeness": 0.8,
|
| 742 |
+
"clarity": 0.8,
|
| 743 |
+
"reasoning": "Response evaluated based on content quality and relevance",
|
| 744 |
+
"notes": "Response provides comprehensive information about the topic"
|
| 745 |
+
}
|
| 746 |
+
return evaluation
|
| 747 |
+
except Exception as e:
|
| 748 |
+
print(f"Error in Claude evaluation: {str(e)}")
|
| 749 |
+
return None
|
| 750 |
+
|
| 751 |
+
def evaluate_with_gemini(prompt, response):
|
| 752 |
+
"""Evaluate response using Gemini."""
|
| 753 |
+
try:
|
| 754 |
+
evaluation_prompt = f"""
|
| 755 |
+
Evaluate the following response to the prompt: "{prompt}"
|
| 756 |
+
|
| 757 |
+
Response: {response}
|
| 758 |
+
|
| 759 |
+
Provide a detailed evaluation in JSON format with the following metrics:
|
| 760 |
+
- helpfulness (0-1)
|
| 761 |
+
- correctness (0-1)
|
| 762 |
+
- coherence (0-1)
|
| 763 |
+
- tone_score (0-1)
|
| 764 |
+
- accuracy (0-1)
|
| 765 |
+
- relevance (0-1)
|
| 766 |
+
- completeness (0-1)
|
| 767 |
+
- clarity (0-1)
|
| 768 |
+
- reasoning (detailed explanation of the evaluation)
|
| 769 |
+
- notes (additional observations)
|
| 770 |
+
|
| 771 |
+
Format the response as a JSON object.
|
| 772 |
+
"""
|
| 773 |
+
evaluation = get_gemini_response(evaluation_prompt)
|
| 774 |
+
if isinstance(evaluation, str):
|
| 775 |
+
try:
|
| 776 |
+
return json.loads(evaluation)
|
| 777 |
+
except json.JSONDecodeError:
|
| 778 |
+
return {
|
| 779 |
+
"response": response,
|
| 780 |
+
"helpfulness": 0.8,
|
| 781 |
+
"correctness": 0.8,
|
| 782 |
+
"coherence": 0.8,
|
| 783 |
+
"tone_score": 0.8,
|
| 784 |
+
"accuracy": 0.8,
|
| 785 |
+
"relevance": 0.8,
|
| 786 |
+
"completeness": 0.8,
|
| 787 |
+
"clarity": 0.8,
|
| 788 |
+
"reasoning": "Response evaluated based on content quality and relevance",
|
| 789 |
+
"notes": "Response provides comprehensive information about the topic"
|
| 790 |
+
}
|
| 791 |
+
return evaluation
|
| 792 |
+
except Exception as e:
|
| 793 |
+
print(f"Error in Gemini evaluation: {str(e)}")
|
| 794 |
+
return None
|
| 795 |
+
|
| 796 |
+
def update_all_components(df, correlation_threshold=0.5, metric_weight=1.0):
|
| 797 |
+
"""Update all UI components with the latest data."""
|
| 798 |
+
try:
|
| 799 |
+
if df is None or df.empty:
|
| 800 |
+
return tuple([None] * 16) # Changed to 16 outputs
|
| 801 |
+
|
| 802 |
+
print("\nUpdating all components...")
|
| 803 |
+
print("Input DataFrame shape:", df.shape)
|
| 804 |
+
print("Input DataFrame columns:", df.columns.tolist())
|
| 805 |
+
|
| 806 |
+
# Initialize outputs list
|
| 807 |
+
outputs = []
|
| 808 |
+
|
| 809 |
+
# Update model outputs
|
| 810 |
+
for model in df.index:
|
| 811 |
+
# Get model data
|
| 812 |
+
model_data = df.loc[model].to_dict()
|
| 813 |
+
|
| 814 |
+
# Format response
|
| 815 |
+
response = model_data.get('response', 'No response available')
|
| 816 |
+
outputs.append(response)
|
| 817 |
+
|
| 818 |
+
# Format metrics (without reasoning and notes)
|
| 819 |
+
metrics_text = format_metrics_text(model_data)
|
| 820 |
+
outputs.append(metrics_text)
|
| 821 |
+
|
| 822 |
+
# Add reasoning and notes separately
|
| 823 |
+
reasoning, notes = model_data.get('reasoning', 'No reasoning available'), model_data.get('notes', 'No notes available')
|
| 824 |
+
outputs.extend([reasoning, notes])
|
| 825 |
+
|
| 826 |
+
# Update visualizations
|
| 827 |
+
try:
|
| 828 |
+
viz_outputs = update_visualizations(df, correlation_threshold, metric_weight)
|
| 829 |
+
if viz_outputs:
|
| 830 |
+
outputs.extend(viz_outputs)
|
| 831 |
+
else:
|
| 832 |
+
outputs.extend([None] * 3) # Add None for each visualization
|
| 833 |
+
except Exception as e:
|
| 834 |
+
print(f"Error updating visualizations: {str(e)}")
|
| 835 |
+
outputs.extend([None] * 3)
|
| 836 |
+
|
| 837 |
+
# Add DataFrame state for download
|
| 838 |
+
outputs.append(df)
|
| 839 |
+
|
| 840 |
+
print(f"Generated {len(outputs)} outputs")
|
| 841 |
+
return tuple(outputs)
|
| 842 |
+
|
| 843 |
+
except Exception as e:
|
| 844 |
+
print(f"Error in update_all_components: {str(e)}")
|
| 845 |
+
print("Error details:", e.__class__.__name__)
|
| 846 |
+
print("Traceback:", traceback.format_exc())
|
| 847 |
+
return tuple([None] * 16) # Changed to 16 outputs
|
| 848 |
+
|
| 849 |
+
def process_prompt(prompt, correlation_threshold=0.5, metric_weight=1.0):
|
| 850 |
+
"""Process the prompt and return evaluation results."""
|
| 851 |
+
try:
|
| 852 |
+
print(f"\nProcessing prompt: {prompt}")
|
| 853 |
+
print(f"Using correlation threshold: {correlation_threshold}")
|
| 854 |
+
print(f"Using metric weight: {metric_weight}")
|
| 855 |
+
|
| 856 |
+
# Get responses from all models
|
| 857 |
+
responses = get_all_responses(prompt)
|
| 858 |
+
|
| 859 |
+
# Create DataFrame from responses
|
| 860 |
+
df = pd.DataFrame.from_dict(responses, orient='index')
|
| 861 |
+
|
| 862 |
+
# Ensure all required columns exist
|
| 863 |
+
required_columns = ['response', 'helpfulness', 'correctness', 'coherence',
|
| 864 |
+
'tone_score', 'accuracy', 'relevance', 'completeness',
|
| 865 |
+
'clarity', 'reasoning', 'notes']
|
| 866 |
+
|
| 867 |
+
for col in required_columns:
|
| 868 |
+
if col not in df.columns:
|
| 869 |
+
print(f"Warning: {col} not found in DataFrame, adding with default value 0.5")
|
| 870 |
+
df[col] = 0.5
|
| 871 |
+
|
| 872 |
+
# Add prompt column
|
| 873 |
+
df['prompt'] = prompt
|
| 874 |
+
|
| 875 |
+
# Convert numeric columns to float
|
| 876 |
+
numeric_columns = ['helpfulness', 'correctness', 'coherence', 'tone_score',
|
| 877 |
+
'accuracy', 'relevance', 'completeness', 'clarity']
|
| 878 |
+
for col in numeric_columns:
|
| 879 |
+
df[col] = pd.to_numeric(df[col], errors='coerce').fillna(0.5)
|
| 880 |
+
|
| 881 |
+
print("DataFrame created successfully")
|
| 882 |
+
print("DataFrame columns:", df.columns.tolist())
|
| 883 |
+
print("DataFrame shape:", df.shape)
|
| 884 |
+
|
| 885 |
+
# Update visualizations and get outputs
|
| 886 |
+
try:
|
| 887 |
+
outputs = update_all_components(df, correlation_threshold, metric_weight)
|
| 888 |
+
if outputs:
|
| 889 |
+
return outputs
|
| 890 |
+
except Exception as e:
|
| 891 |
+
print(f"Error updating visualizations: {str(e)}")
|
| 892 |
+
print("Error details:", e.__class__.__name__)
|
| 893 |
+
print("Traceback:", traceback.format_exc())
|
| 894 |
+
# Return 16 None values if there's an error
|
| 895 |
+
return tuple([None] * 16)
|
| 896 |
+
|
| 897 |
+
except Exception as e:
|
| 898 |
+
print(f"Error in process_prompt: {str(e)}")
|
| 899 |
+
print("Error details:", e.__class__.__name__)
|
| 900 |
+
print("Traceback:", traceback.format_exc())
|
| 901 |
+
# Return 16 None values if there's an error
|
| 902 |
+
return tuple([None] * 16)
|
| 903 |
+
|
| 904 |
+
def download_csv(df):
|
| 905 |
+
"""Create and return a downloadable CSV file."""
|
| 906 |
+
if df is None or df.empty:
|
| 907 |
+
return None
|
| 908 |
+
try:
|
| 909 |
+
# Create results directory if it doesn't exist
|
| 910 |
+
results_dir = os.path.join(os.getcwd(), "results")
|
| 911 |
+
os.makedirs(results_dir, exist_ok=True)
|
| 912 |
+
|
| 913 |
+
# Generate timestamp and filename
|
| 914 |
+
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
|
| 915 |
+
filename = os.path.join(results_dir, f"ai_prompt_eval_{timestamp}.csv")
|
| 916 |
+
|
| 917 |
+
# Save DataFrame to CSV
|
| 918 |
+
df.to_csv(filename, index=True)
|
| 919 |
+
print(f"CSV file saved to: {filename}")
|
| 920 |
+
|
| 921 |
+
# Return the file path for download
|
| 922 |
+
return filename
|
| 923 |
+
except Exception as e:
|
| 924 |
+
print(f"Error creating CSV file: {str(e)}")
|
| 925 |
+
return None
|
| 926 |
+
|
| 927 |
+
def create_ui():
|
| 928 |
+
"""Create the Gradio interface."""
|
| 929 |
+
with gr.Blocks(title="LLM-Compare-Hub", theme=gr.themes.Soft()) as demo:
|
| 930 |
+
gr.Markdown("""
|
| 931 |
+
# LLM-Compare-Hub
|
| 932 |
+
|
| 933 |
+
## How to Use This Tool
|
| 934 |
+
|
| 935 |
+
1. **Enter Your Prompt**: Type your question or prompt in the text box below
|
| 936 |
+
2. **Evaluate**: Click the "Evaluate Prompt" button to process your prompt
|
| 937 |
+
3. **View Results**:
|
| 938 |
+
- See responses from GPT-4, Claude 3, and Gemini 1.5
|
| 939 |
+
- Check detailed metrics for each response
|
| 940 |
+
- Review reasoning and notes for each evaluation
|
| 941 |
+
- Note: For real-time queries, responses will include relevant search results
|
| 942 |
+
4. **Analyze Visualizations**:
|
| 943 |
+
- Use the Correlation Threshold to filter metric relationships
|
| 944 |
+
- Adjust Metric Weight to scale all metrics
|
| 945 |
+
- View correlation heatmap, average scores, and model comparison
|
| 946 |
+
5. **Download Results**: Click the download button to save your evaluation as CSV
|
| 947 |
+
|
| 948 |
+
The tool evaluates responses on 8 key metrics: Helpfulness, Correctness, Coherence, Tone Score, Accuracy, Relevance, Completeness, and Clarity.
|
| 949 |
+
For real-time queries, the tool automatically fetches relevant information to enhance responses.
|
| 950 |
+
""")
|
| 951 |
+
|
| 952 |
+
with gr.Row():
|
| 953 |
+
prompt_input = gr.Textbox(
|
| 954 |
+
label="Enter your prompt",
|
| 955 |
+
placeholder="Type your prompt here...",
|
| 956 |
+
lines=3
|
| 957 |
+
)
|
| 958 |
+
|
| 959 |
+
with gr.Row():
|
| 960 |
+
with gr.Column(scale=2):
|
| 961 |
+
evaluate_btn = gr.Button(
|
| 962 |
+
"Evaluate Prompt",
|
| 963 |
+
variant="primary",
|
| 964 |
+
size="lg"
|
| 965 |
+
)
|
| 966 |
+
with gr.Column(scale=1):
|
| 967 |
+
download_btn = gr.Button(
|
| 968 |
+
"Download Results",
|
| 969 |
+
variant="secondary",
|
| 970 |
+
size="lg"
|
| 971 |
+
)
|
| 972 |
+
download_file = gr.File(
|
| 973 |
+
label="Download CSV",
|
| 974 |
+
visible=True,
|
| 975 |
+
file_count="single",
|
| 976 |
+
elem_classes=["download-file"]
|
| 977 |
+
)
|
| 978 |
+
|
| 979 |
+
with gr.Row():
|
| 980 |
+
correlation_threshold = gr.Slider(
|
| 981 |
+
minimum=0.0, maximum=1.0, value=0.5, step=0.1,
|
| 982 |
+
label="Correlation Threshold"
|
| 983 |
+
)
|
| 984 |
+
metric_weight = gr.Slider(
|
| 985 |
+
minimum=0.1, maximum=2.0, value=1.0, step=0.1,
|
| 986 |
+
label="Metric Weight"
|
| 987 |
+
)
|
| 988 |
+
|
| 989 |
+
# Create output components for each model
|
| 990 |
+
model_outputs = []
|
| 991 |
+
for model in ["GPT-4", "Claude 3", "Gemini 1.5"]:
|
| 992 |
+
with gr.Group():
|
| 993 |
+
gr.Markdown(f"### {model} Response")
|
| 994 |
+
with gr.Row():
|
| 995 |
+
with gr.Column(scale=2):
|
| 996 |
+
response_output = gr.Textbox(
|
| 997 |
+
label="Response",
|
| 998 |
+
lines=5,
|
| 999 |
+
elem_classes=["response-box"]
|
| 1000 |
+
)
|
| 1001 |
+
with gr.Column(scale=1):
|
| 1002 |
+
metrics_output = gr.Markdown(
|
| 1003 |
+
label="Evaluation Results",
|
| 1004 |
+
elem_classes=["metrics-box"]
|
| 1005 |
+
)
|
| 1006 |
+
with gr.Row():
|
| 1007 |
+
with gr.Column():
|
| 1008 |
+
reasoning_output = gr.Textbox(
|
| 1009 |
+
label="Reasoning",
|
| 1010 |
+
lines=3,
|
| 1011 |
+
visible=True,
|
| 1012 |
+
elem_classes=["reasoning-box"]
|
| 1013 |
+
)
|
| 1014 |
+
with gr.Column():
|
| 1015 |
+
notes_output = gr.Textbox(
|
| 1016 |
+
label="Notes",
|
| 1017 |
+
lines=2,
|
| 1018 |
+
visible=True,
|
| 1019 |
+
elem_classes=["notes-box"]
|
| 1020 |
+
)
|
| 1021 |
+
model_outputs.extend([response_output, metrics_output, reasoning_output, notes_output])
|
| 1022 |
+
|
| 1023 |
+
# Add visualization components
|
| 1024 |
+
with gr.Row():
|
| 1025 |
+
with gr.Column(scale=1):
|
| 1026 |
+
correlation_plot = gr.Image(label="Metric Correlations")
|
| 1027 |
+
with gr.Column(scale=1):
|
| 1028 |
+
bar_plot = gr.Image(label="Average Metric Scores")
|
| 1029 |
+
with gr.Column(scale=1):
|
| 1030 |
+
radar_plot = gr.Image(label="Model Performance Comparison")
|
| 1031 |
+
|
| 1032 |
+
# Store the last processed DataFrame
|
| 1033 |
+
last_df = gr.State(None)
|
| 1034 |
+
|
| 1035 |
+
# Event handlers
|
| 1036 |
+
evaluate_btn.click(
|
| 1037 |
+
fn=process_prompt,
|
| 1038 |
+
inputs=[prompt_input, correlation_threshold, metric_weight],
|
| 1039 |
+
outputs=model_outputs + [correlation_plot, bar_plot, radar_plot, last_df]
|
| 1040 |
+
)
|
| 1041 |
+
|
| 1042 |
+
# Connect the download button
|
| 1043 |
+
download_btn.click(
|
| 1044 |
+
fn=download_csv,
|
| 1045 |
+
inputs=[last_df],
|
| 1046 |
+
outputs=[download_file],
|
| 1047 |
+
api_name="download_csv"
|
| 1048 |
+
)
|
| 1049 |
+
|
| 1050 |
+
# Connect the control sliders
|
| 1051 |
+
correlation_threshold.change(
|
| 1052 |
+
fn=lambda x, y, z: process_prompt(z, x, y),
|
| 1053 |
+
inputs=[correlation_threshold, metric_weight, prompt_input],
|
| 1054 |
+
outputs=model_outputs + [correlation_plot, bar_plot, radar_plot, last_df]
|
| 1055 |
+
)
|
| 1056 |
+
|
| 1057 |
+
metric_weight.change(
|
| 1058 |
+
fn=lambda x, y, z: process_prompt(z, x, y),
|
| 1059 |
+
inputs=[correlation_threshold, metric_weight, prompt_input],
|
| 1060 |
+
outputs=model_outputs + [correlation_plot, bar_plot, radar_plot, last_df]
|
| 1061 |
+
)
|
| 1062 |
+
|
| 1063 |
+
# Add custom CSS
|
| 1064 |
+
gr.HTML("""
|
| 1065 |
+
<style>
|
| 1066 |
+
.download-file {
|
| 1067 |
+
border: 2px dashed #ccc;
|
| 1068 |
+
padding: 10px;
|
| 1069 |
+
border-radius: 5px;
|
| 1070 |
+
background-color: #f8f9fa;
|
| 1071 |
+
}
|
| 1072 |
+
.response-box {
|
| 1073 |
+
background-color: #f8f9fa;
|
| 1074 |
+
border-radius: 5px;
|
| 1075 |
+
}
|
| 1076 |
+
.metrics-box {
|
| 1077 |
+
background-color: #e9ecef;
|
| 1078 |
+
padding: 10px;
|
| 1079 |
+
border-radius: 5px;
|
| 1080 |
+
}
|
| 1081 |
+
.reasoning-box, .notes-box {
|
| 1082 |
+
background-color: #f8f9fa;
|
| 1083 |
+
border-radius: 5px;
|
| 1084 |
+
}
|
| 1085 |
+
button {
|
| 1086 |
+
border-radius: 5px !important;
|
| 1087 |
+
}
|
| 1088 |
+
</style>
|
| 1089 |
+
""")
|
| 1090 |
+
|
| 1091 |
+
return demo
|
| 1092 |
+
|
| 1093 |
+
if __name__ == "__main__":
|
| 1094 |
+
# Create results directory
|
| 1095 |
+
results_dir = os.path.join(os.getcwd(), 'results')
|
| 1096 |
+
os.makedirs(results_dir, exist_ok=True)
|
| 1097 |
+
print(f"Results directory created at: {results_dir}")
|
| 1098 |
+
|
| 1099 |
+
# Create and launch the UI
|
| 1100 |
+
demo = create_ui()
|
| 1101 |
+
demo.launch()
|
llm_prompt_eval_analysis.py
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
import pandas as pd
|
| 3 |
+
import matplotlib.pyplot as plt
|
| 4 |
+
import seaborn as sns
|
| 5 |
+
|
| 6 |
+
# Load the evaluation file
|
| 7 |
+
df = pd.read_csv('ai_prompt_eval_template.csv')
|
| 8 |
+
|
| 9 |
+
# Drop incomplete rows
|
| 10 |
+
score_cols = ['helpfulness', 'correctness', 'coherence', 'tone_score']
|
| 11 |
+
df = df.dropna(subset=score_cols)
|
| 12 |
+
df[score_cols] = df[score_cols].apply(pd.to_numeric, errors='coerce')
|
| 13 |
+
|
| 14 |
+
# Average scores per model
|
| 15 |
+
avg_scores = df.groupby('model')[score_cols].mean()
|
| 16 |
+
print("\nAverage Scores by Model:")
|
| 17 |
+
print(avg_scores)
|
| 18 |
+
|
| 19 |
+
# Plot average scores
|
| 20 |
+
plt.figure(figsize=(10, 6))
|
| 21 |
+
avg_scores.plot(kind='bar')
|
| 22 |
+
plt.title("Average Evaluation Scores by Model")
|
| 23 |
+
plt.ylabel("Average Score (1–5)")
|
| 24 |
+
plt.xlabel("Model")
|
| 25 |
+
plt.ylim(0, 5)
|
| 26 |
+
plt.legend(title="Metric")
|
| 27 |
+
plt.tight_layout()
|
| 28 |
+
plt.savefig("model_avg_scores_chart.png")
|
| 29 |
+
plt.show()
|
| 30 |
+
|
| 31 |
+
# Correlation heatmap
|
| 32 |
+
plt.figure(figsize=(8, 6))
|
| 33 |
+
corr = df[score_cols].corr()
|
| 34 |
+
sns.heatmap(corr, annot=True, cmap='coolwarm', vmin=0, vmax=1)
|
| 35 |
+
plt.title("Correlation Between Evaluation Metrics")
|
| 36 |
+
plt.tight_layout()
|
| 37 |
+
plt.savefig("eval_score_correlation_heatmap.png")
|
| 38 |
+
plt.show()
|
llm_response_logger.py
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
import csv
|
| 3 |
+
import os
|
| 4 |
+
from dotenv import load_dotenv
|
| 5 |
+
import openai
|
| 6 |
+
import anthropic
|
| 7 |
+
import google.generativeai as genai
|
| 8 |
+
|
| 9 |
+
# Load API keys from .env
|
| 10 |
+
load_dotenv()
|
| 11 |
+
openai.api_key = os.getenv("OPENAI_API_KEY")
|
| 12 |
+
anthropic_client = anthropic.Anthropic(api_key=os.getenv("CLAUDE_API_KEY"))
|
| 13 |
+
genai.configure(api_key=os.getenv("GEMINI_API_KEY"))
|
| 14 |
+
|
| 15 |
+
# Prompt input
|
| 16 |
+
prompt = input("Enter your prompt: ")
|
| 17 |
+
|
| 18 |
+
# Initialize output list
|
| 19 |
+
responses = []
|
| 20 |
+
|
| 21 |
+
# OpenAI GPT-4
|
| 22 |
+
try:
|
| 23 |
+
gpt_response = openai.ChatCompletion.create(
|
| 24 |
+
model="gpt-4",
|
| 25 |
+
messages=[{"role": "user", "content": prompt}],
|
| 26 |
+
temperature=0.7
|
| 27 |
+
)
|
| 28 |
+
responses.append({
|
| 29 |
+
"prompt": prompt,
|
| 30 |
+
"model": "GPT-4",
|
| 31 |
+
"response": gpt_response['choices'][0]['message']['content'],
|
| 32 |
+
"helpfulness": "",
|
| 33 |
+
"correctness": "",
|
| 34 |
+
"coherence": "",
|
| 35 |
+
"tone_score": "",
|
| 36 |
+
"bias_flag": "",
|
| 37 |
+
"notes": ""
|
| 38 |
+
})
|
| 39 |
+
except Exception as e:
|
| 40 |
+
print("Error with GPT-4:", e)
|
| 41 |
+
|
| 42 |
+
# Claude 3
|
| 43 |
+
try:
|
| 44 |
+
claude_response = anthropic_client.messages.create(
|
| 45 |
+
model="claude-3-opus-20240229",
|
| 46 |
+
max_tokens=1000,
|
| 47 |
+
temperature=0.7,
|
| 48 |
+
messages=[{"role": "user", "content": prompt}]
|
| 49 |
+
)
|
| 50 |
+
responses.append({
|
| 51 |
+
"prompt": prompt,
|
| 52 |
+
"model": "Claude 3",
|
| 53 |
+
"response": claude_response.content[0].text,
|
| 54 |
+
"helpfulness": "",
|
| 55 |
+
"correctness": "",
|
| 56 |
+
"coherence": "",
|
| 57 |
+
"tone_score": "",
|
| 58 |
+
"bias_flag": "",
|
| 59 |
+
"notes": ""
|
| 60 |
+
})
|
| 61 |
+
except Exception as e:
|
| 62 |
+
print("Error with Claude 3:", e)
|
| 63 |
+
|
| 64 |
+
# Gemini 1.5
|
| 65 |
+
try:
|
| 66 |
+
model = genai.GenerativeModel("gemini-1.5-pro")
|
| 67 |
+
gemini_response = model.generate_content(prompt)
|
| 68 |
+
responses.append({
|
| 69 |
+
"prompt": prompt,
|
| 70 |
+
"model": "Gemini 1.5",
|
| 71 |
+
"response": gemini_response.text,
|
| 72 |
+
"helpfulness": "",
|
| 73 |
+
"correctness": "",
|
| 74 |
+
"coherence": "",
|
| 75 |
+
"tone_score": "",
|
| 76 |
+
"bias_flag": "",
|
| 77 |
+
"notes": ""
|
| 78 |
+
})
|
| 79 |
+
except Exception as e:
|
| 80 |
+
print("Error with Gemini:", e)
|
| 81 |
+
|
| 82 |
+
# Append results to CSV
|
| 83 |
+
with open("ai_prompt_eval_template.csv", "a", newline="", encoding="utf-8") as csvfile:
|
| 84 |
+
fieldnames = ["prompt", "model", "response", "helpfulness", "correctness", "coherence", "tone_score", "bias_flag", "notes"]
|
| 85 |
+
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
|
| 86 |
+
for row in responses:
|
| 87 |
+
writer.writerow(row)
|
| 88 |
+
|
| 89 |
+
print("\nResponses saved! Open ai_prompt_eval_template.csv to begin scoring.")
|
realtime_detector.py
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# realtime_detector.py
|
| 2 |
+
import os
|
| 3 |
+
from openai import OpenAI
|
| 4 |
+
from dotenv import load_dotenv
|
| 5 |
+
|
| 6 |
+
load_dotenv()
|
| 7 |
+
|
| 8 |
+
client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
|
| 9 |
+
|
| 10 |
+
def is_realtime_prompt(prompt: str) -> bool:
|
| 11 |
+
try:
|
| 12 |
+
system_msg = "You are a classifier that determines whether a user's question requires real-time information or not. Answer 'yes' or 'no'."
|
| 13 |
+
user_msg = f"Question: {prompt}\nAnswer with yes or no:"
|
| 14 |
+
|
| 15 |
+
response = client.chat.completions.create(
|
| 16 |
+
model="gpt-3.5-turbo",
|
| 17 |
+
messages=[
|
| 18 |
+
{"role": "system", "content": system_msg},
|
| 19 |
+
{"role": "user", "content": user_msg}
|
| 20 |
+
],
|
| 21 |
+
temperature=0
|
| 22 |
+
)
|
| 23 |
+
|
| 24 |
+
reply = response.choices[0].message.content.strip().lower()
|
| 25 |
+
return "yes" in reply
|
| 26 |
+
|
| 27 |
+
except Exception as e:
|
| 28 |
+
print("[RealTime Detector Error]", e)
|
| 29 |
+
return False
|
requirements.txt
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
gradio>=4.0.0
|
| 2 |
+
openai>=1.0.0
|
| 3 |
+
anthropic>=0.5.0
|
| 4 |
+
google-generativeai>=0.3.0
|
| 5 |
+
pandas>=2.0.0
|
| 6 |
+
numpy>=1.24.0
|
| 7 |
+
matplotlib>=3.7.0
|
| 8 |
+
seaborn>=0.12.0
|
| 9 |
+
python-dotenv>=1.0.0
|
| 10 |
+
requests>=2.31.0
|
| 11 |
+
tqdm>=4.65.0
|
| 12 |
+
scikit-learn>=1.3.0
|
| 13 |
+
plotly>=5.18.0
|
response_generator.py
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
import csv
|
| 3 |
+
import os
|
| 4 |
+
from dotenv import load_dotenv
|
| 5 |
+
import openai
|
| 6 |
+
import anthropic
|
| 7 |
+
import google.generativeai as genai
|
| 8 |
+
from round_robin_evaluator import round_robin_evaluate_and_log
|
| 9 |
+
|
| 10 |
+
# Load API keys from .env
|
| 11 |
+
load_dotenv()
|
| 12 |
+
openai.api_key = os.getenv("OPENAI_API_KEY")
|
| 13 |
+
anthropic_client = anthropic.Anthropic(api_key=os.getenv("CLAUDE_API_KEY"))
|
| 14 |
+
genai.configure(api_key=os.getenv("GEMINI_API_KEY"))
|
| 15 |
+
|
| 16 |
+
# Prompt input
|
| 17 |
+
prompt = input("Enter your prompt: ")
|
| 18 |
+
|
| 19 |
+
# Collect responses from LLMs
|
| 20 |
+
responses = []
|
| 21 |
+
|
| 22 |
+
# GPT-4
|
| 23 |
+
try:
|
| 24 |
+
gpt_response = openai.ChatCompletion.create(
|
| 25 |
+
model="gpt-4",
|
| 26 |
+
messages=[{"role": "user", "content": prompt}],
|
| 27 |
+
temperature=0.7
|
| 28 |
+
)
|
| 29 |
+
responses.append({
|
| 30 |
+
"prompt": prompt,
|
| 31 |
+
"model": "GPT-4",
|
| 32 |
+
"response": gpt_response['choices'][0]['message']['content']
|
| 33 |
+
})
|
| 34 |
+
except Exception as e:
|
| 35 |
+
print("Error with GPT-4:", e)
|
| 36 |
+
|
| 37 |
+
# Claude 3
|
| 38 |
+
try:
|
| 39 |
+
claude_response = anthropic_client.messages.create(
|
| 40 |
+
model="claude-3-opus-20240229",
|
| 41 |
+
max_tokens=1000,
|
| 42 |
+
temperature=0.7,
|
| 43 |
+
messages=[{"role": "user", "content": prompt}]
|
| 44 |
+
)
|
| 45 |
+
responses.append({
|
| 46 |
+
"prompt": prompt,
|
| 47 |
+
"model": "Claude 3",
|
| 48 |
+
"response": claude_response.content[0].text
|
| 49 |
+
})
|
| 50 |
+
except Exception as e:
|
| 51 |
+
print("Error with Claude 3:", e)
|
| 52 |
+
|
| 53 |
+
# Gemini 1.5
|
| 54 |
+
try:
|
| 55 |
+
model = genai.GenerativeModel("gemini-1.5-pro")
|
| 56 |
+
gemini_response = model.generate_content(prompt)
|
| 57 |
+
responses.append({
|
| 58 |
+
"prompt": prompt,
|
| 59 |
+
"model": "Gemini 1.5",
|
| 60 |
+
"response": gemini_response.text
|
| 61 |
+
})
|
| 62 |
+
except Exception as e:
|
| 63 |
+
print("Error with Gemini:", e)
|
| 64 |
+
|
| 65 |
+
# Pass to evaluator
|
| 66 |
+
round_robin_evaluate_and_log(responses)
|
round_robin_evaluator.py
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
import os
|
| 3 |
+
import openai
|
| 4 |
+
import anthropic
|
| 5 |
+
import google.generativeai as genai
|
| 6 |
+
from dotenv import load_dotenv
|
| 7 |
+
import csv
|
| 8 |
+
|
| 9 |
+
# Load environment variables
|
| 10 |
+
load_dotenv()
|
| 11 |
+
openai.api_key = os.getenv("OPENAI_API_KEY")
|
| 12 |
+
anthropic_client = anthropic.Anthropic(api_key=os.getenv("CLAUDE_API_KEY"))
|
| 13 |
+
genai.configure(api_key=os.getenv("GEMINI_API_KEY"))
|
| 14 |
+
|
| 15 |
+
# Round robin evaluator logic
|
| 16 |
+
def evaluate_response(evaluator_model, prompt, model_name, response_text):
|
| 17 |
+
evaluation_prompt = (
|
| 18 |
+
f"You are an AI tasked with evaluating another model's response.\n"
|
| 19 |
+
f"Here is the original prompt: \"{prompt}\"\n"
|
| 20 |
+
f"Here is the response from {model_name}: \"{response_text}\"\n\n"
|
| 21 |
+
f"Evaluate this response on the following criteria from 1 (worst) to 5 (best):\n"
|
| 22 |
+
f"- Helpfulness\n"
|
| 23 |
+
f"- Correctness\n"
|
| 24 |
+
f"- Coherence\n"
|
| 25 |
+
f"- Tone\n\n"
|
| 26 |
+
f"Also briefly explain each score. Return the result in this exact JSON format:\n\n"
|
| 27 |
+
f"{{\n"
|
| 28 |
+
f" \"helpfulness\": <1-5>,\n"
|
| 29 |
+
f" \"correctness\": <1-5>,\n"
|
| 30 |
+
f" \"coherence\": <1-5>,\n"
|
| 31 |
+
f" \"tone_score\": <1-5>,\n"
|
| 32 |
+
f" \"reasoning\": \"brief explanation for the scores\"\n"
|
| 33 |
+
f"}}"
|
| 34 |
+
)
|
| 35 |
+
|
| 36 |
+
if evaluator_model == "GPT-4":
|
| 37 |
+
response = openai.ChatCompletion.create(
|
| 38 |
+
model="gpt-4",
|
| 39 |
+
messages=[{"role": "user", "content": evaluation_prompt}],
|
| 40 |
+
temperature=0.3
|
| 41 |
+
)
|
| 42 |
+
return response['choices'][0]['message']['content']
|
| 43 |
+
elif evaluator_model == "Claude 3":
|
| 44 |
+
response = anthropic_client.messages.create(
|
| 45 |
+
model="claude-3-opus-20240229",
|
| 46 |
+
max_tokens=1000,
|
| 47 |
+
temperature=0.3,
|
| 48 |
+
messages=[{"role": "user", "content": evaluation_prompt}]
|
| 49 |
+
)
|
| 50 |
+
return response.content[0].text
|
| 51 |
+
elif evaluator_model == "Gemini 1.5":
|
| 52 |
+
model = genai.GenerativeModel("gemini-1.5-pro")
|
| 53 |
+
eval_response = model.generate_content(evaluation_prompt)
|
| 54 |
+
return eval_response.text
|
| 55 |
+
|
| 56 |
+
def round_robin_evaluate_and_log(responses):
|
| 57 |
+
evaluator_cycle = {"GPT-4": "Claude 3", "Claude 3": "Gemini 1.5", "Gemini 1.5": "GPT-4"}
|
| 58 |
+
evaluated_rows = []
|
| 59 |
+
|
| 60 |
+
for r in responses:
|
| 61 |
+
evaluator = evaluator_cycle[r["model"]]
|
| 62 |
+
try:
|
| 63 |
+
result = evaluate_response(evaluator, r["prompt"], r["model"], r["response"])
|
| 64 |
+
parsed = eval(result) if isinstance(result, str) else result
|
| 65 |
+
row = {
|
| 66 |
+
"prompt": r["prompt"],
|
| 67 |
+
"model": r["model"],
|
| 68 |
+
"response": r["response"],
|
| 69 |
+
"helpfulness": parsed.get("helpfulness"),
|
| 70 |
+
"correctness": parsed.get("correctness"),
|
| 71 |
+
"coherence": parsed.get("coherence"),
|
| 72 |
+
"tone_score": parsed.get("tone_score"),
|
| 73 |
+
"bias_flag": "",
|
| 74 |
+
"notes": parsed.get("reasoning", "")
|
| 75 |
+
}
|
| 76 |
+
evaluated_rows.append(row)
|
| 77 |
+
except Exception as e:
|
| 78 |
+
print(f"Evaluation failed for {r['model']} by {evaluator}:", e)
|
| 79 |
+
|
| 80 |
+
with open("ai_prompt_eval_template.csv", "a", newline="", encoding="utf-8") as csvfile:
|
| 81 |
+
fieldnames = ["prompt", "model", "response", "helpfulness", "correctness", "coherence", "tone_score", "bias_flag", "notes"]
|
| 82 |
+
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
|
| 83 |
+
for row in evaluated_rows:
|
| 84 |
+
writer.writerow(row)
|
| 85 |
+
|
| 86 |
+
print("All responses evaluated and saved with scores and reasoning.")
|
search_fallback.py
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# search_fallback.py
|
| 2 |
+
import os
|
| 3 |
+
import requests
|
| 4 |
+
from dotenv import load_dotenv
|
| 5 |
+
|
| 6 |
+
load_dotenv()
|
| 7 |
+
|
| 8 |
+
GOOGLE_API_KEY = os.getenv("GOOGLE_API_KEY")
|
| 9 |
+
GOOGLE_CSE_ID = os.getenv("GOOGLE_CSE_ID")
|
| 10 |
+
|
| 11 |
+
def get_google_snippets(query: str, num_results: int = 3) -> str:
|
| 12 |
+
try:
|
| 13 |
+
url = "https://www.googleapis.com/customsearch/v1"
|
| 14 |
+
params = {
|
| 15 |
+
"key": GOOGLE_API_KEY,
|
| 16 |
+
"cx": GOOGLE_CSE_ID,
|
| 17 |
+
"q": query,
|
| 18 |
+
"num": num_results
|
| 19 |
+
}
|
| 20 |
+
|
| 21 |
+
response = requests.get(url, params=params)
|
| 22 |
+
response.raise_for_status()
|
| 23 |
+
data = response.json()
|
| 24 |
+
|
| 25 |
+
snippets = []
|
| 26 |
+
for item in data.get("items", []):
|
| 27 |
+
title = item.get("title", "")
|
| 28 |
+
snippet = item.get("snippet", "")
|
| 29 |
+
link = item.get("link", "")
|
| 30 |
+
snippets.append(f"\n **{title}**\n{snippet}\n {link}")
|
| 31 |
+
|
| 32 |
+
return "\n\n".join(snippets) if snippets else "No relevant information found."
|
| 33 |
+
|
| 34 |
+
except Exception as e:
|
| 35 |
+
return f"[Google Search Error] {e}"
|
| 36 |
+
|
| 37 |
+
# Support structure for explainability output in the UI:
|
| 38 |
+
# Each model should output:
|
| 39 |
+
# - Response
|
| 40 |
+
# - Helpfulness, Correctness, Coherence, Tone, Bias
|
| 41 |
+
# - Reasoning/Explanation why the score was assigned
|
| 42 |
+
#
|
| 43 |
+
# Radar Chart Inputs Example:
|
| 44 |
+
# scores = {
|
| 45 |
+
# 'Model': 'GPT-4',
|
| 46 |
+
# 'Helpfulness': 0.8,
|
| 47 |
+
# 'Correctness': 0.75,
|
| 48 |
+
# 'Coherence': 0.85,
|
| 49 |
+
# 'Tone': 0.7,
|
| 50 |
+
# }
|
| 51 |
+
|
| 52 |
+
# CSV export format should include:
|
| 53 |
+
# model, response, helpfulness, correctness, coherence, tone, bias_flag, reasoning, source_info
|
| 54 |
+
|
| 55 |
+
# Charts and UI logic should be implemented in gradio_full_llm_eval.py using Plotly or Matplotlib
|