Spaces:
Sleeping
Sleeping
| import requests | |
| import gradio as gr | |
| def chat_with_openai(api_key, prompt): | |
| if not api_key.strip() or not prompt.strip(): | |
| return "Please provide both an API key and a prompt." | |
| try: | |
| api_url = "https://api.openai.com/v1/chat/completions" | |
| headers = { | |
| "Authorization": f"Bearer {api_key}", | |
| "Content-Type": "application/json", | |
| } | |
| data = { | |
| "model": "gpt-4o-mini", | |
| "messages": [ | |
| {"role": "user", "content": prompt} | |
| ], | |
| } | |
| response = requests.post(api_url, headers=headers, json=data) | |
| if response.status_code == 200: | |
| tmp = response.json() | |
| result = tmp['choices'][0]['message']['content'] | |
| return result | |
| else: | |
| print("ERROR: Failed: ", response.text) | |
| return None | |
| except Exception as e: | |
| return f"Error: {str(e)}" | |
| gradio_app = gr.Interface( | |
| fn=chat_with_openai, | |
| inputs=[ | |
| gr.Textbox(label="OpenAI API Key", placeholder="sk-...", type="password"), | |
| gr.Textbox(label="Prompt", placeholder="Tell me a joke"), | |
| ], | |
| outputs="text", | |
| title="OpenAI Example; V0.0.7", | |
| description="Enter your OpenAI API key and a prompt like 'Tell me a joke'." | |
| ) | |
| if __name__ == "__main__": | |
| gradio_app.launch() |