Skip to content
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

Improve OpenAI error handling #164

Merged
merged 5 commits into from
Oct 11, 2024
Merged

Conversation

MichaelOwenDyer
Copy link
Contributor

@MichaelOwenDyer MichaelOwenDyer commented Oct 11, 2024

Currently, our OpenAI chat and embedding wrappers will retry requests up to 10 times if any Exception occurs. This is bad practice - there are exceptions we shouldn't retry on, and exceptions we shouldn't catch at all.

This PR changes the error handling of OpenAIChatModel and OpenAIEmbeddingModel to only retry if one of the following openai errors is raised: APIError, APITimeoutError, RateLimitError, InternalServerError. This is in alignment with the suggestions in the documentation here. Otherwise, we do not catch the exception and let it raise all the way up to the web layer, where the global error handler reports a fatal error to the client.

This PR also adds special error handling in OpenAIChatModel for the OpenAI content filter. Unfortunately, no error is raised automatically by the openai library in this case. So we check to see if the finish_reason of the returned choice is content_filter, and if so we manually raise an Exception to the global error handler. This means that if the user's input is flagged by the content filter, the user will not receive a response from Iris and will instead see "Fatal error".

Also, the maximum retries has been lowered from 10 to 5, which results in a maximum wait time of 31 seconds. If after this long no request has been successful, we give up and raise a fatal exception (so that the user isn't waiting indefinitely).

Closes #136.

Summary by CodeRabbit

  • New Features

    • Enhanced error handling for OpenAI API interactions, improving reliability.
    • Implemented specific checks for content filter activation in responses.
  • Bug Fixes

    • Reduced retry attempts for API calls from 10 to 5, streamlining error resolution.
    • Improved specificity in error handling for various OpenAI-related errors.
  • Documentation

    • Updated comments to clarify maximum wait times for retries and error handling.

Copy link
Contributor

coderabbitai bot commented Oct 11, 2024

Walkthrough

The pull request enhances error handling and retry logic in the OpenAIChatModel and OpenAIEmbeddingModel classes. The number of retries for API calls has been reduced from 10 to 5, with specific exceptions related to OpenAI API errors being captured. Logging messages have been improved for clarity, and a new check for the finish_reason in response choices has been implemented to manage scenarios where the OpenAI content filter is activated.

Changes

File Change Summary
app/llm/external/openai_chat.py Enhanced error handling and adjusted retry logic; reduced retries from 10 to 5; refined exception handling for API errors; streamlined API call method; added check for finish_reason; updated logging messages.
app/llm/external/openai_embeddings.py Modified error handling in OpenAIEmbeddingModel; reduced retries from 10 to 5; updated logging and documented maximum wait time for retries; raised a generic exception if all retry attempts fail.

📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between b213250 and b3720f2.

📒 Files selected for processing (2)
  • app/llm/external/openai_chat.py (2 hunks)
  • app/llm/external/openai_embeddings.py (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • app/llm/external/openai_chat.py
  • app/llm/external/openai_embeddings.py

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 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
Contributor

@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: 4

🧹 Outside diff range and nitpick comments (1)
app/llm/external/openai_embeddings.py (1)

22-25: LGTM: Improved retry logic with exponential backoff

The changes to the retry logic are well-implemented:

  1. Reducing retries from 10 to 5 is reasonable and aligns with the PR objectives.
  2. Introducing an exponential backoff strategy is a good practice for API requests.
  3. The comment explaining the maximum wait time is helpful.

Consider extracting these retry parameters into class-level constants for easier configuration and testing. For example:

class OpenAIEmbeddingModel(EmbeddingModel):
    MAX_RETRIES = 5
    BACKOFF_FACTOR = 2
    INITIAL_DELAY = 1
    # ...
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 79414c7 and 2438c5e.

📒 Files selected for processing (2)
  • app/llm/external/openai_chat.py (2 hunks)
  • app/llm/external/openai_embeddings.py (3 hunks)
🧰 Additional context used
🔇 Additional comments (5)
app/llm/external/openai_embeddings.py (5)

3-9: LGTM: Improved error handling imports

The addition of specific OpenAI error types (APIError, APITimeoutError, RateLimitError, and InternalServerError) aligns well with the PR objectives. This change enables more precise error handling in the embed method.


35-40: LGTM: Precise error handling for OpenAI-specific errors

The updated except clause now catches specific OpenAI-related errors (APIError, APITimeoutError, RateLimitError, and InternalServerError). This change:

  1. Aligns perfectly with the PR objectives.
  2. Follows OpenAI's documentation recommendations.
  3. Prevents unnecessary retries for unrelated exceptions, improving overall efficiency.

42-43: LGTM: Improved logging for OpenAI errors

The updated logging message is more appropriate and informative:

  1. It now covers all potential OpenAI errors, not just rate limit issues.
  2. The message provides clearer feedback during API interactions.
  3. It includes the attempt number, which is helpful for debugging.

45-45: LGTM: Informative final error logging

The updated final error log message now includes the number of retries attempted. This change:

  1. Provides more context in the error log.
  2. Aligns well with the modifications made to the retry logic.
  3. Helps in debugging by clearly indicating when all retry attempts have been exhausted.

Line range hint 1-77: Summary: Excellent improvements to OpenAI error handling and retry logic

Overall, the changes in this file significantly enhance the error handling and retry mechanism for OpenAI API interactions:

  1. The introduction of specific OpenAI error types allows for more precise error handling.
  2. The refined retry logic with exponential backoff is a good practice for API requests.
  3. Updated logging provides clearer and more informative feedback during API interactions.
  4. The changes align well with the PR objectives and OpenAI's documentation.

These improvements will lead to more robust and efficient API interactions. Great job!

app/llm/external/openai_chat.py Outdated Show resolved Hide resolved
app/llm/external/openai_chat.py Outdated Show resolved Hide resolved
app/llm/external/openai_chat.py Show resolved Hide resolved
app/llm/external/openai_chat.py Outdated Show resolved Hide resolved
coderabbitai[bot]
coderabbitai bot previously approved these changes Oct 11, 2024
Copy link
Contributor

@kaancayli kaancayli left a comment

Choose a reason for hiding this comment

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

changes look good.

@MichaelOwenDyer
Copy link
Contributor Author

Going to go ahead and merge this

@MichaelOwenDyer MichaelOwenDyer merged commit b1d7dc5 into main Oct 11, 2024
11 checks passed
@MichaelOwenDyer MichaelOwenDyer deleted the improve_openai_error_handling branch October 11, 2024 20:09
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

No proper error handling if Azure filtered the response
3 participants