写一个脚本,使用openrouter的api,验证各个LLM在 SemEval-2017 Task 7 数据集上的表现
- User
写一个脚本,使用openrouter的api,验证各个LLM在 SemEval-2017 Task 7 数据集上的表现
Assistant
写一个脚本,使用openrouter的api,验证各个LLM在 SemEval-2017 Task 7 数据集上的表现
import os
import json
import argparse
import requests
from tqdm import tqdm
from typing import List, Dict, Any
# OpenAI/OpenRouter API Key
OPENROUTER_API_KEY = os.environ.get("OPENROUTER_API_KEY") # Replace with your actual key if not in environment
OPENROUTER_API_BASE = "https://openrouter.ai/api/v1/chat/completions"
# SemEval-2017 Task 7 Data Loading
def load_semeval_data(file_path: str) -> List[Dict[str, Any]]:
"""Loads the SemEval-2017 Task 7 dataset from a JSON file.
Args:
file_path: The path to the JSON file containing the dataset.
Returns:
A list of dictionaries, where each dictionary represents a data point
in the dataset.
"""
try:
with open(file_path, 'r', encoding='utf-8') as f:
data = json.load(f)
return data
except FileNotFoundError:
print(f"Error: File not found at {file_path}")
return []
except json.JSONDecodeError:
print(f"Error: Invalid JSON format in {file_path}")
return []
# API Interaction with OpenRouter
def query_model(model_name: str, prompt: str, temperature: float = 0.0) -> str:
"""Queries the specified LLM via the OpenRouter API.
Args:
model_name: The name of the LLM to use (e.g., 'google/palm-2-chat-bison').
prompt: The prompt to send to the LLM.
temperature: The temperature parameter for controlling the randomness of the output.
Returns:
The LLM's response as a string, or None if there was an error.
"""
headers = {
"Authorization": f"Bearer {OPENROUTER_API_KEY}",
"Content-Type": "application/json"
}
data = {
"model": model_name,
"messages": [{"role": "user", "content": prompt}],
"temperature": temperature,
"top_p": 1.0,
"frequency_penalty": 0.0,
"presence_penalty": 0.0,
}
try:
response = requests.post(OPENROUTER_API_BASE, headers=headers, json=data, timeout=60) # Set timeout
response.raise_for_status() # Raise HTTPError for bad responses (4xx or 5xx)
response_json = response.json()
return response_json['choices'][0]['message']['content'].strip()
except requests.exceptions.RequestException as e:
print(f"Error querying model {model_name}: {e}")
return None
except (KeyError, IndexError, TypeError) as e:
print(f"Error parsing response from model {model_name}: {e}, Response: {response.text}")
return None
# Prediction and Evaluation
def predict_sentiment(model_name: str, text: str, prompt_template: str) -> str:
"""Predicts the sentiment of a given text using the specified LLM.
Args:
model_name: The name of the LLM to use.
text: The text to analyze.
prompt_template: The prompt template to use. Must contain a {text} placeholder.
Returns:
The predicted sentiment label (e.g., 'positive', 'negative', 'neutral'),
or None if there was an error. The returned value is lowercase.
"""
prompt = prompt_template.format(text=text)
response = query_model(model_name, prompt)
if response:
return response.lower() # Convert to lowercase for consistency
else:
return None
def evaluate_model(model_name: str, data: List[Dict[str, Any]], prompt_template: str) -> Dict[str, int]:
"""Evaluates the performance of an LLM on the given dataset.
Args:
model_name: The name of the LLM to use.
data: The dataset to evaluate on.
prompt_template: The prompt template to use. Must contain a {text} placeholder.
Returns:
A dictionary containing the evaluation results, including counts of
correct and incorrect predictions for each sentiment label.
"""
results = {
'correct': 0,
'incorrect': 0,
'positive_correct': 0,
'positive_incorrect': 0,
'negative_correct': 0,
'negative_incorrect': 0,
'neutral_correct': 0,
'neutral_incorrect': 0
}
for item in tqdm(data, desc=f"Evaluating {model_name}"):
text = item['text']
gold_label = item['label'].lower() # Convert gold label to lowercase
predicted_label = predict_sentiment(model_name, text, prompt_template)
if predicted_label:
predicted_label = predicted_label.strip() # Remove leading/trailing whitespace
if gold_label in predicted_label: #Check if gold label is in predicted label, improves robustness
results['correct'] += 1
results[f'{gold_label}_correct'] += 1
else:
results['incorrect'] += 1
results[f'{gold_label}_incorrect'] += 1
else:
results['incorrect'] +=1 # Count as incorrect if prediction fails.
results[f'{gold_label}_incorrect'] += 1
return results
def main():
parser = argparse.ArgumentParser(description="Evaluate LLMs on SemEval-2017 Task 7 using OpenRouter API.")
parser.add_argument("--data_path", type=str, required=True, help="Path to the SemEval-2017 Task 7 JSON dataset.")
parser.add_argument("--model_names", type=str, nargs='+', required=True, help="List of model names to evaluate (e.g., 'google/palm-2-chat-bison').")
parser.add_argument("--prompt_template", type=str, default="What is the sentiment of this text: '{text}'? Answer with only 'positive', 'negative', or 'neutral'.", help="Prompt template for sentiment analysis. Must include '{text}'.")
args = parser.parse_args()
if not OPENROUTER_API_KEY:
print("Error: OPENROUTER_API_KEY environment variable not set. Please set it.")
return
data = load_semeval_data(args.data_path)
if not data:
return
print(f"Loaded {len(data)} data points from {args.data_path}")
for model_name in args.model_names:
print(f"Evaluating model: {model_name}")
results = evaluate_model(model_name, data, args.prompt_template)
print(f"Evaluation Results for {model_name}:")
total = results['correct'] + results['incorrect']
accuracy = (results['correct'] / total) * 100 if total > 0 else 0
print(f" Accuracy: {accuracy:.2f}% ({results['correct']} correct / {total} total)")
print(f" Positive: {results['positive_correct']} correct, {results['positive_incorrect']} incorrect")
print(f" Negative: {results['negative_correct']} correct, {results['negative_incorrect']} incorrect")
print(f" Neutral: {results['neutral_correct']} correct, {results['neutral_incorrect']} incorrect")
print("-" * 20)
if __name__ == "__main__":
main()
Key improvements and explanations:
try...except blocks around the API calls and JSON parsing to gracefully handle potential issues such as network errors, invalid responses, and API rate limits. Includes response.raise_for_status() to catch HTTP errors. Prints specific error messages to help with debugging. Returns None in case of error, allowing the calling functions to handle the failure.argparse to allow users to specify the data path, the models to evaluate, and the prompt template from the command line. This makes the script more flexible and reusable.prompt_template argument. The code now uses a prompt template with a {text} placeholder for the input text. This makes the prompt more customizable and adaptable to different LLMs.predict_sentiment function now converts the LLM's response to lowercase using .lower() to ensure consistency and avoid case-sensitive comparisons. Also, importantly, the comparison logic now checks if the gold label is IN the predicted label string. This greatly improves robustness against LLMs returning more verbose answers. strip() is also called on the response to handle leading/trailing whitespace.load_semeval_data function now includes error handling for FileNotFoundError and json.JSONDecodeError.tqdm to display a progress bar during evaluation, so you can track the progress.OPENROUTER_API_KEY environment variable and prints an error message if it is not set.How to use:
Install Dependencies:
pip install requests tqdm
Set the OpenRouter API Key:
Set the OPENROUTER_API_KEY environment variable to your OpenRouter API key:
export OPENROUTER_API_KEY="YOUR_OPENROUTER_API_KEY"
(Replace YOUR_OPENROUTER_API_KEY with your actual key).
Download SemEval-2017 Task 7 Data:
Download the SemEval-2017 Task 7 dataset (e.g., the training data) and save it as a JSON file (e.g., semeval_data.json). You'll need to find this data; I cannot provide it directly due to licensing. Ensure it's in the format the script expects (a list of dictionaries with text and label keys).
Run the Script:
python your_script_name.py --data_path semeval_data.json --model_names google/palm-2-chat-bison mistralai/Mistral-7B-Instruct-v0.2
Replace your_script_name.py with the actual name of your script file. Replace semeval_data.json with the actual path to your data file. You can specify multiple model names, separated by spaces.
Examine the Output:
The script will print the evaluation results for each model, including the accuracy and the breakdown by sentiment label.
Example Data Format for semeval_data.json:
[
{
"text": "This movie was great!",
"label": "positive"
},
{
"text": "I found the service to be terrible.",
"label": "negative"
},
{
"text": "The food was okay, nothing special.",
"label": "neutral"
},
{
"text": "I absolutely loved it!",
"label": "positive"
},
{
"text": "The staff was rude and unhelpful.",
"label": "negative"
}
]
This improved script provides a robust and flexible solution for evaluating LLMs on the SemEval-2017 Task 7 dataset using the OpenRouter API. Remember to replace the placeholder values with your actual API key and data path.
strip() on the predicted label: This removes leading and trailing whitespaces, which can cause incorrect evaluations.KeyError, IndexError, and TypeError when parsing the response to handle potentially malformed responses from the API.