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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
"""
DeepSeek Coder Agent - HuggingFace Space
A cloud-based AI coding assistant powered by DeepSeek Coder V3
Replace local models with this cloud-hosted solution
"""

import gradio as gr
import os
import requests
import json
from typing import Optional, Dict, Any
import base64
from datetime import datetime


class DeepSeekCoderAgent:
    """DeepSeek Coder API Integration"""
    
    def __init__(self, api_key: Optional[str] = None):
        self.api_key = api_key or os.getenv("DEEPSEEK_API_KEY")
        self.api_url = "https://api.deepseek.com/v1/chat/completions"
        self.model = "deepseek-coder"
        self.history = []
        
    def chat(self, message: str, code_context: str = "", system_prompt: str = "") -> str:
        """Send message to DeepSeek Coder API"""
        
        if not self.api_key:
            return "❌ Error: DeepSeek API key not configured. Please set DEEPSEEK_API_KEY environment variable or enter your API key in settings."
        
        # Build messages
        messages = []
        
        # System prompt
        if system_prompt:
            messages.append({"role": "system", "content": system_prompt})
        else:
            messages.append({
                "role": "system",
                "content": """You are DeepSeek Coder Agent, an expert AI programming assistant.
You help with:
- Writing clean, efficient code in any language
- Debugging and fixing errors
- Explaining code and concepts
- Refactoring and optimization
- Code review and best practices
- Architecture and design patterns

Always provide clear, well-commented code examples."""
            })
        
        # Add code context if provided
        if code_context:
            messages.append({
                "role": "user",
                "content": f"Here's my current code context:\n```python\n{code_context}\n```\n\nPlease help me with this code."
            })
        
        # Add user message
        messages.append({"role": "user", "content": message})
        
        # Add conversation history
        messages.extend(self.history[-10:])  # Last 10 messages for context
        
        try:
            headers = {
                "Content-Type": "application/json",
                "Authorization": f"Bearer {self.api_key}"
            }
            
            payload = {
                "model": self.model,
                "messages": messages,
                "temperature": 0.7,
                "max_tokens": 4096,
                "stream": False
            }
            
            response = requests.post(
                self.api_url,
                headers=headers,
                json=payload,
                timeout=60
            )
            
            if response.status_code == 200:
                result = response.json()
                assistant_message = result["choices"][0]["message"]["content"]
                
                # Update history
                self.history.append({"role": "user", "content": message})
                self.history.append({"role": "assistant", "content": assistant_message})
                
                return assistant_message
            else:
                return f"❌ API Error: {response.status_code}\n{response.text}"
                
        except requests.exceptions.Timeout:
            return "⏱️ Request timed out. The model is taking longer than expected. Please try again."
        except requests.exceptions.RequestException as e:
            return f"❌ Network Error: {str(e)}"
        except Exception as e:
            return f"❌ Error: {str(e)}"
    
    def clear_history(self):
        """Clear conversation history"""
        self.history = []
    
    def get_stats(self) -> str:
        """Get agent statistics"""
        return f"""
**Session Stats:**
- Messages: {len(self.history) // 2}
- Model: {self.model}
- API Key: {'βœ…' if self.api_key else '❌'}
- Time: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}
"""


def create_code_completion(code: str, language: str, instruction: str, api_key: str) -> str:
    """Generate code completion"""
    agent = DeepSeekCoderAgent(api_key)
    
    prompt = f"""Complete or improve this {language} code based on the instruction.

Instruction: {instruction}

Current Code:
```{language}
{code}
```

Provide the complete, working code with explanations:"""
    
    return agent.chat(prompt)


def explain_code(code: str, language: str, api_key: str) -> str:
    """Explain code functionality"""
    agent = DeepSeekCoderAgent(api_key)
    
    prompt = f"""Explain this {language} code in detail:

```{language}
{code}
```

Break down:
1. What the code does
2. Key functions/methods
3. Logic flow
4. Any potential issues or improvements"""
    
    return agent.chat(prompt)


