-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy patherror_handling.py
34 lines (32 loc) · 1.1 KB
/
error_handling.py
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
from openai import OpenAI, OpenAIError, RateLimitError, APIError, Timeout
import os
client = OpenAI(
api_key=os.getenv("OPENAI_API_KEY"),
organization=os.getenv("OPENAI_ORG_ID"), # 可选 OpenAI API 中的组织 ID
timeout=30.0 # 默认超时时间
)
def safe_api_call():
try:
response = client.chat.completions.create(
model="gpt-3.5-turbo",
messages=[{"role": "user", "content": "你好"}],
timeout=30, # 请求超时时间
request_timeout=30, # HTTP请求超时
max_retries=3 # 最大重试次数
)
return response.choices[0].message.content
except RateLimitError as e:
print(f"达到速率限制: {str(e)}")
return None
except Timeout as e:
print(f"请求超时: {str(e)}")
return None
except APIError as e:
print(f"API错误: {str(e)}")
return None
except OpenAIError as e:
print(f"其他OpenAI错误: {str(e)}")
return None
except Exception as e:
print(f"未预期的错误: {str(e)}")
return None