处理单个任务的协程函数
(task: Task, result_saver: Optional[BenchmarkResultSaver] = None)
| 181 | completed_lock = asyncio.Lock() |
| 182 | |
| 183 | async def process_single_task(task: Task, result_saver: Optional[BenchmarkResultSaver] = None) -> Task: |
| 184 | """处理单个任务的协程函数""" |
| 185 | nonlocal completed_count # 必须在函数开始处声明 |
| 186 | task_id = task.task_id |
| 187 | start_time = time.time() |
| 188 | |
| 189 | async with semaphore: # 使用 Semaphore 限制并发 |
| 190 | try: |
| 191 | print(f"\n" + "="*50) |
| 192 | print(f"🚀 Processing Task ID: {task_id}") |
| 193 | print("="*50) |
| 194 | |
| 195 | # --- 1. 准备 Prompt --- |
| 196 | question_text = task.input |
| 197 | |
| 198 | # 直接从 task 获取 system_prompt |
| 199 | system_prompt_text = task.system_prompt |
| 200 | |
| 201 | logger.info(f"| 📋 [Task {task_id}] Input length: {len(question_text)}") |
| 202 | |
| 203 | messages = [ |
| 204 | SystemMessage(content=system_prompt_text), |
| 205 | HumanMessage(content=question_text) |
| 206 | ] |
| 207 | |
| 208 | # --- 2. 模型推理 (Structure Output) --- |
| 209 | print(f"⏳ [Task {task_id}] Model inferencing (Structured)...") |
| 210 | |
| 211 | try: |
| 212 | # 调用 model_manager 并传入 response_format,添加超时 |
| 213 | try: |
| 214 | response = await asyncio.wait_for( |
| 215 | model_manager( |
| 216 | model=TARGET_MODEL, |
| 217 | messages=messages, |
| 218 | response_format=Response, |
| 219 | ), |
| 220 | timeout=600.0 # 10分钟超时 |
| 221 | ) |
| 222 | except asyncio.TimeoutError: |
| 223 | logger.error(f"| ⏱️ [Task {task_id}] Model API Timeout (600s)") |
| 224 | task.reasoning = "" |
| 225 | task.result = "" |
| 226 | response = None |
| 227 | |
| 228 | if response and response.success: |
| 229 | # 获取解析后的对象 |
| 230 | response_model = response.extra.parsed_model |
| 231 | task.reasoning = response_model.reasoning |
| 232 | task.result = response_model.answer |
| 233 | |
| 234 | # --- 保存 Response 到 Markdown 文件 --- |
| 235 | try: |
| 236 | safe_id = sanitize_filename(task_id) |
| 237 | filename = f"{safe_id}.md" |
| 238 | file_path = os.path.join(save_dir, filename) |
| 239 | |
| 240 | with open(file_path, "w", encoding="utf-8") as f: |