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 
a8ae8ed
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cbca561
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
from fastapi import FastAPI
from fastapi.responses import StreamingResponse
from pydantic import BaseModel
from transformers import (
    AutoTokenizer,
    AutoModelForCausalLM,
    TextIteratorStreamer
)
from supabase import create_client
import torch
import uvicorn
import threading
import json
import os

# =========================
# CONFIG
# =========================

SUPABASE_URL = os.getenv("SUPABASE_URL")
SUPABASE_KEY = os.getenv("SUPABASE_KEY")

supabase = create_client(
    SUPABASE_URL,
    SUPABASE_KEY
)

# =========================
# APP
# =========================

app = FastAPI()

stop_flags = {}

# =========================
# MODEL
# =========================

MODEL_ID = "Qwen/Qwen2.5-Coder-1.5B-Instruct"

print("🚀 Loading Fast Coder Model...")

device = torch.device(
    "cuda" if torch.cuda.is_available() else "cpu"
)

torch.backends.cuda.matmul.allow_tf32 = True
torch.backends.cudnn.allow_tf32 = True

# =========================
# TOKENIZER
# =========================

tokenizer = AutoTokenizer.from_pretrained(
    MODEL_ID,
    trust_remote_code=True
)

# =========================
# MODEL
# =========================

model = AutoModelForCausalLM.from_pretrained(
    MODEL_ID,
    trust_remote_code=True,
    torch_dtype=torch.float16 if device.type == "cuda" else torch.float32
)

model = model.to(device)
model.eval()

print(f"✅ Loaded on {device}")

# =========================
# REQUEST
# =========================

class ChatRequest(BaseModel):
    user_id: str
    conversation_id: str
    message: str
    temperature: float = 0.1
    branch: bool = False
    parent_id: str | None = None

# =========================
# SYSTEM PROMPT
# =========================

SYSTEM_PROMPT = """
You are a strict expert programming assistant.

CRITICAL RULES:
- Answer ONLY the user's latest request
- NEVER continue conversations
- NEVER generate extra examples unless asked
- NEVER explain unnecessarily
- NEVER repeat code
- NEVER simulate dialogue
- ALWAYS close markdown code blocks properly
- ALWAYS return complete executable code
- Stop immediately after final answer

CODE RULES:
- Use proper markdown
- Use ```language
- Keep formatting clean
- No duplicate code
- No unfinished code
"""

# =========================
# STOP WORDS
# =========================

STOP_WORDS = [
    "<|im_end|>",
    "<|endoftext|>",
    "<|eot_id|>",
    "User:",
    "Assistant:",
    "Human:"
]

# =========================
# CLEAN OUTPUT
# =========================

def clean_output(text):

    for w in STOP_WORDS:

        if w in text:
            text = text.split(w)[0]

    return text.strip()

# =========================
# DB FUNCTIONS
# =========================

def get_messages(cid):

    res = supabase.table("messages") \
        .select("role,content") \
        .eq("conversation_id", cid) \
        .order("created_at") \
        .execute()

    return res.data or []

def save_message(
    cid,
    role,
    content,
    parent_id=None,
    branch_id=None
):

    supabase.table("messages").insert({
        "conversation_id": cid,
        "role": role,
        "content": content,
        "parent_id": parent_id,
        "branch_id": branch_id
    }).execute()

def get_next_branch(parent_id):

    res = supabase.table("messages") \
        .select("branch_id") \
        .eq("parent_id", parent_id) \
        .execute()

    existing = [
        m["branch_id"]
        for m in res.data
        if m.get("branch_id")
    ]

    return max(existing, default=0) + 1

# =========================
# BUILD INPUTS
# =========================

def build_inputs(message, cid):

    # =========================
    # FETCH HISTORY
    # =========================

    history = get_messages(cid)

    # keep only last 2
    history = history[-2:]

    messages = [
        {
            "role": "system",
            "content": SYSTEM_PROMPT
        }
    ]

    # =========================
    # ADD MEMORY
    # =========================

    for msg in history:

        messages.append({
            "role": msg["role"],
            "content": msg["content"]
        })

    # =========================
    # CURRENT USER MESSAGE
    # =========================

    messages.append({
        "role": "user",
        "content": message
    })

    text = tokenizer.apply_chat_template(
        messages,
        tokenize=False,
        add_generation_prompt=True
    )

    return tokenizer(
        text,
        return_tensors="pt"
    ).to(device)

