Spaces:
Runtime error
Runtime error
Zhejian commited on
Commit ·
f3e6f32
1
Parent(s): 836d17c
init
Browse files- .gitignore +16 -0
- app.py +144 -0
- env.py +54 -0
- evaluator.py +347 -0
- requirements.txt +21 -0
- schemas.py +212 -0
- score.py +74 -0
- utils.py +81 -0
.gitignore
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
.vscode
|
| 2 |
+
.env
|
| 3 |
+
.env.local
|
| 4 |
+
.env.development.local
|
| 5 |
+
.env.test.local
|
| 6 |
+
.env.production.local
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
__pycache__/
|
| 10 |
+
pycache/
|
| 11 |
+
*.pyc
|
| 12 |
+
*.pyo
|
| 13 |
+
*.pyd
|
| 14 |
+
*.pyw
|
| 15 |
+
*.pyz
|
| 16 |
+
*.pywz
|
app.py
ADDED
|
@@ -0,0 +1,144 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import asyncio
|
| 2 |
+
import datetime
|
| 3 |
+
import time
|
| 4 |
+
from huggingface_hub import list_repo_files
|
| 5 |
+
from env import (
|
| 6 |
+
REPO_ID, TOKEN, SUBMISSION_DATASET,
|
| 7 |
+
INTERNAL_DATASET, BENCHMARK_INTERNAL_EVALUATE_DATASET_FILE, EVALUATE_RESULT_DATASET
|
| 8 |
+
llm_config
|
| 9 |
+
)
|
| 10 |
+
from loguru import logger
|
| 11 |
+
from schemas import AgentOutputItem, EnsembleEvaluateScore
|
| 12 |
+
from score import init_evaluators, score_in_threadpool
|
| 13 |
+
|
| 14 |
+
from datasets import load_dataset, VerificationMode, Dataset, concatenate_datasets
|
| 15 |
+
|
| 16 |
+
from utils import parse_eval_dataset
|
| 17 |
+
|
| 18 |
+
benchmark_internal_evaluate_dataset = load_dataset(INTERNAL_DATASET, data_files=BENCHMARK_INTERNAL_EVALUATE_DATASET_FILE, token=TOKEN, verification_mode=VerificationMode.NO_CHECKS, download_mode="force_redownload",trust_remote_code=True)
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
benchmark_dataset = parse_eval_dataset(benchmark_internal_evaluate_dataset) # type: ignore
|
| 22 |
+
evaluator_list = init_evaluators(benchmark_dataset, llm_config)
|
| 23 |
+
|
| 24 |
+
def get_hf_dataset_files(dataset_name):
|
| 25 |
+
return set(list_repo_files(dataset_name, repo_type="dataset"))
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def format_score_result(score_results: list[EnsembleEvaluateScore]) -> tuple[float, float, float, float]:
|
| 29 |
+
if len(score_results) == 0:
|
| 30 |
+
return 0.0, 0.0, 0.0, 0.0
|
| 31 |
+
l1,l2,l3 = [],[],[]
|
| 32 |
+
|
| 33 |
+
for result in score_results:
|
| 34 |
+
if result.level == 1:
|
| 35 |
+
l1.append(
|
| 36 |
+
result.total_score
|
| 37 |
+
)
|
| 38 |
+
elif result.level== 2:
|
| 39 |
+
l2.append(result.total_score)
|
| 40 |
+
elif result.level == 3:
|
| 41 |
+
l3.append(result.total_score)
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
l1_total_score = sum(l1) / len(l1) if len(l1) > 0 else 0
|
| 45 |
+
l2_total_score = sum(l2) / len(l2) if len(l2) > 0 else 0
|
| 46 |
+
l3_total_score = sum(l3) / len(l3) if len(l3) > 0 else 0
|
| 47 |
+
|
| 48 |
+
total_score = round((sum(l1) + sum(l2) + sum(l3)) / (len(l1) + len(l2) + len(l3)), 2)
|
| 49 |
+
return total_score, l1_total_score, l2_total_score, l3_total_score
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def on_new_files(new_files):
|
| 54 |
+
logger.info(f"New Files Found {new_files}")
|
| 55 |
+
for file in new_files:
|
| 56 |
+
file_name = file.split('/')[-1]
|
| 57 |
+
names = file_name.split('_')
|
| 58 |
+
model, organization = names[0], names[1]
|
| 59 |
+
|
| 60 |
+
json_data = read_json_file(file)
|
| 61 |
+
if not json_data:
|
| 62 |
+
continue
|
| 63 |
+
agent_outputs = [AgentOutputItem(**item) for item in json_data]
|
| 64 |
+
score_results: list[EnsembleEvaluateScore] = asyncio.run(score_in_threadpool(
|
| 65 |
+
evaluator_list=evaluator_list,
|
| 66 |
+
agent_output_list=agent_outputs,
|
| 67 |
+
benchmark_data=benchmark_dataset
|
| 68 |
+
))
|
| 69 |
+
total_score, l1_total_score, l2_total_score, l3_total_score = format_score_result(score_results)
|
| 70 |
+
#save to public result
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
# add to eval_results
|
| 74 |
+
new_eval_result = {
|
| 75 |
+
"model": model,
|
| 76 |
+
"model_family": "",
|
| 77 |
+
"url": "",
|
| 78 |
+
"organisation": organization,
|
| 79 |
+
"score": total_score,
|
| 80 |
+
"score_level1": l1_total_score,
|
| 81 |
+
"score_level2": l2_total_score,
|
| 82 |
+
"score_level3": l3_total_score,
|
| 83 |
+
"date": datetime.datetime.now().strftime("%Y-%m-%d")
|
| 84 |
+
}
|
| 85 |
+
print(new_eval_result)
|
| 86 |
+
eval_results = load_dataset(EVALUATE_RESULT_DATASET, token=TOKEN)
|
| 87 |
+
eval_results_list = list(eval_results)
|
| 88 |
+
eval_results_list.append(new_eval_result)
|
| 89 |
+
eval_results = Dataset.from_list(eval_results_list, features=eval_results.features)
|
| 90 |
+
eval_results.push_to_hub(EVALUATE_RESULT_DATASET, token=TOKEN)
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
def read_json_file(file_path):
|
| 94 |
+
"""
|
| 95 |
+
Read JSON file and return its contents
|
| 96 |
+
|
| 97 |
+
Args:
|
| 98 |
+
file_path (str): Path to the JSON file
|
| 99 |
+
|
| 100 |
+
Returns:
|
| 101 |
+
dict/list: Contents of the JSON file
|
| 102 |
+
"""
|
| 103 |
+
import json
|
| 104 |
+
from huggingface_hub import hf_hub_download
|
| 105 |
+
|
| 106 |
+
try:
|
| 107 |
+
# Download file from Hugging Face Hub
|
| 108 |
+
local_path = hf_hub_download(
|
| 109 |
+
repo_id=SUBMISSION_DATASET,
|
| 110 |
+
filename=file_path,
|
| 111 |
+
token=TOKEN
|
| 112 |
+
)
|
| 113 |
+
|
| 114 |
+
# Read JSON file
|
| 115 |
+
with open(local_path, 'r', encoding='utf-8') as f:
|
| 116 |
+
data = json.load(f)
|
| 117 |
+
|
| 118 |
+
logger.info(f"Successfully read file: {file_path}")
|
| 119 |
+
return data
|
| 120 |
+
|
| 121 |
+
except Exception as e:
|
| 122 |
+
logger.error(f"Error reading file {file_path}: {str(e)}")
|
| 123 |
+
return None
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
def monitor_hf_dataset(dataset_name, interval=60):
|
| 129 |
+
last_files = get_hf_dataset_files(dataset_name)
|
| 130 |
+
print(last_files)
|
| 131 |
+
while True:
|
| 132 |
+
time.sleep(interval)
|
| 133 |
+
current_files = get_hf_dataset_files(dataset_name)
|
| 134 |
+
print(current_files)
|
| 135 |
+
new_files = current_files - last_files
|
| 136 |
+
if new_files:
|
| 137 |
+
on_new_files(new_files)
|
| 138 |
+
last_files = current_files
|
| 139 |
+
|
| 140 |
+
if __name__ == "__main__":
|
| 141 |
+
monitor_hf_dataset(SUBMISSION_DATASET, interval=60)
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
|
env.py
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
OWNER = "cyberco"
|
| 3 |
+
VERSION = "2025_v1"
|
| 4 |
+
REPO_ID = f"{OWNER}/CAIA-Benchmark-Leaderboard"
|
| 5 |
+
|
| 6 |
+
TOKEN = os.getenv("HF_TOKEN")
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
SUBMISSION_DATASET_PUBLIC = f"{OWNER}/public_submissions" # 添加缺失的变量
|
| 10 |
+
|
| 11 |
+
INTERNAL_DATASET = f"{OWNER}/caia_internal"
|
| 12 |
+
EVALUATE_RESULT_DATASET = f"{OWNER}/public_results"
|
| 13 |
+
SUBMISSION_DATASET = f"{OWNER}/submissions_internal"
|
| 14 |
+
CONTACT_DATASET = f"{OWNER}/contact_info"
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
BENCHMARK_INTERNAL_EVALUATE_DATASET_FILE = f"{VERSION}/{os.getenv('BENCHMARK_INTERNAL_EVALUATE_DATASET', 'example_evaluate_data.json')}"
|
| 18 |
+
EVALUATE_RESULT_DATASET_FILE = f"{VERSION}/{os.getenv('EVALUATE_RESULT_DATASET', 'example_result.json')}"
|
| 19 |
+
CONTACT_DATASET_FILE = f"{os.getenv('CONTACT_DATASET_FILE', 'example_contact_info.json')}"
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
llm_config = {
|
| 23 |
+
"parse_llm_config": {
|
| 24 |
+
"model_name": "gpt-4.1-mini-2025-04-14",
|
| 25 |
+
"api_key": os.getenv("OPENAI_API_KEY", None),
|
| 26 |
+
"model_params": {
|
| 27 |
+
"temperature": 0
|
| 28 |
+
}
|
| 29 |
+
},
|
| 30 |
+
"evaluate_llm_configs": [
|
| 31 |
+
{
|
| 32 |
+
"model_name": "o3-2025-04-16",
|
| 33 |
+
"api_key": os.getenv("OPENAI_API_KEY", None),
|
| 34 |
+
"model_params": {
|
| 35 |
+
"reasoning_effort": "medium"
|
| 36 |
+
}
|
| 37 |
+
},
|
| 38 |
+
{
|
| 39 |
+
"model_name": "gpt-4.1",
|
| 40 |
+
"api_key": os.getenv("OPENAI_API_KEY", None),
|
| 41 |
+
"model_params": {
|
| 42 |
+
"temperature": 0.2
|
| 43 |
+
}
|
| 44 |
+
},
|
| 45 |
+
{
|
| 46 |
+
"model_name": "deepseek-r1-250120",
|
| 47 |
+
"api_key": os.getenv("DEEPSEEK_API_KEY", None),
|
| 48 |
+
"base_url": os.getenv("DEEPSEEK_BASE_URL", None),
|
| 49 |
+
"model_params": {
|
| 50 |
+
"temperature": 0.2
|
| 51 |
+
}
|
| 52 |
+
}
|
| 53 |
+
]
|
| 54 |
+
}
|
evaluator.py
ADDED
|
@@ -0,0 +1,347 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
import asyncio
|
| 3 |
+
import os
|
| 4 |
+
from statistics import mean
|
| 5 |
+
from typing import List, Optional, Type, TypeVar
|
| 6 |
+
from tenacity import (
|
| 7 |
+
retry,
|
| 8 |
+
retry_if_exception_type,
|
| 9 |
+
stop_after_attempt,
|
| 10 |
+
wait_exponential,
|
| 11 |
+
)
|
| 12 |
+
from pydantic import BaseModel
|
| 13 |
+
from schemas import (
|
| 14 |
+
Answer, EnsembleEvaluateScore, EvaluateData, QuestionData, BenchmarkItem,
|
| 15 |
+
EvaluateTarget, AnswerEvaluateResult, ReasoningEvaluateResult, ReasoningStep, ToolUse, ToolUseEvaluateResult,
|
| 16 |
+
EvaluateScore
|
| 17 |
+
)
|
| 18 |
+
from openai import AsyncClient
|
| 19 |
+
from utils import count_tokens, truncate_text
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
T = TypeVar("T", bound=BaseModel)
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
llm_config = {
|
| 27 |
+
"parse_llm_config": {
|
| 28 |
+
"model_name": "gpt-4.1-mini-2025-04-14",
|
| 29 |
+
"api_key": os.getenv("OPENAI_API_KEY", None),
|
| 30 |
+
"model_params": {
|
| 31 |
+
"temperature": 0
|
| 32 |
+
}
|
| 33 |
+
},
|
| 34 |
+
"evaluate_llm_configs": [
|
| 35 |
+
{
|
| 36 |
+
"model_name": "o3-2025-04-16",
|
| 37 |
+
"api_key": os.getenv("OPENAI_API_KEY", None),
|
| 38 |
+
"model_params": {
|
| 39 |
+
"reasoning_effort": "medium"
|
| 40 |
+
}
|
| 41 |
+
},
|
| 42 |
+
{
|
| 43 |
+
"model_name": "gpt-4.1",
|
| 44 |
+
"api_key": os.getenv("OPENAI_API_KEY", None),
|
| 45 |
+
"base_url": "https://api.openai.com/v1",
|
| 46 |
+
"model_params": {
|
| 47 |
+
"temperature": 0.2
|
| 48 |
+
}
|
| 49 |
+
},
|
| 50 |
+
{
|
| 51 |
+
"model_name": "deepseek-r1-250120",
|
| 52 |
+
"api_key": os.getenv("DEEPSEEK_API_KEY", None),
|
| 53 |
+
"base_url": os.getenv("DEEPSEEK_BASE_URL", None),
|
| 54 |
+
"model_params": {
|
| 55 |
+
"temperature": 0.2
|
| 56 |
+
}
|
| 57 |
+
}
|
| 58 |
+
]
|
| 59 |
+
}
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
class Evaluator:
|
| 63 |
+
def __init__(self,
|
| 64 |
+
dataset:List[BenchmarkItem] = [],
|
| 65 |
+
api_key:Optional[str] = None,
|
| 66 |
+
model_name:str = "gpt-4.1",
|
| 67 |
+
base_url:Optional[str] = None,
|
| 68 |
+
parse_model:str = "gpt-4.1-mini",
|
| 69 |
+
parse_model_api_key:Optional[str] = None,
|
| 70 |
+
parse_model_base_url:Optional[str] = None,
|
| 71 |
+
**model_params):
|
| 72 |
+
if not api_key or not parse_model_api_key:
|
| 73 |
+
raise ValueError("api_key and parse_model_api_key are required")
|
| 74 |
+
self.system_prompt = """
|
| 75 |
+
You are a helpful assistant that can evaluate the quality of a given answer.
|
| 76 |
+
"""
|
| 77 |
+
# self.dataset_path = dataset_path
|
| 78 |
+
self.dataset = dataset
|
| 79 |
+
self.benchmark_data:List[BenchmarkItem] = []
|
| 80 |
+
self.model_name = model_name
|
| 81 |
+
self.base_url = base_url
|
| 82 |
+
self.parse_model = parse_model
|
| 83 |
+
self.model_params = model_params or {"temperature": 0.0} # 默认参数
|
| 84 |
+
self.parse_client = AsyncClient(api_key=parse_model_api_key, base_url=parse_model_base_url)
|
| 85 |
+
self.client = AsyncClient(api_key=api_key, base_url=self.base_url)
|
| 86 |
+
self.tool_output_max_tokens = 2000
|
| 87 |
+
|
| 88 |
+
@retry(stop=stop_after_attempt(3), wait=wait_exponential(multiplier=1, min=4, max=15))
|
| 89 |
+
async def parse_str_to_format(self, string_output:Optional[str], target_data_class: Type[T]) -> Optional[T]:
|
| 90 |
+
if not string_output:
|
| 91 |
+
return None
|
| 92 |
+
try:
|
| 93 |
+
# 对于解析模型的参数,使用默认参数
|
| 94 |
+
response = await self.parse_client.beta.chat.completions.parse(
|
| 95 |
+
model=self.parse_model,
|
| 96 |
+
messages=[{"role": "user", "content": string_output}],
|
| 97 |
+
response_format=target_data_class,
|
| 98 |
+
temperature=0.0,
|
| 99 |
+
)
|
| 100 |
+
result = response.choices[0].message.parsed
|
| 101 |
+
if result:
|
| 102 |
+
return result
|
| 103 |
+
except Exception as e:
|
| 104 |
+
print(f"Error parsing string to format: {e}")
|
| 105 |
+
return None
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
async def summarize_tool_use_output(self, question:str, tool_use_list:List[ToolUse]) -> list[ToolUse]:
|
| 110 |
+
"""If the tool use output is too long, summarize the tool use output to keep the important information"""
|
| 111 |
+
system_prompt = f"""
|
| 112 |
+
You are a helpful assistant that can summarize the tool use output. Your output format should be in the following format:"In order to solve <Task>, Invoked <tool_name> with <tool_input> and got <summarized_tool_output>"
|
| 113 |
+
NOTE:
|
| 114 |
+
1. Ignore the noise in the tool_output, only keep the important information that might help to solve/improve the possibility of solving the task.
|
| 115 |
+
2. If the tool_output is not related to the question, just summarize the tool_output to "No relevant information Found"
|
| 116 |
+
"""
|
| 117 |
+
async def process_tool_use(tool_use: ToolUse) -> ToolUse:
|
| 118 |
+
if count_tokens(tool_use.tool_output, self.parse_model) > self.tool_output_max_tokens:
|
| 119 |
+
user_prompt = f"""
|
| 120 |
+
Question: {question}
|
| 121 |
+
Tool use:
|
| 122 |
+
{tool_use.to_prompt()}
|
| 123 |
+
"""
|
| 124 |
+
|
| 125 |
+
response = await self.parse_client.chat.completions.create(
|
| 126 |
+
model=self.parse_model,
|
| 127 |
+
messages=[{"role": "system", "content": system_prompt}, {"role": "user", "content": user_prompt}],
|
| 128 |
+
**self.model_params
|
| 129 |
+
)
|
| 130 |
+
|
| 131 |
+
content = response.choices[0].message.content
|
| 132 |
+
if content:
|
| 133 |
+
tool_use.tool_output = content
|
| 134 |
+
else:
|
| 135 |
+
tool_use.tool_output = truncate_text(tool_use.tool_output, self.parse_model, self.tool_output_max_tokens)
|
| 136 |
+
|
| 137 |
+
return tool_use
|
| 138 |
+
|
| 139 |
+
# 并行处理所有tool_use
|
| 140 |
+
tasks = [process_tool_use(tool_use) for tool_use in tool_use_list]
|
| 141 |
+
tool_use_list = await asyncio.gather(*tasks)
|
| 142 |
+
return tool_use_list
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
async def evaluate_reasoning(self, output_answer:Answer, benchmark_item:BenchmarkItem) -> tuple[float, Optional[ReasoningEvaluateResult]]:
|
| 146 |
+
reasoning_items = [item for item in benchmark_item.evaluate.items if item.target == EvaluateTarget.REASONING]
|
| 147 |
+
reasoning_step_prompt = "\n".join([step.to_prompt() for step in output_answer.reasoning_steps])
|
| 148 |
+
function_call_prompt = "\n".join([step.to_prompt(ignore_output=True) for step in output_answer.function_calls])
|
| 149 |
+
if not reasoning_items:
|
| 150 |
+
return 0.0, None
|
| 151 |
+
prompt = f"""
|
| 152 |
+
Task ID: {benchmark_item.task_id}
|
| 153 |
+
Question: {benchmark_item.question}
|
| 154 |
+
To be evaluated Reasoning Steps:
|
| 155 |
+
```
|
| 156 |
+
{reasoning_step_prompt}
|
| 157 |
+
```
|
| 158 |
+
|
| 159 |
+
In addition, the following function calls are also part of the reasoning steps. The choose of the tool use and the arguments should be taken into account:
|
| 160 |
+
```
|
| 161 |
+
{function_call_prompt}
|
| 162 |
+
```
|
| 163 |
+
|
| 164 |
+
Evaluation Rules:"""
|
| 165 |
+
for item in reasoning_items:
|
| 166 |
+
prompt += f"{item.to_prompt()}\n"
|
| 167 |
+
prompt += f"Now evaluate the reasoning steps based on the evaluation criteria, and give the score for each item in the range of 0 to the point the criteria worth."
|
| 168 |
+
# print(prompt)
|
| 169 |
+
max_retries = 3
|
| 170 |
+
retry_count = 0
|
| 171 |
+
while retry_count < max_retries:
|
| 172 |
+
try:
|
| 173 |
+
response = await self.client.chat.completions.create(
|
| 174 |
+
model=self.model_name,
|
| 175 |
+
messages=[{"role": "user", "content": prompt}],
|
| 176 |
+
**self.model_params
|
| 177 |
+
)
|
| 178 |
+
content = response.choices[0].message.content
|
| 179 |
+
result = await self.parse_str_to_format(content, ReasoningEvaluateResult)
|
| 180 |
+
if not result:
|
| 181 |
+
retry_count += 1
|
| 182 |
+
continue
|
| 183 |
+
if sum([item.score for item in result.items]) > sum([item.points for item in reasoning_items]):
|
| 184 |
+
retry_count += 1
|
| 185 |
+
continue
|
| 186 |
+
return sum([item.score for item in result.items]), result
|
| 187 |
+
except Exception as e:
|
| 188 |
+
print(f"Error evaluating reasoning (attempt {retry_count + 1}/{max_retries}): {e}")
|
| 189 |
+
retry_count += 1
|
| 190 |
+
if retry_count == max_retries:
|
| 191 |
+
return 0.0, None
|
| 192 |
+
await asyncio.sleep(1) # 添加重试间隔
|
| 193 |
+
return 0.0, None
|
| 194 |
+
|
| 195 |
+
async def evaluate_tool_use(self, output_answer:Answer, benchmark_item:BenchmarkItem) -> tuple[float, Optional[ToolUseEvaluateResult]]:
|
| 196 |
+
tool_use_items = [item for item in benchmark_item.evaluate.items if item.target == EvaluateTarget.TOOL_USE]
|
| 197 |
+
if not tool_use_items:
|
| 198 |
+
return 0.0, None
|
| 199 |
+
function_call_prompt = "\n".join([step.to_prompt(ignore_output=True) for step in output_answer.function_calls])
|
| 200 |
+
prompt = f"""
|
| 201 |
+
Task ID: {benchmark_item.task_id}
|
| 202 |
+
Question: {benchmark_item.question}
|
| 203 |
+
To be evaluated tool use:
|
| 204 |
+
```
|
| 205 |
+
{function_call_prompt}
|
| 206 |
+
```
|
| 207 |
+
|
| 208 |
+
Evaluation Rules:
|
| 209 |
+
"""
|
| 210 |
+
for item in tool_use_items:
|
| 211 |
+
prompt += f"{item.to_prompt()}\n"
|
| 212 |
+
prompt += f"Now evaluate the tool use based on the evaluation criteria, and give the score for each item in the range of 0 to the point the criteria worth."
|
| 213 |
+
max_retries = 3
|
| 214 |
+
retry_count = 0
|
| 215 |
+
while retry_count < max_retries:
|
| 216 |
+
try:
|
| 217 |
+
response = await self.client.chat.completions.create(
|
| 218 |
+
model=self.model_name,
|
| 219 |
+
messages=[{"role": "user", "content": prompt}],
|
| 220 |
+
**self.model_params
|
| 221 |
+
)
|
| 222 |
+
content = response.choices[0].message.content
|
| 223 |
+
result = await self.parse_str_to_format(content, ToolUseEvaluateResult)
|
| 224 |
+
if not result:
|
| 225 |
+
retry_count += 1
|
| 226 |
+
continue
|
| 227 |
+
if sum([item.score for item in result.items]) > sum([item.points for item in tool_use_items]):
|
| 228 |
+
retry_count += 1
|
| 229 |
+
continue
|
| 230 |
+
return sum([item.score for item in result.items]), result
|
| 231 |
+
except Exception as e:
|
| 232 |
+
print(f"Error evaluating tool use (attempt {retry_count + 1}/{max_retries}): {e}")
|
| 233 |
+
retry_count += 1
|
| 234 |
+
if retry_count == max_retries:
|
| 235 |
+
return 0.0, None
|
| 236 |
+
await asyncio.sleep(1) # 添��重试间隔
|
| 237 |
+
return 0.0, None
|
| 238 |
+
|
| 239 |
+
|
| 240 |
+
async def evaluate_answer(self, output_answer:Answer, benchmark_item:BenchmarkItem) -> tuple[float, Optional[AnswerEvaluateResult]]:
|
| 241 |
+
evaluate_items = [item for item in benchmark_item.evaluate.items if item.target == EvaluateTarget.ANSWER]
|
| 242 |
+
if not evaluate_items:
|
| 243 |
+
return 0.0, None
|
| 244 |
+
|
| 245 |
+
prompt = f"""
|
| 246 |
+
Task ID: {benchmark_item.task_id}
|
| 247 |
+
Question: {benchmark_item.question}
|
| 248 |
+
To be evaluated output:
|
| 249 |
+
```
|
| 250 |
+
{output_answer.to_prompt()}
|
| 251 |
+
```
|
| 252 |
+
|
| 253 |
+
Evaluation Rules:
|
| 254 |
+
"""
|
| 255 |
+
for item in evaluate_items:
|
| 256 |
+
prompt += f"{item.to_prompt()}\n"
|
| 257 |
+
prompt += f"Now evaluate the output answer based on the evaluation criteria, and give the score for each item in the range of 0 to the point the criteria worth."
|
| 258 |
+
# print(prompt)
|
| 259 |
+
max_retry = 3
|
| 260 |
+
for _ in range(max_retry):
|
| 261 |
+
try:
|
| 262 |
+
response = await self.client.chat.completions.create(
|
| 263 |
+
model=self.model_name,
|
| 264 |
+
messages=[{"role": "user", "content": prompt}],
|
| 265 |
+
**self.model_params
|
| 266 |
+
)
|
| 267 |
+
|
| 268 |
+
|
| 269 |
+
result = await self.parse_str_to_format(response.choices[0].message.content, AnswerEvaluateResult)
|
| 270 |
+
if not result:
|
| 271 |
+
continue
|
| 272 |
+
if result.score > sum([item.points for item in evaluate_items]):
|
| 273 |
+
continue
|
| 274 |
+
return result.score, result
|
| 275 |
+
except Exception as e:
|
| 276 |
+
print(f"Error evaluating answer: {e}")
|
| 277 |
+
continue
|
| 278 |
+
return 0.0, None
|
| 279 |
+
|
| 280 |
+
async def a_evaluate(self, task_id:str, answer:Answer, to_evaluate_item: BenchmarkItem) -> EvaluateScore | None:
|
| 281 |
+
import asyncio
|
| 282 |
+
tasks = [
|
| 283 |
+
self.evaluate_answer(answer, to_evaluate_item),
|
| 284 |
+
self.evaluate_reasoning(answer, to_evaluate_item),
|
| 285 |
+
self.evaluate_tool_use(answer, to_evaluate_item),
|
| 286 |
+
]
|
| 287 |
+
[(answer_score, answer_evaulate_result), (reasoning_score, reasoning_evaulate_result), (tool_use_score, tool_use_evaulate_result)] = await asyncio.gather(*tasks)
|
| 288 |
+
|
| 289 |
+
analysis = await self.analyze_evaulate_result(answer_evaulate_result, reasoning_evaulate_result, tool_use_evaulate_result, to_evaluate_item)
|
| 290 |
+
return analysis
|
| 291 |
+
|
| 292 |
+
|
| 293 |
+
async def analyze_evaulate_result(self,
|
| 294 |
+
answer_evaulate_result:AnswerEvaluateResult,
|
| 295 |
+
reasoning_evaulate_result:ReasoningEvaluateResult,
|
| 296 |
+
tool_use_evaulate_result:ToolUseEvaluateResult,
|
| 297 |
+
to_evaluate_item:BenchmarkItem) -> EvaluateScore:
|
| 298 |
+
"""Analyze the evaulate result and give the analysis"""
|
| 299 |
+
benchmark_answer_item = [item for item in to_evaluate_item.evaluate.items if item.target == EvaluateTarget.ANSWER][0]
|
| 300 |
+
benchmark_reasoning_items = [item for item in to_evaluate_item.evaluate.items if item.target == EvaluateTarget.REASONING]
|
| 301 |
+
benchmark_tool_use_items = [item for item in to_evaluate_item.evaluate.items if item.target == EvaluateTarget.TOOL_USE]
|
| 302 |
+
detail = ""
|
| 303 |
+
detail += f"Answer score: {answer_evaulate_result.score} / {benchmark_answer_item.points}\n"
|
| 304 |
+
detail += f"Reason: {answer_evaulate_result.reason}\n"
|
| 305 |
+
detail += f"Reasoning score: {sum([item.score for item in reasoning_evaulate_result.items])} / {sum([item.points for item in benchmark_reasoning_items])}\n"
|
| 306 |
+
for item in reasoning_evaulate_result.items:
|
| 307 |
+
detail += f"Reasoning step {item.step}: {item.reason} score: {item.score} / {benchmark_reasoning_items[item.step-1].points}\n"
|
| 308 |
+
detail += f"Tool use score: {sum([item.score for item in tool_use_evaulate_result.items])} / {sum([item.points for item in benchmark_tool_use_items])}\n"
|
| 309 |
+
for item in tool_use_evaulate_result.items:
|
| 310 |
+
detail += f"{item.reason}\n"
|
| 311 |
+
print(detail)
|
| 312 |
+
return EvaluateScore(
|
| 313 |
+
model_name=self.model_name,
|
| 314 |
+
answer_score=answer_evaulate_result.score,
|
| 315 |
+
answer_total_score=benchmark_answer_item.points,
|
| 316 |
+
reasoning_score=sum([item.score for item in reasoning_evaulate_result.items]),
|
| 317 |
+
reasoning_total_score=sum([item.points for item in benchmark_reasoning_items]),
|
| 318 |
+
tool_use_score=sum([item.score for item in tool_use_evaulate_result.items]),
|
| 319 |
+
tool_use_total_score=sum([item.points for item in benchmark_tool_use_items]),
|
| 320 |
+
total_score=answer_evaulate_result.score + sum([item.score for item in reasoning_evaulate_result.items]) + sum([item.score for item in tool_use_evaulate_result.items]),
|
| 321 |
+
evaluate_detail=detail,
|
| 322 |
+
task_id=to_evaluate_item.task_id,
|
| 323 |
+
level=to_evaluate_item.level or 1,
|
| 324 |
+
category=to_evaluate_item.category
|
| 325 |
+
)
|
| 326 |
+
|
| 327 |
+
|
| 328 |
+
async def ensemble_evaluate(evaulator_list:list[Evaluator], answer:Answer, to_evaluate_item:BenchmarkItem) -> EnsembleEvaluateScore:
|
| 329 |
+
# for evaluator in evaulator_list:
|
| 330 |
+
# await evaluator.load_validate_data()
|
| 331 |
+
results:list[EvaluateScore|None] = await asyncio.gather(*[evaluator.a_evaluate(to_evaluate_item.task_id, answer, to_evaluate_item) for evaluator in evaulator_list])
|
| 332 |
+
results = [item for item in results if item]
|
| 333 |
+
return EnsembleEvaluateScore(
|
| 334 |
+
task_id=to_evaluate_item.task_id,
|
| 335 |
+
answer_total_score=mean([item.answer_total_score for item in results if item]),
|
| 336 |
+
reasoning_total_score=mean([item.reasoning_total_score for item in results if item]),
|
| 337 |
+
tool_use_total_score=mean([item.tool_use_total_score for item in results if item]),
|
| 338 |
+
total_score=mean([item.total_score for item in results if item]),
|
| 339 |
+
evaluate_detail="no detail",
|
| 340 |
+
answer_score=mean([item.answer_score for item in results if item]),
|
| 341 |
+
reasoning_score=mean([item.reasoning_score for item in results if item]),
|
| 342 |
+
tool_use_score=mean([item.tool_use_score for item in results if item]),
|
| 343 |
+
level=to_evaluate_item.level or 1,
|
| 344 |
+
category=to_evaluate_item.category,
|
| 345 |
+
model_name="ensemble result"
|
| 346 |
+
)
|
| 347 |
+
|
requirements.txt
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
APScheduler
|
| 2 |
+
black
|
| 3 |
+
datasets
|
| 4 |
+
gradio
|
| 5 |
+
gradio[oauth]
|
| 6 |
+
gradio_leaderboard==0.0.13
|
| 7 |
+
gradio_client
|
| 8 |
+
huggingface-hub>=0.18.0
|
| 9 |
+
matplotlib
|
| 10 |
+
numpy
|
| 11 |
+
pandas
|
| 12 |
+
python-dateutil
|
| 13 |
+
tqdm
|
| 14 |
+
transformers
|
| 15 |
+
tokenizers>=0.15.0
|
| 16 |
+
sentencepiece
|
| 17 |
+
pydantic==2.10.1
|
| 18 |
+
openai==1.78.1
|
| 19 |
+
tiktoken==0.9.0
|
| 20 |
+
tenacity===9.1.2
|
| 21 |
+
loguru
|
schemas.py
ADDED
|
@@ -0,0 +1,212 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from math import isclose
|
| 2 |
+
from typing import List, Optional
|
| 3 |
+
from pydantic import BaseModel, Field, field_validator, model_validator
|
| 4 |
+
from enum import Enum
|
| 5 |
+
|
| 6 |
+
class EvaluateTarget(Enum):
|
| 7 |
+
ANSWER = "ANSWER"
|
| 8 |
+
REASONING = "REASONING"
|
| 9 |
+
TOOL_USE = "TOOL_USE"
|
| 10 |
+
SOURCES = "SOURCES"
|
| 11 |
+
|
| 12 |
+
class ToolUse(BaseModel):
|
| 13 |
+
call_id: str
|
| 14 |
+
tool_name:str
|
| 15 |
+
tool_description: str
|
| 16 |
+
tool_input:str
|
| 17 |
+
tool_output: str
|
| 18 |
+
|
| 19 |
+
def to_prompt(self, ignore_output:bool = False) -> str:
|
| 20 |
+
prompt = f"Tool Name: {self.tool_name}\n"
|
| 21 |
+
prompt += f"Tool Description: {self.tool_description}\n"
|
| 22 |
+
prompt += f"Tool Input: {self.tool_input}\n"
|
| 23 |
+
if not ignore_output:
|
| 24 |
+
prompt += f"Tool Output: {self.tool_output}\n"
|
| 25 |
+
return prompt
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
class ReasoningStep(BaseModel):
|
| 29 |
+
step: int
|
| 30 |
+
reasoning: Optional[str] = None
|
| 31 |
+
# function_call: Optional[ToolUse] = None
|
| 32 |
+
|
| 33 |
+
def to_prompt(self) -> str:
|
| 34 |
+
prompt = f"Step {self.step}:\n"
|
| 35 |
+
if self.reasoning:
|
| 36 |
+
prompt += f"Reasoning: {self.reasoning}\n"
|
| 37 |
+
# if self.function_call:
|
| 38 |
+
# prompt += f"Function Call: {self.function_call.to_prompt()}\n"
|
| 39 |
+
return prompt
|
| 40 |
+
|
| 41 |
+
class Answer(BaseModel):
|
| 42 |
+
answer: str
|
| 43 |
+
reasoning_steps: List[ReasoningStep]
|
| 44 |
+
function_calls: List[ToolUse]
|
| 45 |
+
# sources: List[str]
|
| 46 |
+
|
| 47 |
+
def to_prompt(self) -> str:
|
| 48 |
+
prompt = f"Final Answer: {self.answer}\n"
|
| 49 |
+
return prompt
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
class EvaluateItem(BaseModel):
|
| 54 |
+
step: Optional[int] = None
|
| 55 |
+
target: EvaluateTarget
|
| 56 |
+
points: float
|
| 57 |
+
criteria: str
|
| 58 |
+
|
| 59 |
+
def to_prompt(self) -> str:
|
| 60 |
+
prompt = f"Step {self.step}:\n" if self.step else ""
|
| 61 |
+
prompt += f"Worth Points: {self.points}\n"
|
| 62 |
+
prompt += f"Criteria content: {self.criteria}\n"
|
| 63 |
+
return prompt
|
| 64 |
+
|
| 65 |
+
class EvaluateData(BaseModel):
|
| 66 |
+
items: List[EvaluateItem]
|
| 67 |
+
|
| 68 |
+
@field_validator('items')
|
| 69 |
+
@classmethod
|
| 70 |
+
def validate_total_points(cls, items: List[EvaluateItem]) -> List[EvaluateItem]:
|
| 71 |
+
total_points = sum(item.points for item in items)
|
| 72 |
+
if abs(total_points - 10.0) != 0:
|
| 73 |
+
raise ValueError(f"所有评估项的权重总和必须等于10,当前总和为: {total_points}")
|
| 74 |
+
return items
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
class QuestionData(BaseModel):
|
| 78 |
+
task_id: str
|
| 79 |
+
question: str
|
| 80 |
+
# tools:Optional[List[str]] = Field(description="The tools that can be used to answer the question")
|
| 81 |
+
|
| 82 |
+
def to_prompt(self) -> str:
|
| 83 |
+
prompt = f"Task ID: {self.task_id}\n"
|
| 84 |
+
prompt += f"Question: {self.question}\n"
|
| 85 |
+
return prompt
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
class BenchmarkItem(BaseModel):
|
| 90 |
+
task_id: str
|
| 91 |
+
level:Optional[int] = 1
|
| 92 |
+
category:str
|
| 93 |
+
question: str = Field(description="The question to be answered")
|
| 94 |
+
# answer: Answer = Field(description="The agent system output")
|
| 95 |
+
evaluate: EvaluateData = Field(description="The evaluation result")
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
class AnswerEvaluateResult(BaseModel):
|
| 100 |
+
reason: Optional[str] = None
|
| 101 |
+
score: float = Field(description="The score of the answer worth")
|
| 102 |
+
|
| 103 |
+
def __str__(self) -> str:
|
| 104 |
+
return f"Reason: {self.reason}\nScore: {self.score}"
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
class ReasoningEvaluateItem(BaseModel):
|
| 108 |
+
step: int
|
| 109 |
+
reason: Optional[str] = None
|
| 110 |
+
score: float = Field(description="The score of the reasoning step worth")
|
| 111 |
+
|
| 112 |
+
def __str__(self) -> str:
|
| 113 |
+
return f"Step: {self.step}\nReason: {self.reason}\nScore: {self.score}"
|
| 114 |
+
|
| 115 |
+
class ReasoningEvaluateResult(BaseModel):
|
| 116 |
+
items: List[ReasoningEvaluateItem]
|
| 117 |
+
|
| 118 |
+
def __str__(self) -> str:
|
| 119 |
+
return "\n".join([item.__str__() for item in self.items])
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
class ToolUseEvaluateItem(BaseModel):
|
| 123 |
+
reason: Optional[str] = None
|
| 124 |
+
score: float = Field(description="The score of the tool use worth")
|
| 125 |
+
|
| 126 |
+
def __str__(self) -> str:
|
| 127 |
+
return f"Reason: {self.reason}\nScore: {self.score}"
|
| 128 |
+
|
| 129 |
+
class ToolUseEvaluateResult(BaseModel):
|
| 130 |
+
items: List[ToolUseEvaluateItem]
|
| 131 |
+
|
| 132 |
+
def __str__(self) -> str:
|
| 133 |
+
return "\n".join([item.__str__() for item in self.items])
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
class AgentOutputItem(BaseModel):
|
| 138 |
+
task_id: str
|
| 139 |
+
answer: str
|
| 140 |
+
tool_use_list: List[ToolUse]
|
| 141 |
+
reasoning_list: List[ReasoningStep]
|
| 142 |
+
|
| 143 |
+
def to_prompt(self) -> str:
|
| 144 |
+
prompt = f"Task ID: {self.task_id}\n"
|
| 145 |
+
prompt += f"Answer: {self.answer}\n"
|
| 146 |
+
prompt += f"Tool Use List: {self.tool_use_list}\n"
|
| 147 |
+
prompt += f"Reasoning List: {self.reasoning_list}\n"
|
| 148 |
+
return prompt
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
class EvaluateScore(BaseModel):
|
| 152 |
+
answer_total_score: float = Field(description="The total score of the answer worth")
|
| 153 |
+
reasoning_total_score: float = Field(description="The total score of the reasoning worth")
|
| 154 |
+
tool_use_total_score: float = Field(description="The total score of the tool use worth")
|
| 155 |
+
|
| 156 |
+
answer_score: float = Field(description="The score of the agent get from the answer")
|
| 157 |
+
reasoning_score: float = Field(description="The score of the agent get from the reasoning")
|
| 158 |
+
tool_use_score: float = Field(description="The score of the agent get from the tool use")
|
| 159 |
+
|
| 160 |
+
total_score: float = Field(description="The total score of the agent")
|
| 161 |
+
|
| 162 |
+
evaluate_detail:Optional[str] = Field(description="The detail of the evaluation")
|
| 163 |
+
model_name: str
|
| 164 |
+
task_id:str
|
| 165 |
+
level:int
|
| 166 |
+
category:str
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
# @field_validator('total_score')
|
| 170 |
+
@field_validator('answer_score', 'reasoning_score', 'tool_use_score')
|
| 171 |
+
def non_negative(cls, v):
|
| 172 |
+
if v < 0:
|
| 173 |
+
raise ValueError('score cannot be negative')
|
| 174 |
+
return v
|
| 175 |
+
|
| 176 |
+
@field_validator('answer_score')
|
| 177 |
+
def check_answer_score(cls, v, info):
|
| 178 |
+
max_score = info.data.get('answer_total_score', 0)
|
| 179 |
+
if v > max_score:
|
| 180 |
+
raise ValueError('answer_score cannot exceed answer_total_score')
|
| 181 |
+
return v
|
| 182 |
+
|
| 183 |
+
@field_validator('reasoning_score')
|
| 184 |
+
def check_reasoning_score(cls, v, info):
|
| 185 |
+
max_score = info.data.get('reasoning_total_score', 0)
|
| 186 |
+
if v > max_score:
|
| 187 |
+
raise ValueError('reasoning_score cannot exceed reasoning_total_score')
|
| 188 |
+
return v
|
| 189 |
+
|
| 190 |
+
@field_validator('tool_use_score')
|
| 191 |
+
def check_tool_use_score(cls, v, info):
|
| 192 |
+
max_score = info.data.get('tool_use_total_score', 0)
|
| 193 |
+
if v > max_score:
|
| 194 |
+
raise ValueError('tool_use_score cannot exceed tool_use_total_score')
|
| 195 |
+
return v
|
| 196 |
+
|
| 197 |
+
@model_validator(mode='after')
|
| 198 |
+
def check_totals(self):
|
| 199 |
+
# 可选:限制总分(如果业务就是固定 10 分)
|
| 200 |
+
if self.total_score > 10:
|
| 201 |
+
raise ValueError('total_score cannot exceed 10')
|
| 202 |
+
|
| 203 |
+
expected = self.answer_score + self.reasoning_score + self.tool_use_score
|
| 204 |
+
if not isclose(self.total_score, expected, abs_tol=1e-6):
|
| 205 |
+
raise ValueError(
|
| 206 |
+
f'total_score ({self.total_score}) must equal the sum of '
|
| 207 |
+
f'answer_score + reasoning_score + tool_use_score ({expected})'
|
| 208 |
+
)
|
| 209 |
+
return self
|
| 210 |
+
|
| 211 |
+
class EnsembleEvaluateScore(EvaluateScore):
|
| 212 |
+
...
|
score.py
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import asyncio
|
| 2 |
+
from concurrent.futures import ThreadPoolExecutor
|
| 3 |
+
import json
|
| 4 |
+
from typing import List
|
| 5 |
+
from evaluator import Evaluator, ensemble_evaluate
|
| 6 |
+
from schemas import AgentOutputItem, Answer, BenchmarkItem, EvaluateScore, EnsembleEvaluateScore
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def init_evaluators(dataset:List[BenchmarkItem], llm_configs:dict) -> list[Evaluator]:
|
| 10 |
+
parse_llm_config = llm_configs["parse_llm_config"]
|
| 11 |
+
evaluate_llm_configs = llm_configs["evaluate_llm_configs"]
|
| 12 |
+
evaluator_list: list[Evaluator] = []
|
| 13 |
+
for evaluate_llm_config in evaluate_llm_configs:
|
| 14 |
+
for _ in range(3):
|
| 15 |
+
evaluator = Evaluator(
|
| 16 |
+
dataset=dataset,
|
| 17 |
+
parse_model=parse_llm_config["model_name"],
|
| 18 |
+
parse_model_api_key=parse_llm_config.get("api_key", None),
|
| 19 |
+
parse_model_base_url=parse_llm_config.get("base_url", None),
|
| 20 |
+
api_key=evaluate_llm_config.get("api_key", None),
|
| 21 |
+
model_name=evaluate_llm_config["model_name"],
|
| 22 |
+
base_url=evaluate_llm_config.get("base_url", None),
|
| 23 |
+
**evaluate_llm_config.get("model_params",{})
|
| 24 |
+
)
|
| 25 |
+
evaluator_list.append(evaluator)
|
| 26 |
+
return evaluator_list
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def load_agent_output_dataset(dataset_path:str = "dataset/example_agent_output.json") -> list[AgentOutputItem]:
|
| 30 |
+
with open(dataset_path, "r") as f:
|
| 31 |
+
agent_output_dataset = json.load(f)
|
| 32 |
+
return [AgentOutputItem(**item) for item in agent_output_dataset]
|
| 33 |
+
|
| 34 |
+
async def run_evaluate(evaluator_list:list[Evaluator], agent_output_item:AgentOutputItem, to_evaluate_item:BenchmarkItem):
|
| 35 |
+
answer = Answer(
|
| 36 |
+
answer=agent_output_item.answer,
|
| 37 |
+
reasoning_steps=agent_output_item.reasoning_list,
|
| 38 |
+
function_calls=agent_output_item.tool_use_list
|
| 39 |
+
)
|
| 40 |
+
return await ensemble_evaluate(evaluator_list, answer, to_evaluate_item)
|
| 41 |
+
|
| 42 |
+
async def score_item(evaluator_list:list[Evaluator], agent_output_item:AgentOutputItem, to_evaluate_item:BenchmarkItem) -> EnsembleEvaluateScore:
|
| 43 |
+
answer = Answer(
|
| 44 |
+
answer=agent_output_item.answer,
|
| 45 |
+
reasoning_steps=agent_output_item.reasoning_list,
|
| 46 |
+
function_calls=agent_output_item.tool_use_list
|
| 47 |
+
)
|
| 48 |
+
return await ensemble_evaluate(evaluator_list, answer, to_evaluate_item)
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
async def score_in_threadpool(evaluator_list:list[Evaluator], agent_output_list:list[AgentOutputItem], benchmark_data:list[BenchmarkItem]) -> list[EnsembleEvaluateScore]:
|
| 57 |
+
with ThreadPoolExecutor(max_workers=max(1, min(5, len(agent_output_list)))) as executor:
|
| 58 |
+
futures = []
|
| 59 |
+
for agent_output_item in agent_output_list:
|
| 60 |
+
task_id = agent_output_item.task_id
|
| 61 |
+
to_evaluate_item = next((item for item in benchmark_data if item.task_id == task_id), None)
|
| 62 |
+
|
| 63 |
+
if to_evaluate_item:
|
| 64 |
+
future = executor.submit(
|
| 65 |
+
asyncio.run,
|
| 66 |
+
score_item(
|
| 67 |
+
evaluator_list=evaluator_list,
|
| 68 |
+
agent_output_item=agent_output_item,
|
| 69 |
+
to_evaluate_item=to_evaluate_item
|
| 70 |
+
)
|
| 71 |
+
)
|
| 72 |
+
futures.append(future)
|
| 73 |
+
|
| 74 |
+
return [future.result() for future in futures]
|
utils.py
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import pandas as pd
|
| 2 |
+
import tiktoken
|
| 3 |
+
from typing import List, Optional
|
| 4 |
+
from email._parseaddr import AddressList as _AddressList
|
| 5 |
+
|
| 6 |
+
from schemas import BenchmarkItem, EvaluateData, EvaluateItem
|
| 7 |
+
from datasets import DatasetDict
|
| 8 |
+
|
| 9 |
+
def truncate_text(text: str, model: str = "gpt-4.1", max_tokens: Optional[int] = None) -> str:
|
| 10 |
+
"""
|
| 11 |
+
Truncate text to specified token count using tiktoken
|
| 12 |
+
|
| 13 |
+
Args:
|
| 14 |
+
text: Text to be truncated
|
| 15 |
+
model: Model name to use, defaults to "gpt-4"
|
| 16 |
+
max_tokens: Maximum token count, if None then no truncation
|
| 17 |
+
|
| 18 |
+
Returns:
|
| 19 |
+
Truncated text
|
| 20 |
+
"""
|
| 21 |
+
if not max_tokens:
|
| 22 |
+
return text
|
| 23 |
+
|
| 24 |
+
try:
|
| 25 |
+
encoding = tiktoken.encoding_for_model(model)
|
| 26 |
+
except KeyError:
|
| 27 |
+
# 如果找不到指定模型的编码器,使用cl100k_base编码器
|
| 28 |
+
encoding = tiktoken.get_encoding("cl100k_base")
|
| 29 |
+
|
| 30 |
+
tokens = encoding.encode(text)
|
| 31 |
+
if len(tokens) <= max_tokens:
|
| 32 |
+
return text
|
| 33 |
+
|
| 34 |
+
truncated_tokens = tokens[:max_tokens]
|
| 35 |
+
return encoding.decode(truncated_tokens)
|
| 36 |
+
|
| 37 |
+
def count_tokens(text: str, model: str = "gpt-4.1") -> int:
|
| 38 |
+
"""
|
| 39 |
+
Count the number of tokens in a text using tiktoken
|
| 40 |
+
|
| 41 |
+
Args:
|
| 42 |
+
text: Text to count tokens
|
| 43 |
+
model: Model name to use, defaults to "gpt-4"
|
| 44 |
+
|
| 45 |
+
Returns:
|
| 46 |
+
Number of tokens in the text
|
| 47 |
+
"""
|
| 48 |
+
try:
|
| 49 |
+
encoding = tiktoken.encoding_for_model(model)
|
| 50 |
+
except KeyError:
|
| 51 |
+
# 如果找不到指定模型的编码器,使用cl100k_base编码器
|
| 52 |
+
encoding = tiktoken.get_encoding("cl100k_base")
|
| 53 |
+
tokens = encoding.encode(text)
|
| 54 |
+
return len(tokens)
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def parseaddr(addr):
|
| 59 |
+
"""
|
| 60 |
+
Parse addr into its constituent realname and email address parts.
|
| 61 |
+
|
| 62 |
+
Return a tuple of realname and email address, unless the parse fails, in
|
| 63 |
+
which case return a 2-tuple of ('', '').
|
| 64 |
+
"""
|
| 65 |
+
addrs = _AddressList(addr).addresslist
|
| 66 |
+
if not addrs:
|
| 67 |
+
return '', ''
|
| 68 |
+
return addrs[0]
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def parse_eval_dataset(dataset:DatasetDict) -> List[BenchmarkItem]:
|
| 72 |
+
|
| 73 |
+
df = pd.DataFrame(dataset['train'])
|
| 74 |
+
benchmark_items:List[BenchmarkItem] = []
|
| 75 |
+
for index, row in df.iterrows():
|
| 76 |
+
benchmark_items.append(BenchmarkItem(
|
| 77 |
+
task_id=row['task_id'],
|
| 78 |
+
question=row['question'],
|
| 79 |
+
evaluate=EvaluateData(items=[EvaluateItem(**item) for item in row['evaluate']['items']])
|
| 80 |
+
))
|
| 81 |
+
return benchmark_items
|