Nafiul Huda commited on
Update app.py
Browse files
app.py
CHANGED
|
@@ -33,104 +33,97 @@ model = AutoModelForCausalLM.from_pretrained(
|
|
| 33 |
low_cpu_mem_usage=True,
|
| 34 |
)
|
| 35 |
model.eval()
|
| 36 |
-
print("Model loaded.")
|
| 37 |
|
| 38 |
-
MAX_NEW_TOKENS =
|
| 39 |
-
MAX_CONTEXT =
|
| 40 |
|
| 41 |
|
| 42 |
-
def web_search(query
|
| 43 |
try:
|
| 44 |
with DDGS() as ddgs:
|
| 45 |
results = list(ddgs.text(query, max_results=max_results))
|
| 46 |
if not results:
|
| 47 |
return ""
|
| 48 |
-
|
| 49 |
for i, r in enumerate(results, 1):
|
| 50 |
title = r.get("title", "")
|
| 51 |
body = r.get("body", "")
|
| 52 |
href = r.get("href", "")
|
| 53 |
-
|
| 54 |
-
return "\n\n".join(
|
| 55 |
except Exception as e:
|
| 56 |
print(f"Search error: {e}")
|
| 57 |
return ""
|
| 58 |
|
| 59 |
|
| 60 |
-
def should_search(message
|
| 61 |
-
|
| 62 |
"search", "find", "look up", "what is", "who is", "where is",
|
| 63 |
"when did", "how to", "latest", "news", "current", "today",
|
| 64 |
"tell me about", "explain", "define", "meaning of",
|
| 65 |
"what are", "how does", "why does", "can you find",
|
| 66 |
-
"ζη΄’", "ζ₯ζΎ", "ζζ°", "ζ°ι»", "ζ―δ»δΉ", "ζδΉ",
|
| 67 |
]
|
| 68 |
lower = message.lower().strip()
|
| 69 |
-
for
|
| 70 |
-
if
|
| 71 |
return True
|
| 72 |
-
if "?" in message
|
| 73 |
return True
|
| 74 |
return False
|
| 75 |
|
| 76 |
|
| 77 |
-
def build_messages_with_search(messages
|
| 78 |
if not messages:
|
| 79 |
return messages
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
last_user_msg = msg
|
| 85 |
break
|
| 86 |
-
|
| 87 |
-
if last_user_msg is None:
|
| 88 |
return messages
|
| 89 |
-
|
| 90 |
-
user_text = last_user_msg["content"]
|
| 91 |
if not should_search(user_text):
|
| 92 |
return messages
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
if not search_context:
|
| 97 |
return messages
|
| 98 |
-
|
| 99 |
augmented = []
|
| 100 |
-
|
| 101 |
"role": "system",
|
| 102 |
"content": (
|
| 103 |
-
"
|
| 104 |
-
"Use them to inform your answer when relevant. "
|
| 105 |
"Cite sources when possible.\n\n"
|
| 106 |
-
"---
|
| 107 |
-
f"{
|
| 108 |
-
"--- END
|
| 109 |
),
|
| 110 |
-
}
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
for msg in messages:
|
| 114 |
-
augmented.append(msg)
|
| 115 |
-
|
| 116 |
return augmented
|
| 117 |
|
| 118 |
|
| 119 |
-
def generate_response(messages
|
| 120 |
augmented = build_messages_with_search(messages)
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 129 |
if len(text) > MAX_CONTEXT * 4:
|
| 130 |
text = text[-(MAX_CONTEXT * 4):]
|
| 131 |
-
|
| 132 |
inputs = tokenizer(text, return_tensors="pt", truncation=True, max_length=MAX_CONTEXT)
|
| 133 |
-
|
| 134 |
with torch.no_grad():
|
| 135 |
outputs = model.generate(
|
| 136 |
**inputs,
|
|
@@ -142,47 +135,42 @@ def generate_response(messages: list, enable_thinking: bool = True) -> str:
|
|
| 142 |
repetition_penalty=1.1,
|
| 143 |
pad_token_id=tokenizer.eos_token_id,
|
| 144 |
)
|
| 145 |
-
|
| 146 |
input_len = inputs["input_ids"].shape[-1]
|
| 147 |
generated = outputs[0][input_len:]
|
| 148 |
raw = tokenizer.decode(generated, skip_special_tokens=False)
|
| 149 |
-
|
| 150 |
-
# Parse thinking and answer
|
| 151 |
answer = raw
|
| 152 |
thinking = ""
|
| 153 |
if "</think>" in raw:
|
| 154 |
parts = raw.split("</think>", 1)
|
| 155 |
-
|
| 156 |
answer = parts[1] if len(parts) > 1 else ""
|
| 157 |
-
thinking = thinking_part.replace("<think>", "").strip()
|
| 158 |
else:
|
| 159 |
answer = raw.replace("<think>", "").strip()
|
| 160 |
-
|
| 161 |
-
# Clean special tokens
|
| 162 |
-
for tok in ["<|endoftext|>", "<|im_end|>", "<|end|>"]:
|
| 163 |
answer = answer.replace(tok, "")
|
| 164 |
answer = answer.strip()
|
| 165 |
-
|
| 166 |
return answer, thinking
|
| 167 |
|
| 168 |
|
| 169 |
-
def generate_response_streaming(messages
|
| 170 |
augmented = build_messages_with_search(messages)
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 179 |
if len(text) > MAX_CONTEXT * 4:
|
| 180 |
text = text[-(MAX_CONTEXT * 4):]
|
| 181 |
-
|
| 182 |
inputs = tokenizer(text, return_tensors="pt", truncation=True, max_length=MAX_CONTEXT)
|
| 183 |
-
|
| 184 |
streamer = TextIteratorStreamer(tokenizer, skip_prompt=True, skip_special_tokens=False)
|
| 185 |
-
|
| 186 |
gen_kwargs = dict(
|
| 187 |
**inputs,
|
| 188 |
max_new_tokens=MAX_NEW_TOKENS,
|
|
@@ -194,14 +182,12 @@ def generate_response_streaming(messages: list, enable_thinking: bool = True):
|
|
| 194 |
pad_token_id=tokenizer.eos_token_id,
|
| 195 |
streamer=streamer,
|
| 196 |
)
|
| 197 |
-
|
| 198 |
thread = threading.Thread(target=model.generate, kwargs=gen_kwargs)
|
| 199 |
thread.start()
|
| 200 |
-
|
| 201 |
return streamer
|
| 202 |
|
| 203 |
|
| 204 |
-
# FastAPI
|
| 205 |
app = FastAPI(title="Qwen3-1.7B Chat API")
|
| 206 |
|
| 207 |
|
|
@@ -227,16 +213,13 @@ def health():
|
|
| 227 |
@app.post("/v1/chat/completions")
|
| 228 |
async def chat_completions(request: ChatRequest):
|
| 229 |
messages = [{"role": m.role, "content": m.content} for m in request.messages]
|
| 230 |
-
|
| 231 |
if request.stream:
|
| 232 |
return StreamingResponse(
|
| 233 |
stream_chat(messages, request.enable_thinking, request.model),
|
| 234 |
media_type="text/event-stream",
|
| 235 |
)
|
| 236 |
-
|
| 237 |
answer, thinking = generate_response(messages, request.enable_thinking)
|
| 238 |
-
|
| 239 |
-
response = {
|
| 240 |
"id": f"chatcmpl-{uuid.uuid4().hex[:8]}",
|
| 241 |
"object": "chat.completion",
|
| 242 |
"created": int(time.time()),
|
|
@@ -244,10 +227,7 @@ async def chat_completions(request: ChatRequest):
|
|
| 244 |
"choices": [
|
| 245 |
{
|
| 246 |
"index": 0,
|
| 247 |
-
"message": {
|
| 248 |
-
"role": "assistant",
|
| 249 |
-
"content": answer,
|
| 250 |
-
},
|
| 251 |
"finish_reason": "stop",
|
| 252 |
}
|
| 253 |
],
|
|
@@ -257,27 +237,30 @@ async def chat_completions(request: ChatRequest):
|
|
| 257 |
"total_tokens": 0,
|
| 258 |
},
|
| 259 |
}
|
| 260 |
-
|
| 261 |
if thinking:
|
| 262 |
-
|
| 263 |
-
|
| 264 |
-
return JSONResponse(content=response)
|
| 265 |
|
| 266 |
|
| 267 |
async def stream_chat(messages, enable_thinking, model_name):
|
| 268 |
streamer = generate_response_streaming(messages, enable_thinking)
|
| 269 |
chat_id = f"chatcmpl-{uuid.uuid4().hex[:8]}"
|
| 270 |
-
|
| 271 |
-
|
| 272 |
for token_text in streamer:
|
| 273 |
-
full_text += token_text
|
| 274 |
-
# Skip thinking tokens in stream output
|
| 275 |
clean = token_text
|
| 276 |
-
for tok in ["<|endoftext|>", "<|im_end|>", "<|end|>", "<
|
| 277 |
clean = clean.replace(tok, "")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 278 |
if not clean:
|
| 279 |
continue
|
| 280 |
-
|
| 281 |
chunk = {
|
| 282 |
"id": chat_id,
|
| 283 |
"object": "chat.completion.chunk",
|
|
@@ -292,8 +275,7 @@ async def stream_chat(messages, enable_thinking, model_name):
|
|
| 292 |
],
|
| 293 |
}
|
| 294 |
yield f"data: {json.dumps(chunk)}\n\n"
|
| 295 |
-
|
| 296 |
-
final_chunk = {
|
| 297 |
"id": chat_id,
|
| 298 |
"object": "chat.completion.chunk",
|
| 299 |
"created": int(time.time()),
|
|
@@ -306,21 +288,25 @@ async def stream_chat(messages, enable_thinking, model_name):
|
|
| 306 |
}
|
| 307 |
],
|
| 308 |
}
|
| 309 |
-
yield f"data: {json.dumps(
|
| 310 |
yield "data: [DONE]\n\n"
|
| 311 |
|
| 312 |
|
| 313 |
-
# Gradio UI
|
| 314 |
def chat_fn(message, history, enable_search, enable_thinking):
|
| 315 |
if not message or not message.strip():
|
| 316 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 317 |
|
| 318 |
messages = []
|
| 319 |
-
for
|
| 320 |
-
if
|
| 321 |
-
messages.append({"role": "user", "content":
|
| 322 |
-
|
| 323 |
-
messages.append({"role": "assistant", "content":
|
| 324 |
messages.append({"role": "user", "content": message})
|
| 325 |
|
| 326 |
if not enable_search:
|
|
@@ -328,21 +314,125 @@ def chat_fn(message, history, enable_search, enable_thinking):
|
|
| 328 |
else:
|
| 329 |
final_messages = build_messages_with_search(messages)
|
| 330 |
|
| 331 |
-
|
| 332 |
-
|
| 333 |
-
|
| 334 |
-
|
| 335 |
-
|
| 336 |
-
|
| 337 |
-
|
| 338 |
-
|
| 339 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 340 |
|
| 341 |
-
|
|
|
|
|
|
|
|
|
|
| 342 |
|
| 343 |
|
| 344 |
def clear_fn():
|
| 345 |
-
return
|
| 346 |
|
| 347 |
|
| 348 |
with gr.Blocks(
|
|
@@ -350,78 +440,61 @@ with gr.Blocks(
|
|
| 350 |
css="""
|
| 351 |
.gradio-container { max-width: 900px !important; margin: auto; }
|
| 352 |
footer { display: none !important; }
|
| 353 |
-
.thinking-block { background: #f0f0f0; padding: 10px; border-radius: 8px; margin-bottom: 10px; }
|
| 354 |
"""
|
| 355 |
) as chat_ui:
|
| 356 |
gr.Markdown(
|
| 357 |
"""
|
| 358 |
# π€ Qwen3-1.7B Chat
|
| 359 |
-
**Free CPU-based LLM
|
| 360 |
|
| 361 |
-
|
| 362 |
-
- π Thinking mode shows the model's reasoning process
|
| 363 |
-
- π REST API available at `/v1/chat/completions`
|
| 364 |
"""
|
| 365 |
)
|
| 366 |
|
| 367 |
-
|
| 368 |
-
height=
|
| 369 |
-
type="messages",
|
| 370 |
show_copy_button=True,
|
| 371 |
-
avatar_images=(None, None),
|
| 372 |
render_markdown=True,
|
|
|
|
| 373 |
)
|
| 374 |
|
| 375 |
with gr.Row():
|
| 376 |
msg = gr.Textbox(
|
| 377 |
-
placeholder="Type your message here...
|
| 378 |
show_label=False,
|
| 379 |
scale=8,
|
| 380 |
container=False,
|
| 381 |
)
|
| 382 |
-
submit_btn = gr.Button("Send", variant="primary", scale=1)
|
| 383 |
|
| 384 |
with gr.Row():
|
| 385 |
-
enable_search = gr.Checkbox(
|
| 386 |
-
|
| 387 |
-
|
| 388 |
-
scale=1,
|
| 389 |
-
)
|
| 390 |
-
enable_thinking = gr.Checkbox(
|
| 391 |
-
label="π Thinking Mode",
|
| 392 |
-
value=True,
|
| 393 |
-
scale=1,
|
| 394 |
-
)
|
| 395 |
-
clear_btn = gr.Button("ποΈ Clear", scale=1)
|
| 396 |
|
| 397 |
-
with gr.Accordion("API Usage", open=False):
|
| 398 |
gr.Markdown(
|
| 399 |
"""
|
| 400 |
```bash
|
| 401 |
curl -X POST https://YOUR_SPACE.hf.space/v1/chat/completions \\
|
| 402 |
-H "Content-Type: application/json" \\
|
| 403 |
-
-d '{
|
| 404 |
-
"messages": [{"role": "user", "content": "Hello!"}],
|
| 405 |
-
"stream": false,
|
| 406 |
-
"enable_thinking": true
|
| 407 |
-
}'
|
| 408 |
```
|
| 409 |
"""
|
| 410 |
)
|
| 411 |
|
| 412 |
submit_btn.click(
|
| 413 |
fn=chat_fn,
|
| 414 |
-
inputs=[msg,
|
| 415 |
-
outputs=[
|
| 416 |
-
)
|
|
|
|
| 417 |
msg.submit(
|
| 418 |
fn=chat_fn,
|
| 419 |
-
inputs=[msg,
|
| 420 |
-
outputs=[
|
| 421 |
-
)
|
| 422 |
-
|
| 423 |
-
|
| 424 |
-
outputs=[msg, chatbot],
|
| 425 |
-
)
|
| 426 |
|
| 427 |
app = gr.mount_gradio_app(app, chat_ui, path="/")
|
|
|
|
| 33 |
low_cpu_mem_usage=True,
|
| 34 |
)
|
| 35 |
model.eval()
|
| 36 |
+
print("Model loaded successfully.")
|
| 37 |
|
| 38 |
+
MAX_NEW_TOKENS = 256
|
| 39 |
+
MAX_CONTEXT = 1024
|
| 40 |
|
| 41 |
|
| 42 |
+
def web_search(query, max_results=3):
|
| 43 |
try:
|
| 44 |
with DDGS() as ddgs:
|
| 45 |
results = list(ddgs.text(query, max_results=max_results))
|
| 46 |
if not results:
|
| 47 |
return ""
|
| 48 |
+
parts = []
|
| 49 |
for i, r in enumerate(results, 1):
|
| 50 |
title = r.get("title", "")
|
| 51 |
body = r.get("body", "")
|
| 52 |
href = r.get("href", "")
|
| 53 |
+
parts.append(f"[{i}] {title}\n{body}\nURL: {href}")
|
| 54 |
+
return "\n\n".join(parts)
|
| 55 |
except Exception as e:
|
| 56 |
print(f"Search error: {e}")
|
| 57 |
return ""
|
| 58 |
|
| 59 |
|
| 60 |
+
def should_search(message):
|
| 61 |
+
triggers = [
|
| 62 |
"search", "find", "look up", "what is", "who is", "where is",
|
| 63 |
"when did", "how to", "latest", "news", "current", "today",
|
| 64 |
"tell me about", "explain", "define", "meaning of",
|
| 65 |
"what are", "how does", "why does", "can you find",
|
|
|
|
| 66 |
]
|
| 67 |
lower = message.lower().strip()
|
| 68 |
+
for t in triggers:
|
| 69 |
+
if t in lower:
|
| 70 |
return True
|
| 71 |
+
if "?" in message:
|
| 72 |
return True
|
| 73 |
return False
|
| 74 |
|
| 75 |
|
| 76 |
+
def build_messages_with_search(messages):
|
| 77 |
if not messages:
|
| 78 |
return messages
|
| 79 |
+
last_user = None
|
| 80 |
+
for m in reversed(messages):
|
| 81 |
+
if m["role"] == "user":
|
| 82 |
+
last_user = m
|
|
|
|
| 83 |
break
|
| 84 |
+
if last_user is None:
|
|
|
|
| 85 |
return messages
|
| 86 |
+
user_text = last_user["content"]
|
|
|
|
| 87 |
if not should_search(user_text):
|
| 88 |
return messages
|
| 89 |
+
print(f"Searching: {user_text[:80]}")
|
| 90 |
+
ctx = web_search(user_text)
|
| 91 |
+
if not ctx:
|
|
|
|
| 92 |
return messages
|
|
|
|
| 93 |
augmented = []
|
| 94 |
+
augmented.append({
|
| 95 |
"role": "system",
|
| 96 |
"content": (
|
| 97 |
+
"Web search results for context. Use them to help answer. "
|
|
|
|
| 98 |
"Cite sources when possible.\n\n"
|
| 99 |
+
"--- SEARCH RESULTS ---\n"
|
| 100 |
+
f"{ctx}\n"
|
| 101 |
+
"--- END RESULTS ---"
|
| 102 |
),
|
| 103 |
+
})
|
| 104 |
+
for m in messages:
|
| 105 |
+
augmented.append(m)
|
|
|
|
|
|
|
|
|
|
| 106 |
return augmented
|
| 107 |
|
| 108 |
|
| 109 |
+
def generate_response(messages, enable_thinking=True):
|
| 110 |
augmented = build_messages_with_search(messages)
|
| 111 |
+
try:
|
| 112 |
+
text = tokenizer.apply_chat_template(
|
| 113 |
+
augmented,
|
| 114 |
+
tokenize=False,
|
| 115 |
+
add_generation_prompt=True,
|
| 116 |
+
enable_thinking=enable_thinking,
|
| 117 |
+
)
|
| 118 |
+
except TypeError:
|
| 119 |
+
text = tokenizer.apply_chat_template(
|
| 120 |
+
augmented,
|
| 121 |
+
tokenize=False,
|
| 122 |
+
add_generation_prompt=True,
|
| 123 |
+
)
|
| 124 |
if len(text) > MAX_CONTEXT * 4:
|
| 125 |
text = text[-(MAX_CONTEXT * 4):]
|
|
|
|
| 126 |
inputs = tokenizer(text, return_tensors="pt", truncation=True, max_length=MAX_CONTEXT)
|
|
|
|
| 127 |
with torch.no_grad():
|
| 128 |
outputs = model.generate(
|
| 129 |
**inputs,
|
|
|
|
| 135 |
repetition_penalty=1.1,
|
| 136 |
pad_token_id=tokenizer.eos_token_id,
|
| 137 |
)
|
|
|
|
| 138 |
input_len = inputs["input_ids"].shape[-1]
|
| 139 |
generated = outputs[0][input_len:]
|
| 140 |
raw = tokenizer.decode(generated, skip_special_tokens=False)
|
|
|
|
|
|
|
| 141 |
answer = raw
|
| 142 |
thinking = ""
|
| 143 |
if "</think>" in raw:
|
| 144 |
parts = raw.split("</think>", 1)
|
| 145 |
+
thinking = parts[0].replace("<think>", "").strip()
|
| 146 |
answer = parts[1] if len(parts) > 1 else ""
|
|
|
|
| 147 |
else:
|
| 148 |
answer = raw.replace("<think>", "").strip()
|
| 149 |
+
for tok in ["<|endoftext|>", "<|im_end|>", "<|end|>", "<|im_start|>"]:
|
|
|
|
|
|
|
| 150 |
answer = answer.replace(tok, "")
|
| 151 |
answer = answer.strip()
|
|
|
|
| 152 |
return answer, thinking
|
| 153 |
|
| 154 |
|
| 155 |
+
def generate_response_streaming(messages, enable_thinking=True):
|
| 156 |
augmented = build_messages_with_search(messages)
|
| 157 |
+
try:
|
| 158 |
+
text = tokenizer.apply_chat_template(
|
| 159 |
+
augmented,
|
| 160 |
+
tokenize=False,
|
| 161 |
+
add_generation_prompt=True,
|
| 162 |
+
enable_thinking=enable_thinking,
|
| 163 |
+
)
|
| 164 |
+
except TypeError:
|
| 165 |
+
text = tokenizer.apply_chat_template(
|
| 166 |
+
augmented,
|
| 167 |
+
tokenize=False,
|
| 168 |
+
add_generation_prompt=True,
|
| 169 |
+
)
|
| 170 |
if len(text) > MAX_CONTEXT * 4:
|
| 171 |
text = text[-(MAX_CONTEXT * 4):]
|
|
|
|
| 172 |
inputs = tokenizer(text, return_tensors="pt", truncation=True, max_length=MAX_CONTEXT)
|
|
|
|
| 173 |
streamer = TextIteratorStreamer(tokenizer, skip_prompt=True, skip_special_tokens=False)
|
|
|
|
| 174 |
gen_kwargs = dict(
|
| 175 |
**inputs,
|
| 176 |
max_new_tokens=MAX_NEW_TOKENS,
|
|
|
|
| 182 |
pad_token_id=tokenizer.eos_token_id,
|
| 183 |
streamer=streamer,
|
| 184 |
)
|
|
|
|
| 185 |
thread = threading.Thread(target=model.generate, kwargs=gen_kwargs)
|
| 186 |
thread.start()
|
|
|
|
| 187 |
return streamer
|
| 188 |
|
| 189 |
|
| 190 |
+
# --- FastAPI ---
|
| 191 |
app = FastAPI(title="Qwen3-1.7B Chat API")
|
| 192 |
|
| 193 |
|
|
|
|
| 213 |
@app.post("/v1/chat/completions")
|
| 214 |
async def chat_completions(request: ChatRequest):
|
| 215 |
messages = [{"role": m.role, "content": m.content} for m in request.messages]
|
|
|
|
| 216 |
if request.stream:
|
| 217 |
return StreamingResponse(
|
| 218 |
stream_chat(messages, request.enable_thinking, request.model),
|
| 219 |
media_type="text/event-stream",
|
| 220 |
)
|
|
|
|
| 221 |
answer, thinking = generate_response(messages, request.enable_thinking)
|
| 222 |
+
resp = {
|
|
|
|
| 223 |
"id": f"chatcmpl-{uuid.uuid4().hex[:8]}",
|
| 224 |
"object": "chat.completion",
|
| 225 |
"created": int(time.time()),
|
|
|
|
| 227 |
"choices": [
|
| 228 |
{
|
| 229 |
"index": 0,
|
| 230 |
+
"message": {"role": "assistant", "content": answer},
|
|
|
|
|
|
|
|
|
|
| 231 |
"finish_reason": "stop",
|
| 232 |
}
|
| 233 |
],
|
|
|
|
| 237 |
"total_tokens": 0,
|
| 238 |
},
|
| 239 |
}
|
|
|
|
| 240 |
if thinking:
|
| 241 |
+
resp["choices"][0]["message"]["thinking"] = thinking
|
| 242 |
+
return JSONResponse(content=resp)
|
|
|
|
| 243 |
|
| 244 |
|
| 245 |
async def stream_chat(messages, enable_thinking, model_name):
|
| 246 |
streamer = generate_response_streaming(messages, enable_thinking)
|
| 247 |
chat_id = f"chatcmpl-{uuid.uuid4().hex[:8]}"
|
| 248 |
+
in_think = False
|
|
|
|
| 249 |
for token_text in streamer:
|
|
|
|
|
|
|
| 250 |
clean = token_text
|
| 251 |
+
for tok in ["<|endoftext|>", "<|im_end|>", "<|end|>", "<|im_start|>"]:
|
| 252 |
clean = clean.replace(tok, "")
|
| 253 |
+
if "<think>" in clean:
|
| 254 |
+
in_think = True
|
| 255 |
+
clean = clean.replace("<think>", "")
|
| 256 |
+
if "</think>" in clean:
|
| 257 |
+
in_think = False
|
| 258 |
+
clean = clean.replace("</think>", "")
|
| 259 |
+
continue
|
| 260 |
+
if in_think:
|
| 261 |
+
continue
|
| 262 |
if not clean:
|
| 263 |
continue
|
|
|
|
| 264 |
chunk = {
|
| 265 |
"id": chat_id,
|
| 266 |
"object": "chat.completion.chunk",
|
|
|
|
| 275 |
],
|
| 276 |
}
|
| 277 |
yield f"data: {json.dumps(chunk)}\n\n"
|
| 278 |
+
final = {
|
|
|
|
| 279 |
"id": chat_id,
|
| 280 |
"object": "chat.completion.chunk",
|
| 281 |
"created": int(time.time()),
|
|
|
|
| 288 |
}
|
| 289 |
],
|
| 290 |
}
|
| 291 |
+
yield f"data: {json.dumps(final)}\n\n"
|
| 292 |
yield "data: [DONE]\n\n"
|
| 293 |
|
| 294 |
|
| 295 |
+
# --- Gradio UI ---
|
| 296 |
def chat_fn(message, history, enable_search, enable_thinking):
|
| 297 |
if not message or not message.strip():
|
| 298 |
+
yield history
|
| 299 |
+
return
|
| 300 |
+
history = history or []
|
| 301 |
+
history.append([message, None])
|
| 302 |
+
yield history
|
| 303 |
|
| 304 |
messages = []
|
| 305 |
+
for pair in history[:-1]:
|
| 306 |
+
if pair[0]:
|
| 307 |
+
messages.append({"role": "user", "content": pair[0]})
|
| 308 |
+
if pair[1]:
|
| 309 |
+
messages.append({"role": "assistant", "content": pair[1]})
|
| 310 |
messages.append({"role": "user", "content": message})
|
| 311 |
|
| 312 |
if not enable_search:
|
|
|
|
| 314 |
else:
|
| 315 |
final_messages = build_messages_with_search(messages)
|
| 316 |
|
| 317 |
+
try:
|
| 318 |
+
text_input = None
|
| 319 |
+
try:
|
| 320 |
+
text_input = tokenizer.apply_chat_template(
|
| 321 |
+
final_messages,
|
| 322 |
+
tokenize=False,
|
| 323 |
+
add_generation_prompt=True,
|
| 324 |
+
enable_thinking=enable_thinking,
|
| 325 |
+
)
|
| 326 |
+
except TypeError:
|
| 327 |
+
text_input = tokenizer.apply_chat_template(
|
| 328 |
+
final_messages,
|
| 329 |
+
tokenize=False,
|
| 330 |
+
add_generation_prompt=True,
|
| 331 |
+
)
|
| 332 |
+
|
| 333 |
+
if len(text_input) > MAX_CONTEXT * 4:
|
| 334 |
+
text_input = text_input[-(MAX_CONTEXT * 4):]
|
| 335 |
+
|
| 336 |
+
inputs = tokenizer(text_input, return_tensors="pt", truncation=True, max_length=MAX_CONTEXT)
|
| 337 |
+
streamer = TextIteratorStreamer(tokenizer, skip_prompt=True, skip_special_tokens=False)
|
| 338 |
+
|
| 339 |
+
gen_kwargs = dict(
|
| 340 |
+
**inputs,
|
| 341 |
+
max_new_tokens=MAX_NEW_TOKENS,
|
| 342 |
+
do_sample=True,
|
| 343 |
+
temperature=0.7,
|
| 344 |
+
top_p=0.9,
|
| 345 |
+
top_k=50,
|
| 346 |
+
repetition_penalty=1.1,
|
| 347 |
+
pad_token_id=tokenizer.eos_token_id,
|
| 348 |
+
streamer=streamer,
|
| 349 |
+
)
|
| 350 |
+
thread = threading.Thread(target=model.generate, kwargs=gen_kwargs)
|
| 351 |
+
thread.start()
|
| 352 |
+
|
| 353 |
+
full_raw = ""
|
| 354 |
+
thinking_text = ""
|
| 355 |
+
answer_text = ""
|
| 356 |
+
in_think = False
|
| 357 |
+
think_done = False
|
| 358 |
+
|
| 359 |
+
for token in streamer:
|
| 360 |
+
full_raw += token
|
| 361 |
+
|
| 362 |
+
if not think_done:
|
| 363 |
+
if "<think>" in full_raw and not in_think:
|
| 364 |
+
in_think = True
|
| 365 |
+
idx = full_raw.index("<think>")
|
| 366 |
+
full_raw_after = full_raw[idx + len("<think>"):]
|
| 367 |
+
if "</think>" in full_raw_after:
|
| 368 |
+
end_idx = full_raw_after.index("</think>")
|
| 369 |
+
thinking_text = full_raw_after[:end_idx]
|
| 370 |
+
answer_text = full_raw_after[end_idx + len("</think>"):]
|
| 371 |
+
think_done = True
|
| 372 |
+
in_think = False
|
| 373 |
+
else:
|
| 374 |
+
thinking_text = full_raw_after
|
| 375 |
+
continue
|
| 376 |
+
elif in_think:
|
| 377 |
+
if "</think>" in full_raw:
|
| 378 |
+
start = full_raw.index("<think>") + len("<think>")
|
| 379 |
+
end = full_raw.index("</think>")
|
| 380 |
+
thinking_text = full_raw[start:end]
|
| 381 |
+
answer_text = full_raw[end + len("</think>"):]
|
| 382 |
+
think_done = True
|
| 383 |
+
in_think = False
|
| 384 |
+
else:
|
| 385 |
+
start = full_raw.index("<think>") + len("<think>")
|
| 386 |
+
thinking_text = full_raw[start:]
|
| 387 |
+
display = ""
|
| 388 |
+
if thinking_text.strip():
|
| 389 |
+
display = f"π *Thinking...*\n\n{thinking_text.strip()}"
|
| 390 |
+
history[-1][1] = display
|
| 391 |
+
yield history
|
| 392 |
+
continue
|
| 393 |
+
|
| 394 |
+
if think_done:
|
| 395 |
+
start = full_raw.index("</think>") + len("</think>")
|
| 396 |
+
answer_text = full_raw[start:]
|
| 397 |
+
else:
|
| 398 |
+
answer_text = full_raw
|
| 399 |
+
|
| 400 |
+
for tok in ["<|endoftext|>", "<|im_end|>", "<|end|>", "<|im_start|>", "<think>", "</think>"]:
|
| 401 |
+
answer_text = answer_text.replace(tok, "")
|
| 402 |
+
|
| 403 |
+
display = ""
|
| 404 |
+
if thinking_text.strip():
|
| 405 |
+
display += f"<details><summary>π Thought Process</summary>\n\n{thinking_text.strip()}\n\n</details>\n\n"
|
| 406 |
+
display += answer_text.strip()
|
| 407 |
+
history[-1][1] = display
|
| 408 |
+
yield history
|
| 409 |
+
|
| 410 |
+
thread.join()
|
| 411 |
+
|
| 412 |
+
if think_done:
|
| 413 |
+
start = full_raw.index("</think>") + len("</think>")
|
| 414 |
+
answer_text = full_raw[start:]
|
| 415 |
+
else:
|
| 416 |
+
answer_text = full_raw.replace("<think>", "").replace("</think>", "")
|
| 417 |
+
|
| 418 |
+
for tok in ["<|endoftext|>", "<|im_end|>", "<|end|>", "<|im_start|>"]:
|
| 419 |
+
answer_text = answer_text.replace(tok, "")
|
| 420 |
+
|
| 421 |
+
display = ""
|
| 422 |
+
if thinking_text.strip():
|
| 423 |
+
display += f"<details><summary>π Thought Process</summary>\n\n{thinking_text.strip()}\n\n</details>\n\n"
|
| 424 |
+
display += answer_text.strip()
|
| 425 |
+
history[-1][1] = display
|
| 426 |
+
yield history
|
| 427 |
|
| 428 |
+
except Exception as e:
|
| 429 |
+
print(f"Generation error: {e}")
|
| 430 |
+
history[-1][1] = f"β Error: {str(e)}"
|
| 431 |
+
yield history
|
| 432 |
|
| 433 |
|
| 434 |
def clear_fn():
|
| 435 |
+
return [], ""
|
| 436 |
|
| 437 |
|
| 438 |
with gr.Blocks(
|
|
|
|
| 440 |
css="""
|
| 441 |
.gradio-container { max-width: 900px !important; margin: auto; }
|
| 442 |
footer { display: none !important; }
|
|
|
|
| 443 |
"""
|
| 444 |
) as chat_ui:
|
| 445 |
gr.Markdown(
|
| 446 |
"""
|
| 447 |
# π€ Qwen3-1.7B Chat
|
| 448 |
+
**Free CPU-based LLM β’ Web Search β’ Thinking Mode**
|
| 449 |
|
| 450 |
+
π‘ Questions with "?" auto-trigger web search | API at `/v1/chat/completions`
|
|
|
|
|
|
|
| 451 |
"""
|
| 452 |
)
|
| 453 |
|
| 454 |
+
chatbot_ui = gr.Chatbot(
|
| 455 |
+
height=480,
|
|
|
|
| 456 |
show_copy_button=True,
|
|
|
|
| 457 |
render_markdown=True,
|
| 458 |
+
label="Chat",
|
| 459 |
)
|
| 460 |
|
| 461 |
with gr.Row():
|
| 462 |
msg = gr.Textbox(
|
| 463 |
+
placeholder="Type your message here...",
|
| 464 |
show_label=False,
|
| 465 |
scale=8,
|
| 466 |
container=False,
|
| 467 |
)
|
| 468 |
+
submit_btn = gr.Button("Send", variant="primary", scale=1, min_width=80)
|
| 469 |
|
| 470 |
with gr.Row():
|
| 471 |
+
enable_search = gr.Checkbox(label="π Web Search", value=True)
|
| 472 |
+
enable_thinking = gr.Checkbox(label="π Thinking", value=True)
|
| 473 |
+
clear_btn = gr.Button("ποΈ Clear")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 474 |
|
| 475 |
+
with gr.Accordion("π‘ API Usage", open=False):
|
| 476 |
gr.Markdown(
|
| 477 |
"""
|
| 478 |
```bash
|
| 479 |
curl -X POST https://YOUR_SPACE.hf.space/v1/chat/completions \\
|
| 480 |
-H "Content-Type: application/json" \\
|
| 481 |
+
-d '{"messages": [{"role": "user", "content": "Hello!"}]}'
|
|
|
|
|
|
|
|
|
|
|
|
|
| 482 |
```
|
| 483 |
"""
|
| 484 |
)
|
| 485 |
|
| 486 |
submit_btn.click(
|
| 487 |
fn=chat_fn,
|
| 488 |
+
inputs=[msg, chatbot_ui, enable_search, enable_thinking],
|
| 489 |
+
outputs=[chatbot_ui],
|
| 490 |
+
).then(fn=lambda: "", outputs=[msg])
|
| 491 |
+
|
| 492 |
msg.submit(
|
| 493 |
fn=chat_fn,
|
| 494 |
+
inputs=[msg, chatbot_ui, enable_search, enable_thinking],
|
| 495 |
+
outputs=[chatbot_ui],
|
| 496 |
+
).then(fn=lambda: "", outputs=[msg])
|
| 497 |
+
|
| 498 |
+
clear_btn.click(fn=clear_fn, outputs=[chatbot_ui, msg])
|
|
|
|
|
|
|
| 499 |
|
| 500 |
app = gr.mount_gradio_app(app, chat_ui, path="/")
|