File size: 8,401 Bytes
32829b9
 
 
 
 
 
 
86e793d
0a73fa9
 
 
86e793d
 
 
 
 
32829b9
 
86e793d
32829b9
 
 
 
 
 
 
86e793d
 
 
 
0774869
 
fe8085d
58615c9
86e793d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
58615c9
86e793d
 
 
32829b9
 
 
86e793d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
58615c9
32829b9
 
 
58615c9
86e793d
 
 
 
 
fc356c7
58615c9
86e793d
32829b9
 
0a73fa9
86e793d
 
 
 
 
 
 
 
 
 
32829b9
86e793d
58615c9
86e793d
 
58615c9
86e793d
 
 
58615c9
86e793d
 
 
 
58615c9
86e793d
 
 
58615c9
86e793d
 
 
58615c9
86e793d
 
58615c9
86e793d
 
58615c9
86e793d
 
 
32829b9
86e793d
32829b9
86e793d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
58615c9
86e793d
 
32829b9
86e793d
58615c9
86e793d
58615c9
 
86e793d
 
 
fe8085d
58615c9
32829b9
 
86e793d
 
32829b9
86e793d
 
 
 
fe8085d
 
 
86e793d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fe8085d
86e793d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fe8085d
 
86e793d
 
 
 
 
 
 
fe8085d
32829b9
58615c9
86e793d
 
 
 
 
32829b9
 
0a73fa9
86e793d
 
 
 
 
0a73fa9
32829b9
58615c9
32829b9
 
86e793d
 
 
 
32829b9
86e793d
 
 
58615c9
32829b9
86e793d
 
 
 
 
 
 
 
 
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
from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import StreamingResponse
from pydantic import BaseModel
from llama_cpp import Llama
from huggingface_hub import hf_hub_download
from typing import List, Optional
import asyncio
import os
import json
import uvicorn
import gc

# =============================================================================
# FASTAPI
# =============================================================================

app = FastAPI()

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_methods=["*"],
    allow_headers=["*"],
)

# =============================================================================
# MODEL CONFIG
# =============================================================================

MODEL_REPO = "unsloth/Qwen3-4B-GGUF"
MODEL_FILE = "Qwen3-4B-Q4_K_M.gguf"

MAX_HISTORY = 6
MAX_CTX = 8192
MAX_TOKENS = 4096

# Giữ nguyên tham số theo yêu cầu
THREADS = 2
N_BATCH = 512
N_UBATCH = 512

DEFAULT_SYSTEM = (
    "Bạn là trợ lý AI, trả lời bằng tiếng Việt ngắn gọn."
)

STOP_TOKENS = [
    "<|im_end|>",
    "<|endoftext|>",
]

# =============================================================================
# GLOBALS
# =============================================================================

llm: Optional[Llama] = None

# CPU inference -> serialize request để tránh lag/token collapse
inference_lock = asyncio.Semaphore(1)

# =============================================================================
# REQUEST MODELS
# =============================================================================


class Message(BaseModel):
    role: str
    content: str


class ChatRequest(BaseModel):
    prompt: str
    history: List[Message] = []
    system_prompt: Optional[str] = None

    max_tokens: int = MAX_TOKENS
    temperature: float = 0.7
    top_p: float = 0.9


# =============================================================================
# HELPERS
# =============================================================================


def cleanup_text(text: str) -> str:
    return text.strip().replace("\x00", "")


def build_messages(req: ChatRequest) -> list:
    system_prompt = cleanup_text(
        req.system_prompt or DEFAULT_SYSTEM
    )

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

    recent = req.history[-(MAX_HISTORY * 2):]

    last_role = "system"

    for msg in recent:
        role = msg.role.strip().lower()
        content = cleanup_text(msg.content)

        if (
            role not in ("user", "assistant")
            or not content
        ):
            continue

        # tránh duplicate role liên tục
        if role == last_role:
            continue

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

        last_role = role

    prompt = cleanup_text(req.prompt)

    if not prompt:
        raise HTTPException(400, "Prompt trống")

    if len(prompt) > 8000:
        raise HTTPException(400, "Prompt quá dài")

    if messages[-1]["role"] == "user":
        messages.pop()

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

    return messages


