Spaces:
Sleeping
Sleeping
Create app.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152"""Simple OpenAI API Test for Hugging Face SpacesTests if OpenAI API key is working correctly"""
import gradio as grimport osfrom openai import OpenAI
# Global OpenAI clientopenai_client = Noneapi_status = "π Checking..."
def init_openai(): """Initialize OpenAI client""" global openai_client, api_status try: api_key = os.getenv("OPENAI_API_KEY") if not api_key: api_status = "β No OPENAI_API_KEY found in environment" return False if not api_key.startswith("sk-"): api_status = "β Invalid API key format (should start with sk-)" return False if len(api_key) < 20: api_status = "β API key too short" return False # Create client openai_client = OpenAI(api_key=api_key) # Test with a simple request response = openai_client.chat.completions.create( model="gpt-3.5-turbo", messages=[{"role": "user", "content": "Say 'Hello, I'm working!'"}], max_tokens=10 ) if response.choices[0].message.content: api_status = "β
OpenAI API working perfectly!" return True else: api_status = "β Empty response from OpenAI" return False except Exception as e: api_status = f"β Error: {str(e)}" return False
def test_openai_simple(message): """Simple test function""" if not openai_client: return "β OpenAI not initialized. Check your API key." if not message.strip(): return "Please enter a message to test." try: response = openai_client.chat.completions.create( model="gpt-3.5-turbo", messages=[ {"role": "system", "content": "You are a helpful assistant. Keep responses short and friendly."}, {"role": "user", "content": message} ], max_tokens=100, temperature=0.7 ) return f"β
SUCCESS! OpenAI Response:\n\n{response.choices[0].message.content}" except Exception as e: return f"β ERROR: {str(e)}"
# Initialize on startupprint("Initializing OpenAI...")init_success = init_openai()print(f"OpenAI status: {api_status}")
# Create Gradio interfacewith gr.Blocks(title="OpenAI API Test") as demo: gr.Markdown(""" # π€ OpenAI API Test ### Simple test to verify OpenAI API integration in HF Spaces """) # Status display with gr.Row(): status_display = gr.Markdown(f"**π API Status:** {api_status}") # Test interface with gr.Row(): with gr.Column(): test_input = gr.Textbox( label="Test Message", placeholder="Type anything to test OpenAI...", value="Hello! Can you tell me a short joke?" ) test_btn = gr.Button("π§ͺ Test OpenAI API", variant="primary") with gr.Column(): test_output = gr.Textbox( label="OpenAI Response", placeholder="Response will appear here...", lines=5 ) # Event handler test_btn.click( fn=test_openai_simple, inputs=[test_input], outputs=[test_output] ) # Instructions gr.Markdown(""" --- ## π§ Setup Instructions ### 1. Add HF Space Secret Go to your Space settings β Repository secrets and add: ``` OPENAI_API_KEY = sk-your-actual-openai-key ``` ### 2. Requirements.txt ``` gradio==5.34.1 openai==1.35.3 ``` ### 3. Test Results - β
**Success**: API key is working, OpenAI integration ready - β **Failure**: Check API key format, quota, or connection ### 4. Common Issues - **"No OPENAI_API_KEY found"**: Add the secret to your Space - **"Invalid API key format"**: Key should start with `sk-` - **"Insufficient quota"**: Check your OpenAI billing - **"Rate limit"**: Wait a moment and try again ### 5. Next Steps Once this works, you can copy the exact same pattern to your main RAG app! """)
if __name__ == "__main__": demo.launch()app.pyAdded+152