錯誤處理

使用 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 系統

一起來練習吧!

使用 OpenAI API 開發 AI 系統

Preparing Video For Download...