File size: 5,862 Bytes
4688320 e5ccc9c 4688320 e5ccc9c 45db2c3 e5ccc9c 2767a63 e5ccc9c 2767a63 e5ccc9c 2767a63 e5ccc9c 4688320 e5ccc9c 4688320 e5ccc9c 4688320 e5ccc9c 4688320 2767a63 4688320 e5ccc9c 4688320 e5ccc9c 4688320 e5ccc9c 2767a63 e5ccc9c 4688320 e5ccc9c 4688320 2767a63 45db2c3 2767a63 e5ccc9c 2767a63 e5ccc9c 2767a63 e5ccc9c 4688320 e5ccc9c 4688320 e5ccc9c 4688320 47dc0fe 2767a63 45db2c3 4688320 45db2c3 47dc0fe 2767a63 47dc0fe 4688320 45db2c3 4688320 47dc0fe 4688320 47dc0fe 4688320 | 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 | import queue
import threading
import time
import logging
from bot.telegram_api import (
send_message,
edit_message,
delete_message,
md_to_telegram_html,
split_for_telegram,
)
from model.qwen import generate_stream
from db import models as dbm
log = logging.getLogger("streaming")
EDIT_THROTTLE_SEC = 1.0
CURSOR = " ▌"
PREVIEW_LIMIT = 3500
QUEUE_TIMEOUT = 300
FALLBACK_PLAIN_LIMIT = 3900
async def stream_reply(chat_id, user_id, user_text):
try:
window = int(dbm.get_setting("conversation_window", "6"))
except Exception:
window = 6
try:
max_new = int(dbm.get_setting("max_new_tokens", "1024"))
except Exception:
max_new = 1024
try:
temperature = float(dbm.get_setting("temperature", "0.7"))
except Exception:
temperature = 0.7
try:
top_p = float(dbm.get_setting("top_p", "0.9"))
except Exception:
top_p = 0.9
system_prompt = dbm.get_setting("system_prompt", "You are a helpful assistant.")
history = dbm.get_history(user_id, window)
messages = [{"role": "system", "content": system_prompt}] + history
sent = await send_message(chat_id, CURSOR, parse_mode=None)
if not sent.get("ok"):
log.error(f"sendMessage placeholder failed: {sent}")
return
placeholder_id = sent["result"]["message_id"]
buffer = ""
last_edit = 0.0
gpu_start = time.time()
first_token_at = None
error = None
q = queue.Queue()
def _producer():
try:
for chunk in generate_stream(messages, max_new, temperature, top_p):
q.put(("chunk", chunk))
except Exception as e:
q.put(("error", repr(e)))
finally:
q.put(("done", None))
threading.Thread(target=_producer, daemon=True).start()
try:
while True:
try:
kind, payload = q.get(timeout=QUEUE_TIMEOUT)
except queue.Empty:
error = "timeout"
break
if kind == "chunk":
if first_token_at is None:
first_token_at = time.time()
buffer += payload
now = time.time()
if now - last_edit >= EDIT_THROTTLE_SEC:
preview = buffer
if len(preview) > PREVIEW_LIMIT:
preview = preview[-PREVIEW_LIMIT:]
await _safe_edit_plain(chat_id, placeholder_id, preview + CURSOR)
last_edit = now
elif kind == "error":
error = payload
break
elif kind == "done":
break
except Exception as e:
error = repr(e)
log.exception("stream_reply failure")
gpu_ms = int((time.time() - gpu_start) * 1000)
latency_ms = int((time.time() - (first_token_at or gpu_start)) * 1000)
if error:
await _safe_edit_plain(chat_id, placeholder_id, f"⚠️ Error: {error}")
dbm.log_gpu(user_id, gpu_ms, "error")
return
if not buffer.strip():
await _safe_edit_plain(chat_id, placeholder_id, "⚠️ Empty response from model.")
dbm.log_gpu(user_id, gpu_ms, "empty")
return
await delete_message(chat_id, placeholder_id)
delivered = await _deliver_final(chat_id, buffer)
if not delivered:
log.error("Final delivery failed entirely")
await send_message(
chat_id,
"⚠️ Could not deliver the response (formatting error). Full text below:",
parse_mode=None,
)
for chunk in _chunk_plain(buffer, FALLBACK_PLAIN_LIMIT):
await send_message(chat_id, chunk, parse_mode=None)
# ---- Persist ----
dbm.add_message(
user_id, "assistant", buffer,
latency_ms=latency_ms, gpu_time_ms=gpu_ms,
)
dbm.archive_append(user_id, "assistant", buffer, latency_ms=latency_ms)
dbm.increment_user_turns(user_id)
dbm.log_gpu(user_id, gpu_ms, "ok")
user = dbm.get_user(user_id)
if user and user.get("token"):
dbm.bump_token_use(user["token"])
async def _deliver_final(chat_id, raw_text: str) -> bool:
try:
html_text = md_to_telegram_html(raw_text)
chunks = split_for_telegram(html_text)
except Exception:
log.exception("md/split failed for final delivery")
return False
sent_count = 0
for i, chunk in enumerate(chunks):
r = await send_message(chat_id, chunk, parse_mode="HTML")
if r.get("ok"):
sent_count += 1
continue
if i == 0:
log.warning(f"Final chunk 0 HTML failed: {r}")
return False
log.warning(f"Final chunk {i} HTML failed, retrying plain: {r}")
r2 = await send_message(chat_id, _strip_html(chunk), parse_mode=None)
if r2.get("ok"):
sent_count += 1
continue
log.error(f"Plain fallback for chunk {i} also failed: {r2}")
return False
return sent_count == len(chunks)
def _strip_html(s: str) -> str:
import re
return re.sub(r"<[^>]+>", "", s)
def _chunk_plain(text: str, max_len: int):
chunks = []
remaining = text
while len(remaining) > max_len:
cut = remaining.rfind("\n", 0, max_len)
if cut == -1 or cut < max_len * 0.5:
cut = max_len
chunks.append(remaining[:cut])
remaining = remaining[cut:].lstrip("\n")
if remaining:
chunks.append(remaining)
return chunks
async def _safe_edit_plain(chat_id, message_id, text):
try:
r = await edit_message(
chat_id, message_id, text,
parse_mode=None,
)
if not r.get("ok"):
log.warning(f"edit (plain) failed: {r}")
except Exception:
log.exception("plain edit failed") |