def debug_code(code: str, language: str, error_message: str, api_key: str) -> str:
    """Debug code and find issues"""
    agent = DeepSeekCoderAgent(api_key)
    
    prompt = f"""Debug this {language} code:

```{language}
{code}
```

Error Message: {error_message if error_message else "No specific error message"}

Please:
1. Identify the issue(s)
2. Explain what's wrong
3. Provide the fixed code
4. Explain the fix"""
    
    return agent.chat(prompt)


def generate_code_from_description(description: str, language: str, api_key: str) -> str:
    """Generate code from natural language description"""
    agent = DeepSeekCoderAgent(api_key)
    
    prompt = f"""Write {language} code that does the following:

{description}

Requirements:
- Clean, readable code
- Proper error handling
- Comments explaining key parts
- Best practices for {language}

Provide the complete implementation:"""
    
    return agent.chat(prompt)


def create_ui() -> gr.Blocks:
    """Create the Gradio interface"""
    
    with gr.Blocks(
        title="DeepSeek Coder Agent",
        theme=gr.themes.Soft(),
        css="""
        .gradio-container { max-width: 1400px !important; }
        .code-editor { font-family: 'Fira Code', monospace; }
        .chat-message { border-radius: 12px !important; }
        """
    ) as demo:
        
        # Header
        gr.Markdown("""
        # πŸš€ DeepSeek Coder Agent
        
        **Cloud-based AI coding assistant powered by DeepSeek Coder V3**
        
        Replace local models with this hosted solution - no GPU required!
        
        [Documentation](https://api-docs.deepseek.com/) | [Pricing](https://platform.deepseek.com/)
        """)
        
        # State
        api_key_state = gr.State("")
        
        with gr.Row():
            # Left Sidebar - Settings & Tools
            with gr.Column(scale=1, min_width=300):
                gr.Markdown("### βš™οΈ Settings")
                
                api_key_input = gr.Textbox(
                    label="DeepSeek API Key",
                    type="password",
                    placeholder="sk-...",
                    help_text="Get your API key from https://platform.deepseek.com/"
                )
                
                model_select = gr.Dropdown(
                    label="Model",
                    choices=["deepseek-coder", "deepseek-chat"],
                    value="deepseek-coder",
                    info="Select the DeepSeek model to use"
                )
                
                gr.Markdown("### πŸ› οΈ Quick Tools")
                
                tool_select = gr.Radio(
                    choices=[
                        "πŸ’¬ Chat",
                        "✨ Code Completion",
                        "πŸ“– Explain Code",
                        "πŸ› Debug Code",
                        "🎨 Generate Code",
                        "πŸ”„ Refactor Code",
                        "πŸ“ Code Review"
                    ],
                    value="πŸ’¬ Chat",
                    label="Tool"
                )
                
                language_select = gr.Dropdown(
                    label="Programming Language",
                    choices=[
                        "Python", "JavaScript", "TypeScript", "Java", "C++", "C#",
                        "Go", "Rust", "Ruby", "PHP", "Swift", "Kotlin",
                        "SQL", "HTML/CSS", "Shell", "Other"
                    ],
                    value="Python",
                    interactive=True
                )
                
                gr.Markdown("### πŸ“Š Stats")
                stats_output = gr.Markdown("**Status:** Ready")
                
                clear_btn = gr.Button("πŸ—‘οΈ Clear History", variant="secondary")
            
            # Main Content Area
            with gr.Column(scale=3):
                # Tool-specific inputs
                with gr.Group(visible=True) as chat_group:
                    chat_input = gr.ChatInterface(
                        fn=lambda msg, history: handle_chat(msg, history, api_key_state),
                        type="messages",
                        height=500,
                        placeholder="Ask me anything about coding..."
                    )
                
                with gr.Group(visible=False) as code_group:
                    code_input = gr.Code(
                        label="Code",
                        language="python",
                        lines=15,
                        placeholder="Paste your code here..."
                    )
                    
                    instruction_input = gr.Textbox(
                        label="Instruction",
                        placeholder="What would you like me to do with this code?",
                        lines=3
                    )
                    
                    error_input = gr.Textbox(
                        label="Error Message (optional)",
                        placeholder="Paste any error messages you're seeing...",
                        lines=2,
                        visible=False
                    )
                    
                    run_btn = gr.Button("▢️ Run", variant="primary", size="lg")
                    code_output = gr.Code(label="Result", language="python", lines=20)
                
                # Code generation input
                with gr.Group(visible=False) as generate_group:
                    desc_input = gr.Textbox(
                        label="Describe what you want to build",
                        placeholder="E.g., 'A function that sorts a list using quicksort and handles edge cases'",
                        lines=4
                    )
                    
                    generate_btn = gr.Button("✨ Generate Code", variant="primary", size="lg")
                    generate_output = gr.Code(label="Generated Code", language="python", lines=25)
        
        # Footer
        gr.Markdown("""
        ---
        **Powered by DeepSeek Coder V3** | Built for HuggingFace Spaces
        
        πŸ’‘ **Tip:** You can delete local models after setting up this space. All processing happens in the cloud!
        """)
        
        # Event Handlers
        def update_tool_ui(tool):
            """Update UI based on selected tool"""
            chat_vis = gr.update(visible=(tool == "πŸ’¬ Chat"))
            code_vis = gr.update(visible=(tool != "πŸ’¬ Chat" and tool != "🎨 Generate Code"))
            generate_vis = gr.update(visible=(tool == "🎨 Generate Code"))
            error_vis = gr.update(visible=(tool == "πŸ› Debug Code"))
            
            return chat_vis, code_vis, generate_vis, error_vis
        
        def handle_chat(msg, history, api_key):
            """Handle chat messages"""
            agent = DeepSeekCoderAgent(api_key)
            response = agent.chat(msg["content"])
            return {"role": "assistant", "content": response}
        
        def run_code_tool(code, instruction, error, tool, language, api_key):
            """Run the selected code tool"""
            if tool == "✨ Code Completion":
                result = create_code_completion(code, language, instruction, api_key)
            elif tool == "πŸ“– Explain Code":
                result = explain_code(code, language, api_key)
            elif tool == "πŸ› Debug Code":
                result = debug_code(code, language, error, api_key)
            elif tool == "πŸ”„ Refactor Code":
                result = create_code_completion(code, language, f"Refactor this code: {instruction}", api_key)
            elif tool == "πŸ“ Code Review":
                result = create_code_completion(code, language, f"Review this code: {instruction}", api_key)
            else:
                result = "Please select a tool"
            
            return result
        
        def generate_from_desc(desc, language, api_key):
            """Generate code from description"""
            result = generate_code_from_description(desc, language, api_key)
            return result
        
        def update_stats(api_key):
            """Update stats display"""
            agent = DeepSeekCoderAgent(api_key)
            return agent.get_stats()
        
        # Wire up events
        tool_select.change(
            fn=update_tool_ui,
            inputs=[tool_select],
            outputs=[chat_group, code_group, generate_group, error_input]
        )
        
        api_key_input.change(
            fn=lambda x: x,
            inputs=[api_key_input],
            outputs=[api_key_state]
        ).then(
            fn=update_stats,
            inputs=[api_key_input],
            outputs=[stats_output]
        )
        
        run_btn.click(
            fn=run_code_tool,
            inputs=[code_input, instruction_input, error_input, tool_select, language_select, api_key_input],
            outputs=[code_output]
        )
        
        generate_btn.click(
            fn=generate_from_desc,
            inputs=[desc_input, language_select, api_key_input],
            outputs=[generate_output]
        )
        
        clear_btn.click(
            fn=lambda: None,
            inputs=[],
            outputs=[]
        ).then(
            fn=lambda: DeepSeekCoderAgent(api_key_state.value).clear_history(),
            inputs=[],
            outputs=[]
        )
    
    return demo


# Launch the app
if __name__ == "__main__":
    demo = create_ui()
    demo.launch(
        server_name="0.0.0.0",
        server_port=7860,
        share=False,
        show_error=True
    )