# =========================
# STOP ENDPOINT
# =========================

@app.post("/v1/stop")
def stop(data: dict):

    stop_flags[data.get("conversation_id")] = True

    return {
        "status": "stopped"
    }

# =========================
# NORMAL CHAT
# =========================

@app.post("/v1/chat")
def chat(req: ChatRequest):

    inputs = build_inputs(
        req.message,
        req.conversation_id
    )

    with torch.inference_mode():

        output = model.generate(
            **inputs,
            max_new_tokens=512,
            do_sample=False,
            temperature=req.temperature,
            top_p=1.0,
            repetition_penalty=1.08,
            pad_token_id=tokenizer.eos_token_id,
            eos_token_id=tokenizer.eos_token_id
        )

    result = tokenizer.decode(
        output[0][inputs.input_ids.shape[1]:],
        skip_special_tokens=True
    )

    result = clean_output(result)

    def save_async():

        if not req.branch:

            save_message(
                req.conversation_id,
                "user",
                req.message
            )

            save_message(
                req.conversation_id,
                "assistant",
                result
            )

        else:

            branch_id = get_next_branch(
                req.parent_id
            )

            save_message(
                req.conversation_id,
                "assistant",
                result,
                parent_id=req.parent_id,
                branch_id=branch_id
            )

    threading.Thread(
        target=save_async
    ).start()

    return {
        "response": result
    }

# =========================
# STREAM CHAT
# =========================

@app.post("/v1/chat/stream")
def stream_chat(req: ChatRequest):

    inputs = build_inputs(
        req.message,
        req.conversation_id
    )

    streamer = TextIteratorStreamer(
        tokenizer,
        skip_prompt=True,
        skip_special_tokens=True
    )

    generation_kwargs = dict(
        **inputs,
        streamer=streamer,
        max_new_tokens=512,
        do_sample=False,
        temperature=req.temperature,
        top_p=1.0,
        repetition_penalty=1.08,
        pad_token_id=tokenizer.eos_token_id,
        eos_token_id=tokenizer.eos_token_id
    )

    thread = threading.Thread(
        target=model.generate,
        kwargs=generation_kwargs
    )

    thread.start()

    def generate():

        full_text = ""

        for token in streamer:

            if stop_flags.get(req.conversation_id):

                stop_flags[req.conversation_id] = False
                break

            if not token:
                continue

            stop_hit = False

            for sw in STOP_WORDS:

                if sw in token:
                    token = token.split(sw)[0]
                    stop_hit = True
                    break

            if token:

                full_text += token

                # stop after completed markdown block
                if full_text.count("```") >= 2:

                    yield f"data: {json.dumps({'choices':[{'delta':{'content': token}}]})}\n\n"

                    break

                yield f"data: {json.dumps({'choices':[{'delta':{'content': token}}]})}\n\n"

            if stop_hit:
                break

        full_text = clean_output(full_text)

        yield "event: done\ndata: {}\n\n"
        yield "data: [DONE]\n\n"

        def save_async():

            if not full_text:
                return

            if not req.branch:

                save_message(
                    req.conversation_id,
                    "user",
                    req.message
                )

                save_message(
                    req.conversation_id,
                    "assistant",
                    full_text
                )

            else:

                branch_id = get_next_branch(
                    req.parent_id
                )

                save_message(
                    req.conversation_id,
                    "assistant",
                    full_text,
                    parent_id=req.parent_id,
                    branch_id=branch_id
                )

        threading.Thread(
            target=save_async
        ).start()

    return StreamingResponse(
        generate(),
        media_type="text/event-stream"
    )

# =========================
# FEEDBACK
# =========================

@app.post("/v1/feedback")
def feedback(data: dict):

    try:

        supabase.table("messages").update({
            "feedback": data.get("feedback")
        }).eq(
            "id",
            data.get("message_id")
        ).execute()

        return {
            "status": "saved"
        }

    except Exception as e:

        return {
            "error": str(e)
        }

# =========================
# HEALTH
# =========================

@app.get("/")
def root():

    return {
        "status": "Fast Coder Running 🚀"
    }

# =========================
# RUN
# =========================

if __name__ == "__main__":

    uvicorn.run(
        "app:app",
        host="0.0.0.0",
        port=7860
    )