File size: 1,921 Bytes
fa485bd
6bf0f73
 
fa485bd
6bf0f73
 
 
 
 
 
 
 
 
 
fa485bd
6bf0f73
fa485bd
6bf0f73
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fa485bd
 
 
 
 
 
 
6bf0f73
 
fa485bd
 
6bf0f73
fa485bd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# 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()