错误处理

使用 OpenAI API 构建 AI 系统

Francesca Donadoni

Curriculum Manager, DataCamp

AI 应用中的错误

 

  • 简化用户体验
  • 消除障碍

一名男子在电脑前排查 404 错误

使用 OpenAI API 构建 AI 系统

OpenAI API 库中的错误

response = client.chat.completions.create(
 model="text-davinci-001",
 messages=[
   {
    "role": "user", 
    "content": "List two data science professions with related skills in json format."
   }
 ],
 response_format={"type": "json_object"}
)
NotFoundError: Error code: 404 - {'error': {'message': 'The model `text-davinci-001` 
has been deprecated, learn more here: https://platform.openai.com/docs/deprecations'}}
使用 OpenAI API 构建 AI 系统

连接错误

 

  • 通常由用户端或服务端的连接问题引起

 

  • 例:InternalServerErrorAPIConnectionErrorAPITimeoutError

 

  • 可能的解决方案:
    • 检查连接配置
    • 若无效,联系技术支持
使用 OpenAI API 构建 AI 系统

资源限制错误

 

  • 通常由于请求频率或文本长度受限

 

  • 例:ConflictErrorRateLimitError

 

  • 可能的解决方案:
    • 检查限额与限制
    • 确保请求在限额内
使用 OpenAI API 构建 AI 系统

身份验证错误

client = OpenAI(api_key="This is an Invalid Key")

response = client.chat.completions.create( model="gpt-4o-mini", messages=[ { "role": "user", "content": "List two data science professions with related skills in json format." } ], response_format={"type": "json_object"} )
AuthenticationError: Error code: 401 - {'error': {'message': 'Incorrect API key provided: 
ThisIsNo*AKey. You can find your API key at https://platform.openai.com/account/api-keys.'}}
使用 OpenAI API 构建 AI 系统

错误的请求

response = client.chat.completions.create(
 model="gpt-4o-mini",
 messages=[
   {"role": "This is not a Valid Role", "content": "List two data science 
   professions with related skills in json format."}
 ],
 response_format={"type": "json_object"}
)
BadRequestError: Error code: 400 - {'error': {'message': "'NotARole' is not one of 
['system', 'assistant', 'user', 'function'] - 'messages.0.role'", 
'type': 'invalid_request_error', 'param': None, 'code': None}}
使用 OpenAI API 构建 AI 系统

异常处理

try: 
    response = client.chat.completions.create(
     model="gpt-4o-mini",
     messages=[{"role": "user", 
      "content": "List five data science professions."}])

except openai.AuthenticationError as e: print(f"OpenAI API failed to authenticate: {e}") pass except openai.RateLimitError as e: print(f"OpenAI API request exceeded rate limit: {e}") pass
except Exception as e: print(f"Unable to generate a response. Exception: {e}") pass
使用 OpenAI API 构建 AI 系统

Passons à la pratique !

使用 OpenAI API 构建 AI 系统

Preparing Video For Download...