File size: 8,668 Bytes
8930085
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4073896
 
8930085
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
import gradio as gr
import os
import requests
import time

# Daftar model dengan deskripsi
MODELS_INFO = {
    "anthropic/claude-opus-4": {"name": "Claude Opus 4", "description": "Model AI paling canggih Anthropic untuk tugas kompleks"},
    "anthropic/claude-sonnet-4": {"name": "Claude Sonnet 4", "description": "Keseimbangan antara kemampuan dan kecepatan"},
    "deepseek/deepseek-r1-0528": {"name": "DeepSeek R1", "description": "Model bahasa open-source khusus untuk reasoning"},
    "deepseek/deepseek-chat-v3-0324": {"name": "DeepSeek Chat v3", "description": "Dioptimalkan untuk dialog general"},
    "openai/gpt-4.1": {"name": "GPT-4.1", "description": "Generasi penyusun teks OpenAI terbaru"},
    "openai/gpt-4.1-mini": {"name": "GPT-4.1 Mini", "description": "Versi lebih kecil dan cepat dari GPT-4.1"},
    "google/gemini-2.5-pro-preview": {"name": "Gemini 2.5 Pro", "description": "Model Google terbaru untuk pemahaman kompleks"},
    "microsoft/phi-4-reasoning-plus": {"name": "Phi-4 Reasoning", "description": "Pakar penalaran matematika dan logika"},
    "qwen/qwen3-30b-a3b": {"name": "Qwen 30B", "description": "Model bahasa besar dari China"},
    "meta-llama/llama-guard-4-12b": {"name": "Llama Guard 4", "description": "Model khusus untuk moderasi konten"},
    "meta-llama/llama-4-maverick": {"name": "Llama 4 Maverick", "description": "Model kreatif untuk penulisan"},  
    "meta-llama/llama-4-scout": {"name": "Llama 4 Scout", "description": "Direncanakan sebagai penerus Gemini ini"},
    "x-ai/grok-2-vision-1212": {"name": "Grok-2 Vision", "description": "Model multimodal X-AI untuk teks dan gambar"}}
}

# Default models list
MODELS = list(MODELS_INFO.keys())

def chat_with_openrouter(prompt, system_prompt, model):
    try:
        # Konfigurasi API OpenRouter
        api_url = "https://openrouter.ai/api/v1/chat/completions"
        api_key = os.environ.get("OPENROUTER_API_KEY")
        
        # Header untuk autentikasi
        headers = {
            "Authorization": f"Bearer {api_key}",
            "HTTP-Referer": "https://huggingface.co",
            "X-Title": "OpenRouter Space",
        }
        
        # Bangun pesan dengan sistem prompt
        messages = []
        if system_prompt.strip():
            messages.append({"role": "system", "content": system_prompt})
        messages.append({"role": "user", "content": prompt})
        
        # Body request
        data = {
            "model": model,
            "messages": messages,
            "max_tokens": 2048
        }
        
        start_time = time.time()
        
        # Kirim request ke OpenRouter
        response = requests.post(api_url, headers=headers, json=data, timeout=90)
        response.raise_for_status()
        
        # Ekstrak dan kembalikan respons
        result = response.json()
        
        end_time = time.time()
        processing_time = f"\n\nπŸ•’ Waktu pemrosesan: {end_time - start_time:.2f} detik"
        
        return result["choices"][0]["message"]["content"] + processing_time
    
    except Exception as e:
        error_detail = f"{str(e)}"
        if hasattr(e, 'response') and e.response:
            try:
                error_resp = e.response.json()
                error_detail += f"\nError: {error_resp.get('error', {}).get('message', 'Unknown error')}"
            except:
                error_detail += f"\nStatus: {e.response.status_code}\nResponse: {e.response.text[:500]}"
        return f"🚨 Error: {error_detail}"

# CSS Styles
with open("style.css", "r") as f:
    css_content = f.read()

