krisshattanicole's picture
Upload app.py with huggingface_hub
01d7cb0 verified
"""
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
)