helperai commited on
Commit
0d6bb64
·
verified ·
1 Parent(s): 5f83552

Create main.py

Browse files
Files changed (1) hide show
  1. main.py +103 -0
main.py ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import FastAPI, HTTPException
2
+ from pydantic import BaseModel
3
+ import torch
4
+ from transformers import AutoModelForCausalLM, AutoTokenizer
5
+ import time
6
+
7
+ # --- MODEL CONSTANTS ---
8
+ MODEL_NAME = "deepseek-ai/deepseek-coder-1.3b-instruct"
9
+ # CRITICAL: Force model to use CPU for the free tier
10
+ DEVICE = "cpu"
11
+ MAX_NEW_TOKENS = 512 # Limit output size for speed and cost control
12
+ TORCH_DTYPE = torch.float32 # Use standard float for maximum CPU compatibility
13
+
14
+ # Global variables for model and tokenizer
15
+ model = None
16
+ tokenizer = None
17
+
18
+ # --- API Data Structure ---
19
+ class CodeRequest(BaseModel):
20
+ """Defines the expected input structure from the front-end website."""
21
+ user_prompt: str # The user's request (e.g., "Fix the bug in this function")
22
+ code_context: str # The block of code the user provided
23
+
24
+ # --- FastAPI App Setup ---
25
+ # The app will run on port 7860 as defined in the Dockerfile
26
+ app = FastAPI(title="CodeFlow AI Agent Backend - DeepSeek SLM")
27
+
28
+ @app.on_event("startup")
29
+ async def startup_event():
30
+ """Load the DeepSeek SLM Model and Tokenizer ONLY ONCE when the server starts."""
31
+ global model, tokenizer
32
+ print(f"--- Starting CodeFlow AI Agent (DeepSeek 1.3B) on {DEVICE} ---")
33
+ start_time = time.time()
34
+
35
+ try:
36
+ # Load the Tokenizer
37
+ tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME, trust_remote_code=True)
38
+
39
+ # Load the Model
40
+ # Using device_map="cpu" is essential for the free tier.
41
+ model = AutoModelForCausalLM.from_pretrained(
42
+ MODEL_NAME,
43
+ torch_dtype=TORCH_DTYPE,
44
+ device_map=DEVICE,
45
+ trust_remote_code=True
46
+ )
47
+ model.eval() # Set model to evaluation mode
48
+ print(f"DeepSeek Model loaded successfully in {time.time() - start_time:.2f} seconds.")
49
+
50
+ except Exception as e:
51
+ # If the model fails to load, log the error and prevent the API from functioning
52
+ print(f"ERROR: Failed to load DeepSeek model on CPU: {e}")
53
+ # Raising an exception here will cause the Docker container to fail, which is correct
54
+ # as a non-working model should not be deployed.
55
+ raise RuntimeError(f"Model failed to load on startup: {e}")
56
+
57
+ # --- The API Endpoint ---
58
+ @app.post("/fix_code")
59
+ async def fix_code_endpoint(request: CodeRequest):
60
+ """
61
+ Accepts code context and task, processes it with DeepSeek-Coder, and returns the fix.
62
+ """
63
+ if model is None or tokenizer is None:
64
+ raise HTTPException(status_code=503, detail="AI Agent is still loading or failed to start.")
65
+
66
+ # --- CONSTRUCT AGENT PROMPT (DeepSeek Instruction Format) ---
67
+ # DeepSeek uses a specific format: ### Instruction: ... ### Response:
68
+
69
+ instruction = (
70
+ f"You are Arya's CodeBuddy, an elite Full-Stack Software Engineer. Your only job is to analyze "
71
+ f"the user's request and provide the complete, fixed, or generated code. You must ONLY output "
72
+ f"a single, complete, and corrected Markdown code block. Use a friendly and encouraging tone.\n\n"
73
+ f"TASK: {request.user_prompt}\n\n"
74
+ f"CODE_CONTEXT:\n{request.code_context}"
75
+ )
76
+
77
+ # Format the prompt correctly for the model
78
+ prompt = f"### Instruction:\n{instruction}\n\n### Response:\n"
79
+
80
+ # Tokenize and send tensors to CPU
81
+ model_inputs = tokenizer([prompt], return_tensors="pt").to(DEVICE)
82
+
83
+ try:
84
+ # --- GENERATE CODE (CPU Inference) ---
85
+ generated_ids = model.generate(
86
+ **model_inputs,
87
+ max_new_tokens=MAX_NEW_TOKENS,
88
+ do_sample=False, # Deterministic output
89
+ temperature=0.1, # Low temperature for reliable coding
90
+ )
91
+
92
+ # Decode the output
93
+ response_text = tokenizer.decode(generated_ids[0], skip_special_tokens=True)
94
+
95
+ # Post-processing: Extract ONLY the text after the '### Response:' tag.
96
+ final_code_only = response_text.split("### Response:")[1].strip()
97
+
98
+ return {"fixed_code": final_code_only}
99
+
100
+ except Exception as e:
101
+ print(f"Generation error: {e}")
102
+ # Return a generic error to the user
103
+ raise HTTPException(status_code=500, detail="The DeepSeek CodeBuddy encountered a processing error.")