File size: 12,182 Bytes
5999980
6953393
 
5999980
6953393
 
 
5999980
6953393
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5999980
6953393
 
 
5999980
6953393
5999980
 
6953393
 
 
 
 
5999980
6953393
 
 
 
5999980
6953393
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5999980
6953393
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5999980
6953393
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5999980
 
6953393
 
 
5999980
6953393
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5999980
 
 
 
6953393
 
5999980
6953393
5999980
6953393
 
 
5999980
6953393
5999980
 
6953393
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5999980
6953393
5999980
 
 
 
 
 
6953393
 
 
 
5999980
 
 
 
 
6953393
 
 
 
 
 
 
5999980
6953393
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5999980
6953393
 
 
5999980
6953393
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5999980
6953393
 
 
 
 
 
 
 
 
 
 
 
 
5999980
 
 
 
6953393
5999980
 
 
 
 
6953393
5999980
 
 
6953393
5999980
6953393
 
 
 
 
5999980
 
 
 
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
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
import gradio as gr
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline
import time
from typing import Dict, List, Tuple
from code_shower import CodeShower
from file_manager import FileManager

class DualModeAssistant:
    def __init__(self):
        print("πŸ”„ Loading Llama 3.2 (General purpose)...")
        self.llama_model_id = "meta-llama/Llama-3.2-1B-Instruct"
        self.llama_pipe = pipeline(
            "text-generation",
            model=self.llama_model_id,
            torch_dtype=torch.bfloat16,
            device_map="auto",
            token=True  # Uses HF_TOKEN from env if available
        )
        
        print("πŸ’» Loading Maincoder (Code specialist)...")
        self.codex_model_id = "maincode/maincoder-1b"
        self.codex_pipe = pipeline(
            "text-generation",
            model=self.codex_model_id,
            torch_dtype=torch.bfloat16,
            device_map="auto"
        )
        
        self.current_mode = "codex"
        self.file_manager = FileManager()
        
    def generate_with_thinking(self, prompt: str, mode: str, history: List = None) -> Dict:
        """Generate with thinking process"""
        
        self.current_mode = mode
        
        # Choose model
        if mode == "codex":
            pipe = self.codex_pipe
            system_prompt = """You are Maincoder, a specialized coding assistant. 
When asked to write code, always output complete files with their filenames as markdown code blocks.
Example format:
```python app.py
print("Hello")
html
<h1>Hello</h1>
```"""
        else:
            pipe = self.llama_pipe
            system_prompt = "You are a helpful general assistant. Answer questions thoroughly."
        
        # Build messages
        messages = [
            {"role": "system", "content": system_prompt},
            {"role": "user", "content": prompt}
        ]
        
        # Add conversation history if provided
        if history:
            for h in history[-4:]:  # Last 4 exchanges
                if isinstance(h, dict):
                    messages.append(h)
        
        # Generate thinking (using system prompt to encourage reasoning)
        full_response = pipe(
            messages,
            max_new_tokens=1000,
            temperature=0.7,
            do_sample=True,
            top_p=0.95
        )[0]['generated_text']
        
        # Extract the assistant's response
        if isinstance(full_response, list):
            assistant_msg = full_response[-1].get('content', '')
        else:
            # Parse the full text
            assistant_msg = full_response
        
        # Detect and extract code blocks for file tree
        files = self.file_manager.extract_files_from_code(assistant_msg)
        
        return {
            "response": assistant_msg,
            "model_used": "Codex (Coding Specialist)" if mode == "codex" else "Llama (General)",
            "files": files
        }

# Initialize components
assistant = DualModeAssistant()
code_shower = CodeShower()