# Buat antarmuka Gradio dengan CSS
with gr.Blocks(css=css_content, theme=gr.themes.Soft()) as demo:
    gr.Markdown("#app-container", visible=False)
    
    # Header Section
    with gr.Column(elem_classes="header"):
        gr.Markdown("""
        # πŸ€– Advanced AI Chat Assistant
        Eksplorasi model AI terbaik melalui OpenRouter
        """)
    
    # Main Content
    with gr.Row(elem_classes="content"):
        # Left Controls Panel
        with gr.Column(elem_classes="controls"):
            with gr.Group(elem_classes="model-selector"):
                selected_model = gr.Dropdown(
                    label="Pilih Model AI",
                    choices=MODELS,
                    value="anthropic/claude-opus-4",
                    interactive=True,
                    elem_id="model-dropdown"
                )
                
            # Preview model info cards
            with gr.Group():
                gr.Markdown("### Info Model")
                with gr.Row():
                    for model_id in MODELS:
                        info = MODELS_INFO[model_id]
                        with gr.Column(min_width=250):
                            card = gr.Checkbox(
                                label=f"**{info['name']}**\n{info['description']}",
                                value=(model_id == "anthropic/claude-opus-4"),
                                elem_classes="model-card",
                                elem_id=f"model-card-{model_id}"
                            )
                            card.change(lambda x,m=model_id: m, inputs=[card], outputs=[selected_model])
            
            with gr.Group(elem_classes="system-prompt-area"):
                system_prompt = gr.Textbox(
                    label="Sistem Prompt (Opsional)",
                    placeholder="Contoh: 'Anda adalah ahli bahasa Indonesia yang ramah dan membantu'",
                    lines=5,
                    max_lines=10
                )
            
            with gr.Group(elem_classes="tips"):
                gr.Markdown("### πŸš€ Tips Penggunaan")
                gr.Markdown("""
                - Claude Opus: Terbaik untuk tugas kompleks
                - Gemini 2.5: Penalaran kuat dan detail
                - GPT-4.1: Kreativi tinggi dan fleksibel
                - Llama 4: Variasi fungsi khusus
                - **Ctrl+Enter** untuk mengirim prompt
                - Gunakan contoh di bawah untuk memulai
                """)
        
        # Right Chat Panel
        with gr.Column(elem_classes="chat-container"):
            with gr.Column(elem_classes="chat-area"):
                with gr.Group(elem_classes="chat-input"):
                    prompt = gr.Textbox(
                        label="Pertanyaan/Permintaan",
                        placeholder="Tulis pesan untuk AI di sini...",
                        lines=6
                    )
                    with gr.Row():
                        clear_btn = gr.Button("Hapus")
                        submit_btn = gr.Button("Kirim ke AI", elem_classes="btn-submit")
                
                with gr.Group(elem_classes="chat-output"):
                    output = gr.Textbox(
                        label="Respon AI",
                        lines=15,
                        interactive=False
                    )
    
    # Kwamples Section
    with gr.Group(elem_classes="examples"):
        gr.Examples(
            examples=[
                ["Terjemahkan artikel ilmiah ini ke bahasa Indonesia: [...teks ilmiah...]", "", "openai/gpt-4.1"],
                ["Tulis puisi tentang budaya Indonesia dalam gaya Chairil Anwar", "Pakai bahasa Indonesia dengan gaya puisi modern", "anthropic/claude-sonnet-4"],
                ["Jelaskan black hole dalam konsep relativitas umum secara sederhana", "Anda adalah profesor astrofisika yang ramah", "google/gemini-2.5-pro-preview"],
                ["Ubahlah kode ini menjadi lebih efisien: [contoh kode Python]", "Fokus pada penggunaan memori dan kompleksitas algoritma", "microsoft/phi-4-reasoning-plus"]
            ],
            inputs=[prompt, system_prompt, selected_model],
            label="Contoh Permintaan AI"
        )
    
    # Footer
    with gr.Column(elem_classes="footer"):
        gr.Markdown(""" 
        ### Dibangun dengan πŸ€—
        Powered by [OpenRouter](https://openrouter.ai) | 
        [Sumber Daya API](https://openrouter.ai/docs) | 
        [Statistik Penggunaan](https://openrouter.ai/activity)
        """)
        gr.HTML("""<img src="https://cdn.myportfolio.com/45200424-090f-478b-9be0-85ca9dee2b39/f3a8a7fb-b385-4a7a-8bee-e325c4b9cf9b_rw_600.png?h=fe0a7278654a29de048391005c6d748f" width="200">""")
    
    # Event handlers
    submit_btn.click(
        fn=chat_with_openrouter,
        inputs=[prompt, system_prompt, selected_model],
        outputs=output
    )
    
    clear_btn.click(lambda: ["", ""], outputs=[prompt, output])
    
    prompt.submit(
        fn=chat_with_openrouter,
        inputs=[prompt, system_prompt, selected_model],
        outputs=output
    )

demo.launch()