File size: 13,601 Bytes
1e012a3 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 |
import json
import openai
import google.generativeai as genai
import time
from collections import defaultdict
from typing import Dict, List
import os
from tqdm import tqdm
import argparse
class PoetryEvaluator:
def __init__(self, api_key: str, provider: str = "openai", model: str = "gpt-3.5-turbo",
dry_run: bool = False, delay: float = 0.5, max_retries: int = 3, retry_delay: float = 1.0):
"""初始化评测器
Args:
api_key: API密钥
provider: API提供商 ("openai" 或 "google")
model: 模型名称
dry_run: 是否为演示模式
delay: API调用间隔时间(秒)
max_retries: 最大重试次数
retry_delay: 重试等待时间(秒)
"""
self.api_key = api_key
self.provider = provider
self.model = model
self.dry_run = dry_run
self.delay = delay
self.max_retries = max_retries
self.retry_delay = retry_delay
self.results = defaultdict(list)
# 根据provider初始化API
if provider == "google":
genai.configure(api_key=api_key)
self.generation_config = {
"temperature": 0,
"top_p": 0.95,
"top_k": 64,
"max_output_tokens": 8192,
}
self.google_model = genai.GenerativeModel(
model_name=model,
generation_config=self.generation_config
)
def load_benchmark(self, jsonl_path: str) -> List[Dict]:
"""加载评测数据集"""
questions = []
with open(jsonl_path, 'r', encoding='utf-8') as f:
for line in f:
if line.strip():
questions.append(json.loads(line))
return questions
def generate_prompt(self, question: Dict) -> str:
"""根据题型生成提示词"""
q_type = question['type']
author = question['metadata']['author']
content = question['content']['question']
prompts = {
'couplet': "请将下面的诗句补充完整。只需要回答括号()之内的内容,不需要进行解释。\n\n",
'hint_words': "请将以下包含星号的诗句补充完整。回答补充后的完整诗句,不需要进行解释。\n\n",
'find_poetry': "请从以下给出的多行诗句中,从每一行提取出一个字,组成一句有效的诗句。只需要回答找到的诗句,不需要进行解释。\n\n",
'blank_filling': "请将下面的诗句补充完整。只需要回答括号()之内的内容,不需要进行解释。\n\n",
'first_last_words': "请将以下包含星号的诗句补充完整。回答补充后的完整诗句,不需要进行解释。\n\n"
}
if author != None:
return prompts[q_type] + f"{author}: {content}"
else:
return prompts[q_type] + content
def normalize_answer(self, answer: str) -> str:
"""标准化答案格式"""
return answer.strip().replace('。', '').replace(',', '')
def evaluate_answer(self, prediction: str, ground_truth: str) -> bool:
"""评估答案是否正确
只要模型输出中包含正确答案就算对
"""
pred = self.normalize_answer(prediction)
truth = self.normalize_answer(ground_truth)
# 如果答案中包含多个可能的正确答案(用/分隔)
if '/' in truth:
possible_answers = [ans.strip() for ans in truth.split('/')]
return any(ans in pred for ans in possible_answers)
# 否则检查输出中是否包含正确答案
return truth in pred
def call_api_with_retry(self, prompt: str) -> str:
"""带重试机制的API调用
Args:
prompt: 提示词
Returns:
模型回复文本
"""
retries = 0
while True:
try:
if self.provider == "openai":
client = openai.OpenAI(
api_key=self.api_key,
base_url=openai.api_base
)
response = client.chat.completions.create(
model=self.model,
messages=[
{"role": "system", "content": "你是一个古诗词专家。"},
{"role": "user", "content": prompt}
],
temperature=0
)
return response.choices[0].message.content
elif self.provider == "google":
chat = self.google_model.start_chat(
history=[
{"role": "user", "parts": ["你是一个古诗词专家。"]}
]
)
response = chat.send_message(prompt)
return response.text
except Exception as e:
retries += 1
if retries > self.max_retries:
raise e
# 对于限流错误,使用指数退避策略
if "429" in str(e):
wait_time = self.retry_delay * (2 ** (retries - 1))
print(f"\n遇到限流,等待 {wait_time} 秒后重试 ({retries}/{self.max_retries})...")
time.sleep(wait_time)
else:
raise e
def evaluate_single(self, question: Dict) -> Dict:
"""评估单个问题"""
prompt = self.generate_prompt(question)
try:
if self.dry_run:
prediction = f"[DRY RUN] 这是问题 {question['id']} 的模拟答案"
else:
prediction = self.call_api_with_retry(prompt)
# 添加调用间隔
time.sleep(self.delay)
is_correct = self.evaluate_answer(prediction, question['content']['answer'])
return {
'id': question['id'],
'type': question['type'],
'difficulty': question['difficulty'],
'metadata': question['metadata'],
'prompt': prompt,
'prediction': prediction,
'ground_truth': question['content']['answer'],
'is_correct': is_correct
}
except Exception as e:
print(f"Error evaluating question {question['id']}: {str(e)}")
return None
def evaluate_all(self, questions: List[Dict]):
"""评估所有问题"""
# 初始化计数器
total = len(questions)
correct = 0
# 创建进度条
pbar = tqdm(questions, desc="Evaluating")
for question in pbar:
result = self.evaluate_single(question)
if result:
self.results['all'].append(result)
self.results[result['type']].append(result)
self.results[result['difficulty']].append(result)
if result['metadata']['dynasty']:
self.results[result['metadata']['dynasty']].append(result)
# 更新计数
if result['is_correct']:
correct += 1
# 更新进度条描述
accuracy = correct / len(self.results['all']) * 100
pbar.set_description(
f"Accuracy: {accuracy:.2f}% ({correct}/{len(self.results['all'])})"
)
# 打印详细信息
print(f"\n问题 {result['id']} ({result['type']}, {result['difficulty']}):")
print(f"提示: {result['prompt']}")
print(f"预测: {result['prediction']}")
print(f"答案: {result['ground_truth']}")
print(f"结果: {'✓' if result['is_correct'] else '✗'}\n")
# 每次评测后更新总体准确率
print(f"当前总体准确率: {accuracy:.2f}%")
print("-" * 80)
def generate_report(self) -> Dict:
"""生成评测报告"""
report = {
'overall': self._calculate_metrics(self.results['all']),
'by_type': {},
'by_difficulty': {},
'by_dynasty': {}
}
# 按题型统计
for q_type in ['couplet', 'hint_words', 'find_poetry', 'blank_filling', 'first_last_words']:
if self.results[q_type]:
report['by_type'][q_type] = self._calculate_metrics(self.results[q_type])
# 按难度统计
for difficulty in ['easy', 'medium', 'hard']:
if self.results[difficulty]:
report['by_difficulty'][difficulty] = self._calculate_metrics(self.results[difficulty])
# 按朝代统计
for dynasty in set(r['metadata']['dynasty'] for r in self.results['all'] if r['metadata']['dynasty']):
report['by_dynasty'][dynasty] = self._calculate_metrics(self.results[dynasty])
return report
def _calculate_metrics(self, results: List[Dict]) -> Dict:
"""计算评测指标"""
total = len(results)
correct = sum(1 for r in results if r['is_correct'])
return {
'total': total,
'correct': correct,
'accuracy': correct / total if total > 0 else 0
}
def save_results(self, output_dir: str):
"""保存评测结果"""
os.makedirs(output_dir, exist_ok=True)
# 保存详细结果
with open(os.path.join(output_dir, 'detailed_results.jsonl'), 'w', encoding='utf-8') as f:
for result in self.results['all']:
f.write(json.dumps(result, ensure_ascii=False) + '\n')
# 保存原始输入输出
with open(os.path.join(output_dir, 'raw_io.jsonl'), 'w', encoding='utf-8') as f:
for result in self.results['all']:
raw_io = {
'id': result['id'],
'type': result['type'],
'prompt': result['prompt'],
'completion': result['prediction'],
'ground_truth': result['ground_truth']
}
f.write(json.dumps(raw_io, ensure_ascii=False) + '\n')
# 保存评测报告
report = self.generate_report()
with open(os.path.join(output_dir, 'evaluation_report.json'), 'w', encoding='utf-8') as f:
json.dump(report, ensure_ascii=False, indent=2, fp=f)
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='评测大语言模型的古诗词能力')
parser.add_argument('--api-key',
type=str,
required=True,
help='API密钥')
parser.add_argument('--provider',
type=str,
choices=['openai', 'google'],
default='openai',
help='API提供商 (openai 或 google)')
parser.add_argument('--model',
type=str,
help='要评测的模型名称')
parser.add_argument('--api-base',
type=str,
help='API基础URL (例如: https://api.openai.com/v1)')
parser.add_argument('--output-dir',
type=str,
default='evaluation_results',
help='评测结果保存目录 (默认: evaluation_results)')
parser.add_argument('--benchmark-file',
type=str,
default='poetry_benchmark.jsonl',
help='评测数据集文件路径 (默认: poetry_benchmark.jsonl)')
parser.add_argument('--dry-run',
action='store_true',
help='演示模式,不实际调用API')
parser.add_argument('--delay',
type=float,
default=0.5,
help='API调用间隔时间(秒) (默认: 0.5)')
parser.add_argument('--max-retries',
type=int,
default=5,
help='API调用最大重试次数 (默认: 5)')
parser.add_argument('--retry-delay',
type=float,
default=10,
help='重试等待时间(秒) (默认: 10)')
args = parser.parse_args()
# 设置API基础URL (仅OpenAI需要)
if not args.dry_run and args.provider == "openai":
openai.api_base = args.api_base
# 初始化评测器
evaluator = PoetryEvaluator(
api_key=args.api_key,
provider=args.provider,
model=args.model,
dry_run=args.dry_run,
delay=args.delay,
max_retries=args.max_retries,
retry_delay=args.retry_delay
)
# 加载数据
questions = evaluator.load_benchmark(args.benchmark_file)
# 运行评测
evaluator.evaluate_all(questions)
# 生成报告
report = evaluator.generate_report()
print(json.dumps(report, ensure_ascii=False, indent=2))
# 保存结果
evaluator.save_results(args.output_dir) |