Callmebowoo-22 commited on
Commit
a758968
·
verified ·
1 Parent(s): c561e50

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +108 -30
app.py CHANGED
@@ -1,36 +1,114 @@
 
1
  import gradio as gr
2
  from openai import OpenAI
 
3
 
4
- # Konfigurasi OpenRouter
5
- client = OpenAI(
6
- base_url="https://openrouter.ai/api/v1",
7
- api_key="your-openrouter-api-key", # Ganti dengan API key OpenRouter Anda
8
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9
 
10
  def respond(message, history):
11
- # Kirim pesan ke model DeepSeek R1 Zero
12
- completion = client.chat.completions.create(
13
- extra_headers={
14
- "HTTP-Referer": "https://huggingface.co/spaces", # Optional
15
- "X-Title": "DeepSeek Chatbot", # Optional
16
- },
17
- model="deepseek/deepseek-r1-zero:free",
18
- messages=[
19
- {"role": "system", "content": "Anda adalah asisten AI yang membantu. Berikan jawaban yang singkat dan jelas."},
20
- *[{"role": "user" if i % 2 == 0 else "assistant", "content": h} for i, h in enumerate(history)],
21
- {"role": "user", "content": message}
22
- ]
23
- )
24
 
25
- return completion.choices[0].message.content
26
-
27
- # Buat antarmuka chatbot
28
- demo = gr.ChatInterface(
29
- respond,
30
- title="DeepSeek R1 Zero Chatbot",
31
- description="Chatbot menggunakan model DeepSeek R1 Zero melalui OpenRouter",
32
- theme="soft",
33
- examples=["Apa itu AI?", "Buatkan puisi pendek", "Jelaskan teori relativitas dengan sederhana"]
34
- )
35
-
36
- demo.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
  import gradio as gr
3
  from openai import OpenAI
4
+ from dotenv import load_dotenv
5
 
6
+ # Memuat environment variables
7
+ load_dotenv()
8
+
9
+ class Chatbot:
10
+ def __init__(self):
11
+ # Dapatkan API key dari environment variables
12
+ self.api_key = os.getenv("OPENROUTER_API_KEY")
13
+
14
+ if not self.api_key:
15
+ raise ValueError(
16
+ "OpenRouter API key not found. "
17
+ "Please set it in Hugging Face Secrets or .env file."
18
+ )
19
+
20
+ self.client = OpenAI(
21
+ base_url="https://openrouter.ai/api/v1",
22
+ api_key=self.api_key,
23
+ )
24
+
25
+ # Konfigurasi model
26
+ self.model = "deepseek/deepseek-r1-zero:free"
27
+ self.system_prompt = """
28
+ Anda adalah asisten AI yang membantu. Berikan jawaban yang:
29
+ - Singkat dan jelas
30
+ - Ramah dan informatif
31
+ - Relevan dengan pertanyaan
32
+ """
33
+
34
+ def generate_response(self, message, history):
35
+ """Generate AI response based on message and conversation history"""
36
+ try:
37
+ # Format conversation history
38
+ messages = [{"role": "system", "content": self.system_prompt}]
39
+
40
+ for i, h in enumerate(history):
41
+ messages.append({
42
+ "role": "user" if i % 2 == 0 else "assistant",
43
+ "content": h
44
+ })
45
+
46
+ messages.append({"role": "user", "content": message})
47
+
48
+ # Kirim permintaan ke API
49
+ completion = self.client.chat.completions.create(
50
+ extra_headers={
51
+ "HTTP-Referer": "https://huggingface.co/spaces",
52
+ "X-Title": "DeepSeek Chatbot",
53
+ },
54
+ model=self.model,
55
+ messages=messages,
56
+ temperature=0.7,
57
+ max_tokens=500
58
+ )
59
+
60
+ return completion.choices[0].message.content
61
+
62
+ except Exception as e:
63
+ print(f"Error generating response: {str(e)}")
64
+ return f"Maaf, terjadi error: {str(e)}"
65
+
66
+ # Inisialisasi chatbot
67
+ try:
68
+ chatbot = Chatbot()
69
+ except ValueError as e:
70
+ print(str(e))
71
+ chatbot = None
72
 
73
  def respond(message, history):
74
+ if not chatbot:
75
+ return "Error: Chatbot tidak dapat diinisialisasi. Periksa konfigurasi API key."
 
 
 
 
 
 
 
 
 
 
 
76
 
77
+ return chatbot.generate_response(message, history)
78
+
79
+ # Contoh pertanyaan
80
+ examples = [
81
+ "Apa itu kecerdasan buatan?",
82
+ "Buatkan puisi tentang teknologi",
83
+ "Jelaskan teori relativitas dengan sederhana",
84
+ "Apa kelebihan model DeepSeek?"
85
+ ]
86
+
87
+ # Buat antarmuka Gradio
88
+ with gr.Blocks(theme=gr.themes.Soft()) as demo:
89
+ gr.Markdown("""
90
+ # 🤖 DeepSeek R1 Zero Chatbot
91
+ Chatbot cerdas menggunakan model DeepSeek R1 Zero melalui OpenRouter API
92
+ """)
93
+
94
+ with gr.Row():
95
+ with gr.Column():
96
+ gr.ChatInterface(
97
+ respond,
98
+ examples=examples,
99
+ retry_btn="Coba Lagi",
100
+ undo_btn="Undo",
101
+ clear_btn="Bersihkan"
102
+ )
103
+ with gr.Column():
104
+ gr.Markdown("""
105
+ ### Tentang Chatbot Ini
106
+ - Menggunakan model **DeepSeek R1 Zero**
107
+ - Diakses melalui **OpenRouter API**
108
+ - Dibangun dengan **Gradio** di Hugging Face Spaces
109
+
110
+ **Catatan**: Chatbot ini hanya untuk demonstrasi.
111
+ """)
112
+
113
+ if __name__ == "__main__":
114
+ demo.launch()