Skip to content

SD2 1406 add error code handling nyckel #353

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 6 commits into from
Apr 15, 2025

Conversation

juandavidcruzgomez
Copy link
Contributor

@juandavidcruzgomez juandavidcruzgomez commented Apr 15, 2025

  • Error handling: give a more informative message when an image (or resource) already exists
  • Fix an unbound variable error
  • Search for the exact job_id and get only one result or none

Summary by CodeRabbit

  • Bug Fixes
    • Improved error messages for specific HTTP error responses, providing clearer feedback on billing issues, access restrictions, resource conflicts, throttling, and service availability.
  • Refactor
    • Enhanced internal handling of webhook URL construction for better reliability.

Copy link

coderabbitai bot commented Apr 15, 2025

Walkthrough

The changes introduce a new error handling method, handle_provider_error, in the Nyckel API integration to provide more specific exception messages based on HTTP status codes. This method replaces the previous generic error handler in the image autoML classification job launch method. Additionally, exception chaining is removed when raising a ProviderException after a webhook failure. In the Nyckel helpers module, the construction of the query parameter for a webhook URL is refactored for clarity, assigning the query string to a variable before encoding.

Changes

File(s) Change Summary
edenai_apis/apis/nyckel/nyckel_api.py Added handle_provider_error method to map HTTP errors to specific messages; replaced old error handling in job launch; removed exception chaining in webhook failure.
edenai_apis/apis/nyckel/nyckel_helpers.py Refactored query parameter construction for webhook URL by assigning to a variable before URL encoding.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant NyckelApi

    Client->>NyckelApi: image__automl_classification__upload_data_async__launch_job()
    NyckelApi->>NyckelApi: Send HTTP request
    NyckelApi->>NyckelApi: If response error, call handle_provider_error(response)
    NyckelApi->>NyckelApi: Map status code to specific ProviderException
    NyckelApi-->>Client: Return result or raise ProviderException
Loading

Poem

A rabbit hopped through Nyckel’s code,
With error maps and queries showed.
Exceptions now are clear and bright,
Each status gets its message right.
Webhook queries neat and spry—
Refactored clean, oh my oh my!
🐇✨


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Lite

📥 Commits

Reviewing files that changed from the base of the PR and between eb2f3e3 and afdcce9.

