Spaces:
Sleeping
Sleeping
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() |