asad231's picture
Update app.py
c6da0a5 verified
# # app.py (Advanced Design for VoltAIon - AI Chatbot)
# import gradio as gr
# import os
# import requests
# # API Setup
# API_KEY = os.getenv("AIML_API_KEY")
# API_URL = "https://api.aimlapi.com/v1/chat/completions"
# # Keep conversation history
# chat_history = []
# def query_gpt5(user_input):
# global chat_history
# if not API_KEY:
# return [("System", "⚠️ API Key not set. Please set AIML_API_KEY in secrets.")]
# headers = {"Authorization": f"Bearer {API_KEY}"}
# messages = [{"role": "system", "content": "You are an expert assistant for battery materials and sustainable energy."}]
# # Append conversation history
# for role, content in chat_history:
# messages.append({"role": role, "content": content})
# messages.append({"role": "user", "content": user_input})
# data = {"model": "openai/gpt-4o", "messages": messages}
# try:
# response = requests.post(API_URL, headers=headers, json=data)
# response.raise_for_status()
# resp_json = response.json()
# if "choices" in resp_json:
# bot_reply = resp_json["choices"][0]["message"]["content"]
# chat_history.append(("user", user_input))
# chat_history.append(("assistant", bot_reply))
# return [(u, a) for u, a in chat_history if u != "system"]
# elif "error" in resp_json:
# return [("System", f"❌ Error: {resp_json['error']}")]
# else:
# return [("System", f"Unexpected API response: {resp_json}")]
# except Exception as e:
# return [("System", f"⚠️ API request failed: {e}")]
# # Reset chat
# def reset_chat():
# global chat_history
# chat_history = []
# return []
# # Gradio UI with chat style
# with gr.Blocks(theme=gr.themes.Soft(primary_hue="green", secondary_hue="emerald")) as demo:
# with gr.Row():
# with gr.Column(scale=1):
# gr.Markdown(
# """
# # ⚑ VoltAIon - AI Research Assistant
# πŸ€– *Your Sustainable Energy & Battery Materials Expert*
# ---
# Ask any question about **battery chemistry, EV storage, lithium-ion, or renewable energy solutions.**
# """)
# clear_btn = gr.Button("πŸ”„ Reset Chat", variant="secondary")
# with gr.Column(scale=2):
# chatbot = gr.Chatbot(label="VoltAIon Chat", height=500, bubble_full_width=False, show_copy_button=True)
# user_input = gr.Textbox(placeholder="Type your question here...", label="Your Question")
# submit_btn = gr.Button("πŸš€ Ask AI", variant="primary")
# submit_btn.click(query_gpt5, inputs=user_input, outputs=chatbot)
# user_input.submit(query_gpt5, inputs=user_input, outputs=chatbot)
# clear_btn.click(reset_chat, outputs=chatbot)
# # Launch for Hugging Face
# if __name__ == "__main__":
# demo.launch()
# app.py (Fixed VoltAIon - AI Chatbot)
import gradio as gr
import os
import requests
# βœ… Directly add your API key here for testing (replace with your key)
API_KEY = os.getenv("AIML_API_KEY") or "YOUR_API_KEY_HERE"
API_URL = "https://api.aimlapi.com/v1/chat/completions"
# Keep conversation history
chat_history = []
def query_gpt5(user_input):
global chat_history
if not API_KEY:
return [("System", "⚠️ API Key not set. Please set AIML_API_KEY in secrets.")]
headers = {"Authorization": f"Bearer {API_KEY}"}
messages = [{"role": "system", "content": "You are an expert assistant for battery materials and sustainable energy."}]
# Append previous chat history
for role, content in chat_history:
messages.append({"role": role, "content": content})
messages.append({"role": "user", "content": user_input})
data = {"model": "openai/gpt-4o", "messages": messages}
try:
response = requests.post(API_URL, headers=headers, json=data, timeout=20)
response.raise_for_status()
resp_json = response.json()
if "choices" in resp_json and len(resp_json["choices"]) > 0:
bot_reply = resp_json["choices"][0]["message"]["content"]
chat_history.append(("user", user_input))
chat_history.append(("assistant", bot_reply))
return chat_history
elif "error" in resp_json:
return [("System", f"❌ Error: {resp_json['error']}")]
else:
return [("System", f"Unexpected API response: {resp_json}")]
except requests.exceptions.RequestException as e:
return [("System", f"⚠️ API request failed: {e}")]
# Reset chat
def reset_chat():
global chat_history
chat_history = []
return []
# Gradio UI
with gr.Blocks(theme=gr.themes.Soft(primary_hue="green", secondary_hue="emerald")) as demo:
with gr.Row():
with gr.Column(scale=1):
gr.Markdown(
"""
# ⚑ VoltAIon - AI Research Assistant
πŸ€– *Your Sustainable Energy & Battery Materials Expert*
---
Ask any question about **battery chemistry, EV storage, lithium-ion, or renewable energy solutions.**
"""
)
clear_btn = gr.Button("πŸ”„ Reset Chat", variant="secondary")
with gr.Column(scale=2):
chatbot = gr.Chatbot(label="VoltAIon Chat", height=500, bubble_full_width=False, show_copy_button=True)
user_input = gr.Textbox(placeholder="Type your question here...", label="Your Question")
submit_btn = gr.Button("πŸš€ Ask AI", variant="primary")
submit_btn.click(query_gpt5, inputs=user_input, outputs=chatbot)
user_input.submit(query_gpt5, inputs=user_input, outputs=chatbot)
clear_btn.click(reset_chat, outputs=chatbot)
if __name__ == "__main__":
demo.launch()