Fix handling of empty OpenAI API key #4
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Issue Fixed
This pull request addresses an issue where the application would attempt to use empty API keys for LLM services, causing runtime errors. Previously, the code only checked if environment variables were set (os.getenv("OPENAI_API_KEY")) but didn't validate whether they contained actual valid values.
Changes Made
The fix implements proper validation and fallback mechanisms in the LLMService class:
Added validation to check if API keys are empty, None, or just whitespace in all three main methods:
get_artist_recommendations()
get_track_recommendations()
generate_playlist_name()
Implemented a robust fallback mechanism:
When an OpenAI API key is empty or invalid, the service now logs a warning and automatically falls back to using Anthropic
Added model switching logic to ensure the appropriate model provider is used when falling back
Added a final validation check before API calls to ensure no empty API keys are used, raising a clear error message if no valid keys are available
Testing
The changes have been tested with various environment configurations:
With valid OpenAI API key
With empty OpenAI API key (falls back to Anthropic)
With no API keys set (raises appropriate error)
This fix improves application stability by preventing runtime errors when API keys are technically present in the environment but contain no usable value.