File size: 2,594 Bytes
af32aba
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fe537c7
af32aba
 
fe537c7
af32aba
fc822a7
af32aba
fe537c7
af32aba
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fe537c7
af32aba
 
 
 
 
 
 
 
 
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
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()