为华为大模型API调用添加重试机制,增强了错误处理逻辑,确保在请求失败时能够自动重试并提供详细的错误信息。同时,将API调用逻辑分离到单独的方法中,以提高代码可读性和可维护性。

This commit is contained in:
python 2025-12-09 11:41:45 +08:00
parent 8461725a13
commit 14ff607b52

View File

@ -4,6 +4,7 @@ AI服务 - 封装大模型调用
""" """
import os import os
import re import re
import time
import requests import requests
import json import json
from typing import Dict, List, Optional from typing import Dict, List, Optional
@ -116,8 +117,78 @@ class AIService:
raise Exception(f"AI服务调用失败: {str(e)}") raise Exception(f"AI服务调用失败: {str(e)}")
def _extract_with_huawei(self, prompt: str, output_fields: List[Dict]) -> Optional[Dict]: def _extract_with_huawei(self, prompt: str, output_fields: List[Dict]) -> Optional[Dict]:
"""使用华为大模型API提取字段""" """
使用华为大模型API提取字段带重试机制
至少重试3次总共最多尝试4次
"""
max_retries = 3 # 最多重试3次总共4次尝试
retry_delay = 1 # 重试延迟(秒),每次重试延迟递增
last_exception = None
for attempt in range(max_retries + 1): # 0, 1, 2, 3 (总共4次)
try: try:
if attempt > 0:
# 重试前等待延迟时间递增1秒、2秒、3秒
wait_time = retry_delay * attempt
print(f"[AI服务] 第 {attempt} 次重试,等待 {wait_time} 秒后重试...")
time.sleep(wait_time)
print(f"[AI服务] 正在调用华为大模型API (尝试 {attempt + 1}/{max_retries + 1})...")
result = self._call_huawei_api_once(prompt, output_fields)
if result is not None:
if attempt > 0:
print(f"[AI服务] 重试成功!")
return result
except requests.exceptions.Timeout as e:
last_exception = e
error_msg = f"AI服务调用超时 (尝试 {attempt + 1}/{max_retries + 1})"
print(f"[AI服务] {error_msg}")
if attempt < max_retries:
continue
else:
raise Exception(f"{error_msg}: {str(e)}")
except requests.exceptions.ConnectionError as e:
last_exception = e
error_msg = f"连接错误 (尝试 {attempt + 1}/{max_retries + 1})"
print(f"[AI服务] {error_msg}: {str(e)}")
if attempt < max_retries:
continue
else:
raise Exception(f"{error_msg}: {str(e)}")
except requests.exceptions.RequestException as e:
last_exception = e
error_msg = f"请求异常 (尝试 {attempt + 1}/{max_retries + 1})"
print(f"[AI服务] {error_msg}: {str(e)}")
if attempt < max_retries:
continue
else:
raise Exception(f"{error_msg}: {str(e)}")
except Exception as e:
last_exception = e
error_msg = f"AI服务调用失败 (尝试 {attempt + 1}/{max_retries + 1})"
print(f"[AI服务] {error_msg}: {str(e)}")
# 对于其他类型的错误,也进行重试
if attempt < max_retries:
continue
else:
raise Exception(f"{error_msg}: {str(e)}")
# 如果所有重试都失败了
if last_exception:
raise Exception(f"AI服务调用失败已重试 {max_retries} 次: {str(last_exception)}")
else:
raise Exception(f"AI服务调用失败已重试 {max_retries}")
def _call_huawei_api_once(self, prompt: str, output_fields: List[Dict]) -> Optional[Dict]:
"""
单次调用华为大模型API不包含重试逻辑
"""
payload = { payload = {
"model": self.huawei_model, "model": self.huawei_model,
"messages": [ "messages": [
@ -178,12 +249,7 @@ class AIService:
# 如果无法提取JSON尝试从文本中提取 # 如果无法提取JSON尝试从文本中提取
return self._parse_text_response(content, output_fields) return self._parse_text_response(content, output_fields)
else: else:
raise Exception("API返回格式异常") raise Exception("API返回格式异常未找到choices字段或choices为空")
except requests.exceptions.Timeout:
raise Exception("AI服务调用超时")
except Exception as e:
raise Exception(f"AI服务调用失败: {str(e)}")
def _extract_json_from_text(self, text: str) -> Optional[Dict]: def _extract_json_from_text(self, text: str) -> Optional[Dict]:
""" """