SuperAI-1 / app.py
Imogi's picture
Update app.py
fe537c7 verified
import os
import gradio as gr
import requests
import json
# OpenRouter API URL
OPENROUTER_URL = "https://openrouter.ai/api/v1/chat/completions"
def predict(message, history):
# Hugging Face-er Settings > Variables theke OPENROUTER_API_KEY nibe
api_key = os.getenv("OPENROUTER_API_KEY")
if not api_key:
yield "Error: OpenRouter API Key khunje paoya jayni! Please check Hugging Face Settings."
return
# Past chat history convert kora OpenRouter format-e
messages = []
for user_msg, bot_msg in history:
messages.append({"role": "user", "content": user_msg})
messages.append({"role": "assistant", "content": bot_msg})
# Current message jog kora
messages.append({"role": "user", "content": message})
# Request Header
headers = {
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json",
"HTTP-Referer": "https://huggingface.co/spaces",
}
# Request Body
payload = {
"model": "arcee-ai/trinity-large-thinking:free",
"messages": messages,
"stream": True
}
try:
response = requests.post(OPENROUTER_URL, headers=headers, json=payload, stream=True)
partial_message = ""
for line in response.iter_lines():
if line:
line_str = line.decode("utf-8")
if line_str.startswith("data: "):
data_content = line_str[6:]
if data_content.strip() == "[DONE]":
break
try:
json_data = json.loads(data_content)
if "choices" in json_data and len(json_data["choices"]) > 0:
delta = json_data["choices"][0].get("delta", {})
if "content" in delta:
partial_message += delta["content"]
yield partial_message
except json.JSONDecodeError:
pass
except Exception as e:
yield f"An error occurred: {str(e)}"
# Gradio ChatInterface UI toiri (Eখান থেকে theme সল্যুশন করা হয়েছে)
demo = gr.ChatInterface(
fn=predict,
title="🚀 OpenRouter AI Chatbot",
description="OpenRouter API key use kore Hugging Face Spaces-e cholche apnar custom AI Chatbot!",
examples=["Hi, who are you?", "Write a Python function to check a prime number.", "Give me a YouTube video script idea."]
)
if __name__ == "__main__":
demo.launch()