Spaces:
Sleeping
Sleeping
import os | |
import gradio as gr | |
from openai import OpenAI | |
from dotenv import load_dotenv | |
# Load environment variables from .env file | |
load_dotenv() | |
# Get API key from environment variable | |
api_key = os.getenv("OPENAI_API_KEY") | |
# Initialize OpenAI client | |
client = OpenAI( | |
base_url="https://models.inference.ai.azure.com", | |
api_key=api_key | |
) | |
# Function to get response from OpenAI | |
def chat_with_ai(user_input): | |
try: | |
response = client.chat.completions.create( | |
model="gpt-4o", | |
messages=[ | |
{"role": "system", "content": "You are a helpful assistant."}, | |
{"role": "user", "content": user_input}, | |
] | |
) | |
return response.choices[0].message.content | |
except Exception as e: | |
return f"Error: {str(e)}" | |
# Create Gradio UI | |
iface = gr.Interface( | |
fn=chat_with_ai, | |
inputs="text", | |
outputs="text", | |
title="AI Chatbot", | |
description="A chatbot powered by OpenAI's API." | |
) | |
# Run the app | |
if __name__ == "__main__": | |
iface.launch() | |