|
|
|
|
|
import gradio as gr |
|
|
import os |
|
|
import requests |
|
|
|
|
|
|
|
|
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", |
|
|
"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() |
|
|
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}" |
|
|
|
|
|
|
|
|
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." |
|
|
) |
|
|
|
|
|
|
|
|
|
|
|
if __name__ == "__main__": |
|
|
ai_chat_interface.launch() |