Spaces:
Sleeping
Sleeping
Commit
Β·
361389f
1
Parent(s):
4840462
Enhance OpenAI client configuration and error handling; add connection test at startup
Browse files- app.py +47 -10
- requirements.txt +3 -1
app.py
CHANGED
|
@@ -23,7 +23,12 @@ openai_api_key = os.getenv("OPENAI_API_KEY")
|
|
| 23 |
if not openai_api_key:
|
| 24 |
raise ValueError("OPENAI_API_KEY not found. Please set it in your environment variables or .env file.")
|
| 25 |
|
| 26 |
-
client
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 27 |
|
| 28 |
# Explanation complexity levels with clear descriptions
|
| 29 |
EXPLANATION_LEVELS = {
|
|
@@ -96,16 +101,32 @@ def explain_concept(question, level, language):
|
|
| 96 |
except Exception as e:
|
| 97 |
# Provide more specific error messages for common issues
|
| 98 |
error_msg = str(e).lower()
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 107 |
else:
|
| 108 |
-
yield f"β Error
|
| 109 |
|
| 110 |
# Create enhanced Gradio interface with modern styling
|
| 111 |
with gr.Blocks(
|
|
@@ -203,6 +224,22 @@ if __name__ == "__main__":
|
|
| 203 |
|
| 204 |
print("π Starting AI Concept Explainer...")
|
| 205 |
print(f"Environment: {'Hugging Face Spaces' if is_space else 'Local Development'}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 206 |
|
| 207 |
if is_space:
|
| 208 |
# Production configuration for Hugging Face Spaces
|
|
|
|
| 23 |
if not openai_api_key:
|
| 24 |
raise ValueError("OPENAI_API_KEY not found. Please set it in your environment variables or .env file.")
|
| 25 |
|
| 26 |
+
# Configure OpenAI client with settings optimized for Hugging Face Spaces
|
| 27 |
+
client = OpenAI(
|
| 28 |
+
api_key=openai_api_key,
|
| 29 |
+
timeout=60.0, # Longer timeout for HF Spaces network
|
| 30 |
+
max_retries=3 # Retry on connection failures
|
| 31 |
+
)
|
| 32 |
|
| 33 |
# Explanation complexity levels with clear descriptions
|
| 34 |
EXPLANATION_LEVELS = {
|
|
|
|
| 101 |
except Exception as e:
|
| 102 |
# Provide more specific error messages for common issues
|
| 103 |
error_msg = str(e).lower()
|
| 104 |
+
error_type = type(e).__name__
|
| 105 |
+
|
| 106 |
+
# Log full error for debugging (visible in HF Spaces logs)
|
| 107 |
+
print(f"β API Error [{error_type}]: {str(e)}")
|
| 108 |
+
|
| 109 |
+
if "connection" in error_msg or "timeout" in error_msg or "ssl" in error_msg:
|
| 110 |
+
yield f"""β **Connection Error**: Unable to reach OpenAI API.
|
| 111 |
+
|
| 112 |
+
**On Hugging Face Spaces:**
|
| 113 |
+
1. Verify `OPENAI_API_KEY` is set in **Settings β Repository secrets**
|
| 114 |
+
2. Restart the Space after adding the secret
|
| 115 |
+
3. Check the Logs tab for detailed error messages
|
| 116 |
+
|
| 117 |
+
**Error details**: `{error_type}: {str(e)[:200]}`"""
|
| 118 |
+
elif "api key" in error_msg or "authentication" in error_msg or "401" in error_msg:
|
| 119 |
+
yield """β **Authentication Error**: Invalid or missing API key.
|
| 120 |
+
|
| 121 |
+
**Fix**: Go to **Settings β Repository secrets** and add:
|
| 122 |
+
- Name: `OPENAI_API_KEY`
|
| 123 |
+
- Value: Your OpenAI API key (starts with `sk-`)"""
|
| 124 |
+
elif "rate limit" in error_msg or "429" in error_msg:
|
| 125 |
+
yield "β **Rate Limit**: Too many requests. Please wait a moment and try again."
|
| 126 |
+
elif "model" in error_msg or "404" in error_msg:
|
| 127 |
+
yield f"β **Model Error**: The model may not be available.\n\nError: `{str(e)}`"
|
| 128 |
else:
|
| 129 |
+
yield f"β **Error**: `[{error_type}]` {str(e)}"
|
| 130 |
|
| 131 |
# Create enhanced Gradio interface with modern styling
|
| 132 |
with gr.Blocks(
|
|
|
|
| 224 |
|
| 225 |
print("π Starting AI Concept Explainer...")
|
| 226 |
print(f"Environment: {'Hugging Face Spaces' if is_space else 'Local Development'}")
|
| 227 |
+
print(f"API Key configured: {'β
Yes' if openai_api_key else 'β No'}")
|
| 228 |
+
if openai_api_key:
|
| 229 |
+
print(f"API Key starts with: {openai_api_key[:10]}...")
|
| 230 |
+
|
| 231 |
+
# Test OpenAI connection at startup (HF Spaces only)
|
| 232 |
+
if is_space:
|
| 233 |
+
try:
|
| 234 |
+
print("\nπ Testing OpenAI API connection...")
|
| 235 |
+
# Simple API test
|
| 236 |
+
test_models = client.models.list()
|
| 237 |
+
print("β
OpenAI API connection successful!")
|
| 238 |
+
except Exception as e:
|
| 239 |
+
print(f"β οΈ WARNING: OpenAI API connection test failed!")
|
| 240 |
+
print(f" Error: [{type(e).__name__}] {str(e)}")
|
| 241 |
+
print(f" The app will start, but API calls may fail.")
|
| 242 |
+
print(f" Check: 1) OPENAI_API_KEY secret is set, 2) API key is valid")
|
| 243 |
|
| 244 |
if is_space:
|
| 245 |
# Production configuration for Hugging Face Spaces
|
requirements.txt
CHANGED
|
@@ -3,7 +3,9 @@
|
|
| 3 |
# gradio==5.46.0
|
| 4 |
# openai==1.107.3
|
| 5 |
# python-dotenv==1.1.1
|
|
|
|
| 6 |
|
| 7 |
gradio
|
| 8 |
openai
|
| 9 |
-
python-dotenv
|
|
|
|
|
|
| 3 |
# gradio==5.46.0
|
| 4 |
# openai==1.107.3
|
| 5 |
# python-dotenv==1.1.1
|
| 6 |
+
# httpx==0.27.0
|
| 7 |
|
| 8 |
gradio
|
| 9 |
openai
|
| 10 |
+
python-dotenv
|
| 11 |
+
httpx
|