File size: 10,433 Bytes
f0c9bc7
 
 
 
 
 
 
 
 
 
 
5fa25d7
 
f0c9bc7
 
 
 
 
5fedbc6
 
 
f0c9bc7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5fa25d7
f0c9bc7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5fa25d7
 
f0c9bc7
 
 
 
 
 
 
5fa25d7
f0c9bc7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
346da48
f0c9bc7
346da48
 
 
f0c9bc7
346da48
5fa25d7
f0c9bc7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5fa25d7
f0c9bc7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
FastAPI server providing OpenAI-compatible endpoints for code generation.
Designed to work with MCP servers and provide unlimited tokens with minimal rate limiting.
"""
import os
import time
import uuid
from typing import Optional, List, Dict, Any
from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel, Field
from huggingface_hub import hf_hub_download
from llama_cpp import Llama
import uvicorn

# ============================================================================
# CONFIGURATION
# ============================================================================
MODEL_REPO = "TheBloke/deepseek-coder-1.3b-instruct-GGUF"
MODEL_FILE = "deepseek-coder-1.3b-instruct.Q4_K_M.gguf"
MODEL_NAME = "deepseek-coder-1.3b-instruct"

# Context and generation settings for "unlimited" tokens
MAX_CONTEXT = 4096      # Larger context window
MAX_TOKENS = 4096       # Allow very long responses
DEFAULT_TEMP = 0.7
DEFAULT_TOP_P = 0.95

# ============================================================================
# PYDANTIC MODELS (OpenAI-compatible)
# ============================================================================
class Message(BaseModel):
    role: str
    content: str

class ChatCompletionRequest(BaseModel):
    model: str = MODEL_NAME
    messages: List[Message]
    temperature: Optional[float] = DEFAULT_TEMP
    top_p: Optional[float] = DEFAULT_TOP_P
    max_tokens: Optional[int] = MAX_TOKENS
    stream: Optional[bool] = False
    stop: Optional[List[str]] = None

class CompletionRequest(BaseModel):
    model: str = MODEL_NAME
    prompt: str
    temperature: Optional[float] = DEFAULT_TEMP
    top_p: Optional[float] = DEFAULT_TOP_P
    max_tokens: Optional[int] = MAX_TOKENS
    stop: Optional[List[str]] = None

class Usage(BaseModel):
    prompt_tokens: int
    completion_tokens: int
    total_tokens: int

class ChatCompletionChoice(BaseModel):
    index: int
    message: Message
    finish_reason: str

class ChatCompletionResponse(BaseModel):
    id: str
    object: str = "chat.completion"
    created: int
    model: str
    choices: List[ChatCompletionChoice]
    usage: Usage

class CompletionChoice(BaseModel):
    index: int
    text: str
    finish_reason: str

class CompletionResponse(BaseModel):
    id: str
    object: str = "text_completion"
    created: int
    model: str
    choices: List[CompletionChoice]
    usage: Usage

# ============================================================================
# FASTAPI APP
# ============================================================================
app = FastAPI(
    title="Code LLM API",
    description="OpenAI-compatible API for code generation with minimal rate limiting",
    version="1.0.0"
)

# Enable CORS for MCP server access
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# Global model instance
llm: Optional[Llama] = None

# ============================================================================
# MODEL LOADING
# ============================================================================
@app.on_event("startup")
async def load_model():
    """Load the LLM model on startup."""
    global llm
    print(f"Downloading model {MODEL_REPO}/{MODEL_FILE}...")
    model_path = hf_hub_download(repo_id=MODEL_REPO, filename=MODEL_FILE)
    print(f"Model downloaded to: {model_path}")

    print("Loading model into memory...")
    llm = Llama(                                                                                                       
        model_path=model_path,
        n_ctx=MAX_CONTEXT,                                                                                             
        n_threads=8,           # Changed from 4 to 8
        n_batch=1024,          # Changed from 512 to 1024
        verbose=False,
        n_gpu_layers=0
    )
    print("Model loaded successfully!")

# ============================================================================
# HELPER FUNCTIONS
# ============================================================================
def messages_to_prompt(messages: List[Message]) -> str:
    """Convert OpenAI-style messages to a prompt for CodeLlama."""
    prompt_parts = []

    for msg in messages:
        if msg.role == "system":
            prompt_parts.append(f"### System: {msg.content}")
        elif msg.role == "user":
            prompt_parts.append(f"### Instruction: {msg.content}")
        elif msg.role == "assistant":
            prompt_parts.append(f"### Response: {msg.content}")

    prompt_parts.append("### Response:")
    return "\n".join(prompt_parts)

def estimate_tokens(text: str) -> int:
    """Rough token estimation (1 token ≈ 4 chars)."""
    return len(text) // 4

# ============================================================================
# API ENDPOINTS
# ============================================================================
@app.get("/")
async def root():
    """Health check endpoint."""
    return {
        "status": "online",
        "model": MODEL_NAME,
        "max_context": MAX_CONTEXT,
        "max_tokens": MAX_TOKENS,
        "endpoints": {
            "chat": "/v1/chat/completions",
            "completion": "/v1/completions",
            "models": "/v1/models"
        }
    }

@app.get("/health")
async def health():
    """Health check for monitoring."""
    return {
        "status": "healthy" if llm is not None else "loading",
        "model_loaded": llm is not None
    }

@app.get("/v1/models")
async def list_models():
    """List available models (OpenAI-compatible)."""
    return {
        "object": "list",
        "data": [
            {
                "id": MODEL_NAME,
                "object": "model",
                "created": int(time.time()),
                "owned_by": "huggingface",
                "permission": [],
                "root": MODEL_NAME,
                "parent": None
            }
        ]
    }

@app.post("/v1/chat/completions", response_model=ChatCompletionResponse)
async def chat_completions(request: ChatCompletionRequest):
    """
    OpenAI-compatible chat completions endpoint.
    No rate limiting - designed for unlimited use.
    """
    if llm is None:
        raise HTTPException(status_code=503, detail="Model still loading")

    if request.stream:
        raise HTTPException(status_code=501, detail="Streaming not yet implemented")

    # Convert messages to prompt
    prompt = messages_to_prompt(request.messages)

    # Generate response
    try:
        output = llm(
            prompt,
            max_tokens=request.max_tokens or MAX_TOKENS,
            temperature=request.temperature or DEFAULT_TEMP,
            top_p=request.top_p or DEFAULT_TOP_P,
            stop=request.stop or ["###", "\n\n\n"],
            echo=False
        )

        generated_text = output['choices'][0]['text'].strip()

        # Estimate token usage
        prompt_tokens = estimate_tokens(prompt)
        completion_tokens = estimate_tokens(generated_text)

        return ChatCompletionResponse(
            id=f"chatcmpl-{uuid.uuid4().hex[:8]}",
            created=int(time.time()),
            model=request.model,
            choices=[
                ChatCompletionChoice(
                    index=0,
                    message=Message(role="assistant", content=generated_text),
                    finish_reason="stop"
                )
            ],
            usage=Usage(
                prompt_tokens=prompt_tokens,
                completion_tokens=completion_tokens,
                total_tokens=prompt_tokens + completion_tokens
            )
        )
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Generation failed: {str(e)}")

@app.post("/v1/completions", response_model=CompletionResponse)
async def completions(request: CompletionRequest):
    """
    OpenAI-compatible completions endpoint.
    No rate limiting - designed for unlimited use.
    """
    if llm is None:
        raise HTTPException(status_code=503, detail="Model still loading")

    try:
        output = llm(
            request.prompt,
            max_tokens=request.max_tokens or MAX_TOKENS,
            temperature=request.temperature or DEFAULT_TEMP,
            top_p=request.top_p or DEFAULT_TOP_P,
            stop=request.stop or [],
            echo=False
        )

        generated_text = output['choices'][0]['text'].strip()

        # Estimate token usage
        prompt_tokens = estimate_tokens(request.prompt)
        completion_tokens = estimate_tokens(generated_text)

        return CompletionResponse(
            id=f"cmpl-{uuid.uuid4().hex[:8]}",
            created=int(time.time()),
            model=request.model,
            choices=[
                CompletionChoice(
                    index=0,
                    text=generated_text,
                    finish_reason="stop"
                )
            ],
            usage=Usage(
                prompt_tokens=prompt_tokens,
                completion_tokens=completion_tokens,
                total_tokens=prompt_tokens + completion_tokens
            )
        )
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Generation failed: {str(e)}")

# ============================================================================
# SIMPLE ENDPOINTS (for easier testing)
# ============================================================================
@app.post("/generate")
async def generate(prompt: str, max_tokens: int = 512):
    """Simple generation endpoint for quick testing."""
    if llm is None:
        raise HTTPException(status_code=503, detail="Model still loading")

    try:
        output = llm(prompt, max_tokens=max_tokens, temperature=0.7)
        return {
            "prompt": prompt,
            "response": output['choices'][0]['text'].strip(),
            "model": MODEL_NAME
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

# ============================================================================
# MAIN
# ============================================================================
if __name__ == "__main__":
    uvicorn.run(
        app,
        host="0.0.0.0",
        port=int(os.getenv("PORT", "7860")),  # HF Spaces uses port 7860
        log_level="info"
    )