# Custom CSS
custom_css = """
<style>
    /* Main layout */
    .main-container {
        display: flex;
        gap: 20px;
        height: 100vh;
    }
    
    .chat-panel {
        flex: 1;
        min-width: 400px;
    }
    
    .code-panel {
        width: 450px;
        border-left: 1px solid #ddd;
        padding-left: 15px;
        overflow-y: auto;
    }
    
    /* File tree styling */
    .file-tree {
        max-height: 300px;
        overflow-y: auto;
        border: 1px solid #e0e0e0;
        border-radius: 8px;
        background: #fafafa;
    }
    
    .file-item {
        display: flex;
        align-items: center;
        padding: 8px 12px;
        border-bottom: 1px solid #eee;
        cursor: pointer;
        transition: background 0.2s;
    }
    
    .file-item:hover {
        background: #f0f0f0;
    }
    
    .file-item.active {
        background: #e3f2fd;
        border-left: 3px solid #2196f3;
    }
    
    .file-logo {
        font-size: 1.2em;
        margin-right: 10px;
    }
    
    .file-name {
        flex: 1;
        font-family: monospace;
        font-size: 0.9em;
    }
    
    .file-badge {
        font-size: 0.7em;
        padding: 2px 6px;
        border-radius: 10px;
        background: #e0e0e0;
        margin-left: 8px;
    }
    
    .file-delete {
        background: none;
        border: none;
        cursor: pointer;
        opacity: 0.5;
        margin-left: 8px;
    }
    
    .file-delete:hover {
        opacity: 1;
    }
    
    .file-tree-empty {
        padding: 20px;
        text-align: center;
        color: #999;
    }
    
    /* Preview area */
    .preview-container {
        border: 1px solid #ddd;
        border-radius: 8px;
        overflow: hidden;
        background: white;
    }
    
    .preview-placeholder, .preview-error {
        padding: 40px;
        text-align: center;
        color: #999;
        background: #f9f9f9;
        border-radius: 8px;
    }
    
    /* Code viewer */
    .code-viewer {
        background: #1e1e1e;
        border-radius: 8px;
        overflow: hidden;
    }
    
    .code-header {
        display: flex;
        justify-content: space-between;
        padding: 8px 12px;
        background: #2d2d2d;
        color: white;
        border-bottom: 1px solid #444;
    }
    
    .code-block {
        margin: 0;
        padding: 15px;
        overflow-x: auto;
        font-family: 'Courier New', monospace;
        font-size: 13px;
        line-height: 1.4;
    }
    
    .copy-btn {
        background: #007bff;
        border: none;
        color: white;
        padding: 4px 12px;
        border-radius: 4px;
        cursor: pointer;
    }
    
    .copy-btn:hover {
        background: #0056b3;
    }
    
    /* Thinking mode bubble */
    .thinking-bubble {
        background: #f0f4ff;
        border-left: 4px solid #667eea;
        padding: 10px 15px;
        margin: 10px 0;
        border-radius: 8px;
        font-style: italic;
        color: #555;
    }
    
    /* Chat messages */
    .message {
        margin-bottom: 15px;
    }
    
    .user-message {
        background: #e3f2fd;
        padding: 10px;
        border-radius: 10px;
        margin-left: 20%;
    }
    
    .assistant-message {
        background: #f5f5f5;
        padding: 10px;
        border-radius: 10px;
        margin-right: 20%;
    }
    
    /* Responsive */
    @media (max-width: 800px) {
        .code-panel {
            display: none;
        }
        .chat-panel {
            min-width: 100%;
        }
    }
</style>
"""

