VOLTALON / app.py
Bushra346's picture
Update app.py
fa485bd verified
# app.py (Simplified for AI Chat Only)
import gradio as gr
import os
import requests
# Assuming your API key is set as an environment variable in Hugging Face Spaces secrets
API_KEY = os.getenv("AIML_API_KEY")
API_URL = "https://api.aimlapi.com/v1/chat/completions"
def query_gpt5(user_input):
if not API_KEY:
return "API Key not set. Please set AIML_API_KEY environment variable."
headers = {"Authorization": f"Bearer {API_KEY}"}
data = {
"model": "openai/gpt-4o", # Or another model you have access to
"messages": [
{"role": "system", "content": "You are an expert assistant for battery materials and sustainable energy."},
{"role": "user", "content": user_input}
]
}
try:
response = requests.post(API_URL, headers=headers, json=data)
response.raise_for_status() # Raise an HTTPError for bad responses (4xx or 5xx)
resp_json = response.json()
if "choices" in resp_json:
return resp_json["choices"][0]["message"]["content"]
elif "error" in resp_json:
return f"Error from API: {resp_json['error']}"
else:
return f"Unexpected API response structure: {resp_json}"
except requests.exceptions.RequestException as e:
return f"API request failed: {e}"
except Exception as e:
return f"An error occurred during API query: {e}"
# Define Gradio Interface
ai_chat_interface = gr.Interface(
fn=query_gpt5,
inputs=gr.Textbox(label="Ask about Battery Materials or Sustainable Energy"),
outputs=gr.Textbox(label="AI Research Assistant"),
title="🤖 VoltAIon - AI Research Assistant (API Key Focus)",
description="Ask questions about battery materials and sustainable energy using the API."
)
# Launch the interface
# For deployment on Hugging Face Spaces, use launch()
if __name__ == "__main__":
ai_chat_interface.launch()