Enhancement: Robust API key handling and environment fallbacks for AI providers #73
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.
Enhancement: Robust API key handling and environment fallbacks for AI providers
Summary
This PR strengthens the AI provider configuration flow by adding environment variable fallbacks, improving encrypted settings handling, and enhancing error reporting. It ensures that providers such as OpenAI, OpenRouter, Claude, and Groq can still be used even when user settings are missing, malformed, or encrypted incorrectly, provided valid API keys exist in environment variables.
Additionally, the
SettingInstancemodel query logic has been refined to prefer ORM-based enum handling while still falling back to direct SQL when necessary.Changes
🔹 Backend: Provider Handling (
ai_providers.py)Added
_get_env_api_keyhelper for mapping providers to environment variables:OPENAI_API_KEYOPENROUTER_API_KEYANTHROPIC_API_KEYGROQ_API_KEYEnhanced provider initialization:
Improved settings decryption flow:
Updated
get_all_models:Improved
chat_completion:HTTPExceptionto preserve status codes.🔹 Backend: Settings (
models/settings.py)Refined scope filtering:
Motivation
SettingInstance.Testing & Validation
Tested with:
Verified
get_all_modelsloads models successfully using both settings and env keys.Confirmed settings scope filtering works case-insensitively and respects enum resolution.
Impact
get_all_models).Checklist
_get_env_api_keyhelperget_all_modelswith robust parsing + env fallbackchat_completionerror handlingSettingInstanceORM vs direct SQL logic