# Create the Gradio interface
with gr.Blocks(css=custom_css, title="Llama Codex - Dual Mode Assistant", theme=gr.themes.Soft()) as demo:
    gr.Markdown("""
    # πŸ€– Llama Codex - Dual Mode AI Coding Assistant
    
    **Switch between two specialized AI modes:**
    - 🧠 **Llama Mode**: General conversations, explanations, Q&A
    - πŸ’» **Codex Mode**: Specialized coding with file extraction and previews
    
    > πŸ’‘ Inspired by DeepSeek-R1 - both modes show their reasoning process before responding!
    """)
    
    with gr.Row(elem_classes="main-container"):
        # Left panel: Chat
        with gr.Column(elem_classes="chat-panel", scale=2):
            with gr.Row():
                mode_selector = gr.Radio(
                    choices=["πŸ’» Codex Mode (Coding Specialist)", "🧠 Llama Mode (General)"],
                    label="Select AI Mode",
                    value="πŸ’» Codex Mode (Coding Specialist)",
                    interactive=True
                )
            
            with gr.Row():
                thinking_toggle = gr.Checkbox(
                    label="🧠 Show Thinking Process",
                    value=True,
                    info="Shows the AI's reasoning before the final answer"
                )
            
            chatbot = gr.Chatbot(
                label="Assistant",
                height=500,
                bubble_full_width=False
            )
            
            with gr.Row():
                msg = gr.Textbox(
                    label="Your message",
                    placeholder="Ask me to write code, explain concepts, or help debug...",
                    scale=4,
                    lines=3
                )
                send_btn = gr.Button("Send", variant="primary", scale=1)
            
            with gr.Row():
                clear_btn = gr.Button("Clear Chat")
                gr.Markdown("""
                **Example prompts:** 
                - "Write a Python function to calculate fibonacci"
                - "Create an HTML game of Snake"
                - "Explain how recursion works"
                - "Debug this: `for i in range(10) print(i)`"
                """)
        
        # Right panel: Code Shower
        with gr.Column(elem_classes="code-panel", scale=1):
            code_shower_ui = code_shower.create_ui()
    
    # Footer with attribution
    gr.Markdown("""
    ---
    <footer style="text-align: center;">
    <b>Built with Llama</b> β€’ Llama 3.2 1B + Maincoder 1B β€’ <a href="https://llama.meta.com/" target="_blank">Meta Llama 3.2</a>
    </footer>
    """)
    
    # State for conversation history
    conversation_history = gr.State([])
    
    # Helper functions
    def get_model_mode(radio_value: str) -> str:
        return "codex" if "Codex" in radio_value else "llama"
    
    def respond(message, history, mode_radio, show_thinking):
        if not message.strip():
            yield history + [("", "Please enter a message.")], ""
            return
        
        # Show thinking indicator
        thinking_msg = "πŸ€” Thinking" + "." * 3
        yield history + [("", thinking_msg)], ""
        
        # Get mode
        mode = get_model_mode(mode_radio)
        
        # Generate response
        result = assistant.generate_with_thinking(message, mode, history)
        
        # Format response
        if show_thinking:
            # Extract thinking from response (simple heuristic)
            response_parts = result["response"].split("\n\n")
            thinking_text = "No explicit thinking shown"
            
            # Simple thinking extraction - you can enhance this
            if "think" in result["response"].lower() or "step" in result["response"].lower():
                thinking_text = result["response"][:300] + "..."
            
            formatted = f"""<div class="thinking-bubble">
πŸ’­ **Thinking process ({result['model_used']}):**
{thinking_text}
</div>

✨ **Response:**
{result["response"]}"""
        else:
            formatted = result["response"]
        
        # Update code shower with extracted files
        if result.get("files") and code_shower:
            # Update file tree
            code_shower.current_files = result["files"]
            file_tree_html = code_shower.update_files_display()
            
            # Update code_shower_ui components
            if result["files"]:
                first_file = list(result["files"].keys())[0]
                preview, code_view, code_content = code_shower.display_file(first_file)
                # Note: In full implementation, update the UI components here
                # For this example, we'll just update the file tree
        
        # Update chat
        new_history = history + [(message, formatted)]
        yield new_history, ""
    
    def clear_chat():
        return [], ""
    
    # Event handlers
    send_btn.click(
        respond,
        [msg, chatbot, mode_selector, thinking_toggle],
        [chatbot, msg]
    )
    
    msg.submit(
        respond,
        [msg, chatbot, mode_selector, thinking_toggle],
        [chatbot, msg]
    )
    
    clear_btn.click(clear_chat, None, [chatbot, msg])
    
    # Code shower event handlers
    code_shower_ui["add_file_btn"].click(
        code_shower.add_new_file,
        [code_shower_ui["new_lang"], code_shower_ui["new_filename"]],
        [code_shower_ui["file_tree"], code_shower_ui["preview_area"], code_shower_ui["code_area"], msg]
    )

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