File size: 3,504 Bytes
a758968
b01280f
c648bf5
a758968
b01280f
a758968
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b01280f
c648bf5
a758968
 
c648bf5
a758968
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
import os
import gradio as gr
from openai import OpenAI
from dotenv import load_dotenv

# Memuat environment variables
load_dotenv()

class Chatbot:
    def __init__(self):
        # Dapatkan API key dari environment variables
        self.api_key = os.getenv("OPENROUTER_API_KEY")
        
        if not self.api_key:
            raise ValueError(
                "OpenRouter API key not found. "
                "Please set it in Hugging Face Secrets or .env file."
            )
        
        self.client = OpenAI(
            base_url="https://openrouter.ai/api/v1",
            api_key=self.api_key,
        )
        
        # Konfigurasi model
        self.model = "deepseek/deepseek-r1-zero:free"
        self.system_prompt = """
        Anda adalah asisten AI yang membantu. Berikan jawaban yang:
        - Singkat dan jelas
        - Ramah dan informatif
        - Relevan dengan pertanyaan
        """

    def generate_response(self, message, history):
        """Generate AI response based on message and conversation history"""
        try:
            # Format conversation history
            messages = [{"role": "system", "content": self.system_prompt}]
            
            for i, h in enumerate(history):
                messages.append({
                    "role": "user" if i % 2 == 0 else "assistant",
                    "content": h
                })
            
            messages.append({"role": "user", "content": message})
            
            # Kirim permintaan ke API
            completion = self.client.chat.completions.create(
                extra_headers={
                    "HTTP-Referer": "https://huggingface.co/spaces",
                    "X-Title": "DeepSeek Chatbot",
                },
                model=self.model,
                messages=messages,
                temperature=0.7,
                max_tokens=500
            )
            
            return completion.choices[0].message.content
            
        except Exception as e:
            print(f"Error generating response: {str(e)}")
            return f"Maaf, terjadi error: {str(e)}"

# Inisialisasi chatbot
try:
    chatbot = Chatbot()
except ValueError as e:
    print(str(e))
    chatbot = None

def respond(message, history):
    if not chatbot:
        return "Error: Chatbot tidak dapat diinisialisasi. Periksa konfigurasi API key."
    
    return chatbot.generate_response(message, history)

# Contoh pertanyaan
examples = [
    "Apa itu kecerdasan buatan?",
    "Buatkan puisi tentang teknologi",
    "Jelaskan teori relativitas dengan sederhana",
    "Apa kelebihan model DeepSeek?"
]

# Buat antarmuka Gradio
with gr.Blocks(theme=gr.themes.Soft()) as demo:
    gr.Markdown("""
    # 🤖 DeepSeek R1 Zero Chatbot
    Chatbot cerdas menggunakan model DeepSeek R1 Zero melalui OpenRouter API
    """)
    
    with gr.Row():
        with gr.Column():
            gr.ChatInterface(
                respond,
                examples=examples,
                retry_btn="Coba Lagi",
                undo_btn="Undo",
                clear_btn="Bersihkan"
            )
        with gr.Column():
            gr.Markdown("""
            ### Tentang Chatbot Ini
            - Menggunakan model **DeepSeek R1 Zero**
            - Diakses melalui **OpenRouter API**
            - Dibangun dengan **Gradio** di Hugging Face Spaces
            
            **Catatan**: Chatbot ini hanya untuk demonstrasi.
            """)

if __name__ == "__main__":
    demo.launch()