fix: typing — ThreadPoolExecutor + polling loop каждые 4 сек
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -158,27 +158,40 @@ async def ask_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
||||
|
||||
import time
|
||||
|
||||
import concurrent.futures
|
||||
|
||||
assistant = get_assistant()
|
||||
q_type = assistant._classify_question(question)
|
||||
eta = "~5 сек" if q_type == "cag" else "~15-20 сек"
|
||||
wait_msg = await update.message.reply_text(f"🤔 Думаю... {eta}")
|
||||
|
||||
# Keep typing indicator active throughout
|
||||
stop_typing = asyncio.Event()
|
||||
typing_task = asyncio.create_task(
|
||||
keep_typing(context.bot, update.effective_chat.id, stop_typing)
|
||||
)
|
||||
chat_id = update.effective_chat.id
|
||||
|
||||
# Start LLM in thread pool (non-blocking)
|
||||
loop = asyncio.get_event_loop()
|
||||
executor = concurrent.futures.ThreadPoolExecutor(max_workers=1)
|
||||
future = loop.run_in_executor(executor, assistant.ask, question)
|
||||
|
||||
t0 = time.time()
|
||||
|
||||
# Send typing every 4 sec while waiting
|
||||
while not future.done():
|
||||
try:
|
||||
await context.bot.send_chat_action(chat_id=chat_id, action="typing")
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
await asyncio.wait_for(asyncio.shield(future), timeout=4.0)
|
||||
break
|
||||
except asyncio.TimeoutError:
|
||||
continue
|
||||
except Exception:
|
||||
break
|
||||
|
||||
try:
|
||||
t0 = time.time()
|
||||
answer = await asyncio.get_event_loop().run_in_executor(
|
||||
None, assistant.ask, question
|
||||
)
|
||||
answer = future.result()
|
||||
elapsed = time.time() - t0
|
||||
|
||||
stop_typing.set()
|
||||
await typing_task
|
||||
|
||||
if len(answer) > 4000:
|
||||
answer = answer[:3900] + "\n\n... (ответ сокращён)"
|
||||
answer += f"\n\n⏱ {elapsed:.1f}с"
|
||||
@@ -190,8 +203,6 @@ async def ask_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
||||
await update.message.reply_text(answer)
|
||||
|
||||
except Exception as e:
|
||||
stop_typing.set()
|
||||
await typing_task
|
||||
logger.error(f"Ask error: {e}")
|
||||
try:
|
||||
await wait_msg.delete()
|
||||
|
||||
Reference in New Issue
Block a user