def sse(data):
    return f"data: {json.dumps(data, ensure_ascii=False)}\n\n"


# =============================================================================
# STARTUP
# =============================================================================


@app.on_event("startup")
async def startup_event():
    global llm

    # Xóa file corrupt
    if (
        os.path.exists(MODEL_FILE)
        and os.path.getsize(MODEL_FILE) < 1_000_000
    ):
        os.remove(MODEL_FILE)

    # Download nếu chưa có
    if not os.path.exists(MODEL_FILE):
        print(f"Downloading {MODEL_FILE}...")

        hf_hub_download(
            repo_id=MODEL_REPO,
            filename=MODEL_FILE,
            local_dir=".",
        )

        print("Download complete!")

    print("Loading model...")

    llm = Llama(
        model_path=MODEL_FILE,

        # Context
        n_ctx=MAX_CTX,

        # Giữ nguyên batch
        n_batch=N_BATCH,
        n_ubatch=N_UBATCH,

        # CPU
        n_threads=THREADS,
        n_threads_batch=THREADS,
        n_gpu_layers=0,

        # RAM
        use_mmap=False,
        use_mlock=True,

        # KV cache
        cache_type_k="q4_0",
        cache_type_v="q4_0",

        # Prefix detection
        last_n_tokens_size=64,

        # Performance
        flash_attn=True,

        # Cleaner logs
        verbose=False,
    )

    print("Warmup model...")

    try:
        _ = llm.create_chat_completion(
            messages=[
                {
                    "role": "system",
                    "content": DEFAULT_SYSTEM,
                },
                {
                    "role": "user",
                    "content": "hi",
                },
            ],
            max_tokens=1,
            stream=False,
        )

    except Exception as e:
        print(f"Warmup failed: {e}")

    gc.collect()

    print("Model ready!")


# =============================================================================
# CHAT
# =============================================================================


@app.post("/chat")
async def chat(req: ChatRequest):
    global llm

    if llm is None:
        raise HTTPException(
            503,
            "Model chưa sẵn sàng",
        )

    messages = build_messages(req)

    # Clamp để user không spam 999999
    max_tokens = min(
        max(1, req.max_tokens),
        MAX_TOKENS,
    )

    temperature = min(
        max(0.0, req.temperature),
        2.0,
    )

    top_p = min(
        max(0.1, req.top_p),
        1.0,
    )

    async def event_stream():
        full = ""

        async with inference_lock:
            try:
                stream = llm.create_chat_completion(
                    messages=messages,

                    max_tokens=max_tokens,

                    temperature=temperature,
                    top_p=top_p,

                    stop=STOP_TOKENS,

                    stream=True,
                )

                for chunk in stream:
                    try:
                        delta = (
                            chunk["choices"][0]
                            .get("delta", {})
                            .get("content", "")
                        )

                        if not delta:
                            continue

                        full += delta

                        yield sse(
                            {
                                "delta": delta,
                            }
                        )

                    except Exception:
                        continue

            except Exception as e:
                yield sse(
                    {
                        "error": str(e),
                    }
                )

            finally:
                print(
                    f"[DONE] "
                    f"{len(full)} chars"
                )

                yield "data: [DONE]\n\n"

                gc.collect()

    return StreamingResponse(
        event_stream(),
        media_type="text/event-stream",
        headers={
            "Cache-Control": "no-cache",
            "Connection": "keep-alive",
            "X-Accel-Buffering": "no",
        },
    )


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


@app.get("/")
async def root():
    return {
        "status": "ok" if llm else "loading",
        "model": MODEL_FILE,
        "ctx": MAX_CTX,
        "batch": N_BATCH,
        "threads": THREADS,
    }


@app.get("/health")
async def health():
    return {
        "healthy": llm is not None,
    }


# =============================================================================
# MAIN
# =============================================================================

if __name__ == "__main__":
    uvicorn.run(
        app,
        host="0.0.0.0",
        port=7860,

        # production-ish
        access_log=False,
        server_header=False,
    )