Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import gradio as gr
|
| 3 |
+
from openai import OpenAI
|
| 4 |
+
from dotenv import load_dotenv
|
| 5 |
+
|
| 6 |
+
# Load environment variables from .env file
|
| 7 |
+
load_dotenv()
|
| 8 |
+
|
| 9 |
+
# Get API key from environment variable
|
| 10 |
+
api_key = os.getenv("OPENAI_API_KEY")
|
| 11 |
+
|
| 12 |
+
# Initialize OpenAI client
|
| 13 |
+
client = OpenAI(
|
| 14 |
+
base_url="https://models.inference.ai.azure.com",
|
| 15 |
+
api_key=api_key
|
| 16 |
+
)
|
| 17 |
+
|
| 18 |
+
# Function to get response from OpenAI
|
| 19 |
+
def chat_with_ai(user_input):
|
| 20 |
+
try:
|
| 21 |
+
response = client.chat.completions.create(
|
| 22 |
+
model="gpt-4o",
|
| 23 |
+
messages=[
|
| 24 |
+
{"role": "system", "content": "You are a helpful assistant."},
|
| 25 |
+
{"role": "user", "content": user_input},
|
| 26 |
+
]
|
| 27 |
+
)
|
| 28 |
+
return response.choices[0].message.content
|
| 29 |
+
except Exception as e:
|
| 30 |
+
return f"Error: {str(e)}"
|
| 31 |
+
|
| 32 |
+
# Create Gradio UI
|
| 33 |
+
iface = gr.Interface(
|
| 34 |
+
fn=chat_with_ai,
|
| 35 |
+
inputs="text",
|
| 36 |
+
outputs="text",
|
| 37 |
+
title="AI Chatbot",
|
| 38 |
+
description="A chatbot powered by OpenAI's API."
|
| 39 |
+
)
|
| 40 |
+
|
| 41 |
+
# Run the app
|
| 42 |
+
if __name__ == "__main__":
|
| 43 |
+
iface.launch()
|