📒 Files selected for processing (1)
  • edenai_apis/apis/nyckel/nyckel_api.py (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • edenai_apis/apis/nyckel/nyckel_api.py

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Nitpick comments (2)
edenai_apis/apis/nyckel/nyckel_api.py (2)

380-381: Exception chaining removed - consider preserving original cause.

You've removed the from exp exception chaining that was present in the line above (377-378). While this makes the code more consistent with similar error handling patterns in the file, it removes information about the original cause of the failure.

-            raise ProviderException("Could not upload image data", 400)
+            raise ProviderException("Could not upload image data", 400) from exp

543-577: Well-structured error handler with clear error messages.

The new handle_provider_error method is well-documented and provides specific error messages for different HTTP status codes, which improves the developer experience when debugging issues.

However, there's a typo in the error message for status code 409.

-                "Resouce conflict. Commonly raised when trying to create a sample that already exists in the function (Nyckel does not allow duplicate samples). When annotating an existing sample, use the PUT samples endpoint instead."
+                "Resource conflict. Commonly raised when trying to create a sample that already exists in the function (Nyckel does not allow duplicate samples). When annotating an existing sample, use the PUT samples endpoint instead."
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between cd7dbf9 and eb2f3e3.

📒 Files selected for processing (2)
  • edenai_apis/apis/nyckel/nyckel_api.py (3 hunks)
  • edenai_apis/apis/nyckel/nyckel_helpers.py (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
edenai_apis/apis/nyckel/nyckel_api.py (1)
edenai_apis/utils/exception.py (2)
  • ProviderException (14-26)
  • status_code (23-26)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: test
🔇 Additional comments (2)
edenai_apis/apis/nyckel/nyckel_helpers.py (1)

19-22: Good refactoring for clarity and maintainability.

Extracting the query string into a separate variable before using it with urllib.parse.quote_plus improves code readability and makes the logic easier to follow.

edenai_apis/apis/nyckel/nyckel_api.py (1)

352-353: Good replacement of generic error handling with specific error codes.

Replacing the generic exception with a specialized error handler improves the API's usability by providing more descriptive error messages based on specific HTTP status codes.

Comment on lines 543 to 577
def handle_provider_error(self, response: requests.Response):
"""
402 Billing issue. Mostly likely because you have exceeded the free tier quota.
403 Forbidden. Check your credentials.
409 Resouce conflict. Commonly raised when trying to create a sample that already exists in the function (Nyckel does not allow duplicate samples). When annotating an existing sample, use the PUT samples endpoint instead.
429 Throttled. You have exceeded either 25 requests per second or 25 concurrent requests.
500 Internal error. Retry -- ideally with exponential backoff.
503 Service temporarily unavailable. Retry -- ideally with exponential backoff.
"""
if response.status_code == 402:
raise ProviderException(
"Billing issue. Mostly likely because you have exceeded the free tier quota."
)
elif response.status_code == 403:
raise ProviderException("Forbidden. Check your credentials.")
elif response.status_code == 409:
raise ProviderException(
"Resouce conflict. Commonly raised when trying to create a sample that already exists in the function (Nyckel does not allow duplicate samples). When annotating an existing sample, use the PUT samples endpoint instead."
)
elif response.status_code == 429:
raise ProviderException(
"Throttled. You have exceeded either 25 requests per second or 25 concurrent requests."
)
elif response.status_code == 500:
raise ProviderException(
"Internal error. Retry -- ideally with exponential backoff."
)
elif response.status_code == 503:
raise ProviderException(
"Service temporarily unavailable. Retry -- ideally with exponential backoff."
)
else:
raise ProviderException(
"Something went wrong when running the prediction !!", 500
)
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Error handler should pass status code to ProviderException.

The current implementation doesn't pass the response status code to the ProviderException constructor in most cases, which means this information is lost. The ProviderException class supports a code parameter which should be utilized.

-            raise ProviderException(
-                "Billing issue. Mostly likely because you have exceeded the free tier quota."
-            )
+            raise ProviderException(
+                "Billing issue. Mostly likely because you have exceeded the free tier quota.",
+                response.status_code
+            )

Apply similar changes for all other exception cases in the method.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
def handle_provider_error(self, response: requests.Response):
"""
402 Billing issue. Mostly likely because you have exceeded the free tier quota.
403 Forbidden. Check your credentials.
409 Resouce conflict. Commonly raised when trying to create a sample that already exists in the function (Nyckel does not allow duplicate samples). When annotating an existing sample, use the PUT samples endpoint instead.
429 Throttled. You have exceeded either 25 requests per second or 25 concurrent requests.
500 Internal error. Retry -- ideally with exponential backoff.
503 Service temporarily unavailable. Retry -- ideally with exponential backoff.
"""
if response.status_code == 402:
raise ProviderException(
"Billing issue. Mostly likely because you have exceeded the free tier quota."
)
elif response.status_code == 403:
raise ProviderException("Forbidden. Check your credentials.")
elif response.status_code == 409:
raise ProviderException(
"Resouce conflict. Commonly raised when trying to create a sample that already exists in the function (Nyckel does not allow duplicate samples). When annotating an existing sample, use the PUT samples endpoint instead."
)
elif response.status_code == 429:
raise ProviderException(
"Throttled. You have exceeded either 25 requests per second or 25 concurrent requests."
)
elif response.status_code == 500:
raise ProviderException(
"Internal error. Retry -- ideally with exponential backoff."
)
elif response.status_code == 503:
raise ProviderException(
"Service temporarily unavailable. Retry -- ideally with exponential backoff."
)
else:
raise ProviderException(
"Something went wrong when running the prediction !!", 500
)
def handle_provider_error(self, response: requests.Response):
"""
402 Billing issue. Mostly likely because you have exceeded the free tier quota.
403 Forbidden. Check your credentials.
409 Resouce conflict. Commonly raised when trying to create a sample that already exists in the function (Nyckel does not allow duplicate samples). When annotating an existing sample, use the PUT samples endpoint instead.
429 Throttled. You have exceeded either 25 requests per second or 25 concurrent requests.
500 Internal error. Retry -- ideally with exponential backoff.
503 Service temporarily unavailable. Retry -- ideally with exponential backoff.
"""
if response.status_code == 402:
raise ProviderException(
"Billing issue. Mostly likely because you have exceeded the free tier quota.",
response.status_code
)
elif response.status_code == 403:
raise ProviderException(
"Forbidden. Check your credentials.",
response.status_code
)
elif response.status_code == 409:
raise ProviderException(
"Resouce conflict. Commonly raised when trying to create a sample that already exists in the function (Nyckel does not allow duplicate samples). When annotating an existing sample, use the PUT samples endpoint instead.",
response.status_code
)
elif response.status_code == 429:
raise ProviderException(
"Throttled. You have exceeded either 25 requests per second or 25 concurrent requests.",
response.status_code
)
elif response.status_code == 500:
raise ProviderException(
"Internal error. Retry -- ideally with exponential backoff.",
response.status_code
)
elif response.status_code == 503:
raise ProviderException(
"Service temporarily unavailable. Retry -- ideally with exponential backoff.",
response.status_code
)
else:
raise ProviderException(
"Something went wrong when running the prediction !!",
response.status_code
)

@juandavidcruzgomez juandavidcruzgomez merged commit b874dd3 into master Apr 15, 2025
4 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants