mirror of
https://gitee.com/qqtt-ah/ai-crm.git
synced 2026-11-24 01:09:20 +08:00
128 lines
4.8 KiB
Python
128 lines
4.8 KiB
Python
"""前端工具回执门闩:进程内按会话代次等待,供 SSE 挂起后由 POST 唤醒。"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import asyncio
|
|
from dataclasses import dataclass
|
|
|
|
# 前端写入应很快返回;超时后模型拿到失败,避免 SSE 一直挂着
|
|
_DEFAULT_TIMEOUT_SECONDS = 20.0
|
|
|
|
|
|
def format_client_tool_result(ok: bool, message: str) -> str:
|
|
"""写成模型可读的 ToolMessage。失败统一前缀,便于提示词识别。"""
|
|
text = (message or "").strip()
|
|
if ok:
|
|
return text or "已写入"
|
|
return f"写入失败:{text or '未知原因'}"
|
|
|
|
|
|
@dataclass
|
|
class _Waiter:
|
|
epoch: int
|
|
future: asyncio.Future[tuple[bool, str]]
|
|
|
|
|
|
class ClientToolGate:
|
|
"""单进程等待表。多 worker 时回执可能打到别的进程,当前部署按单进程使用。"""
|
|
|
|
def __init__(self, timeout_seconds: float = _DEFAULT_TIMEOUT_SECONDS) -> None:
|
|
self._timeout = timeout_seconds
|
|
self._epoch: dict[str, int] = {}
|
|
self._waiters: dict[tuple[str, str], _Waiter] = {}
|
|
|
|
def begin(self, thread_id: str) -> int:
|
|
"""新开一轮:抬高代次,并结束该会话上一代尚未完成的等待。"""
|
|
epoch = self._epoch.get(thread_id, 0) + 1
|
|
self._epoch[thread_id] = epoch
|
|
self._settle(thread_id, only_epoch=None, keep_epoch=epoch, message="本轮已取消")
|
|
return epoch
|
|
|
|
def end(self, thread_id: str, epoch: int) -> None:
|
|
"""本轮流结束或断开:只结算这一代,避免误伤已开始的下一轮。"""
|
|
self._settle(thread_id, only_epoch=epoch, keep_epoch=None, message="本轮已取消")
|
|
|
|
def arm(self, thread_id: str, epoch: int, tool_call_id: str) -> None:
|
|
"""在向浏览器推 client_tool 之前登记,避免回执先到。"""
|
|
if self._epoch.get(thread_id) != epoch:
|
|
return
|
|
key = (thread_id, tool_call_id)
|
|
loop = asyncio.get_running_loop()
|
|
previous = self._waiters.get(key)
|
|
if previous is not None and not previous.future.done():
|
|
previous.future.set_result((False, "本轮已取消"))
|
|
self._waiters[key] = _Waiter(epoch=epoch, future=loop.create_future())
|
|
|
|
async def wait(self, thread_id: str, epoch: int, tool_call_id: str) -> tuple[bool, str]:
|
|
key = (thread_id, tool_call_id)
|
|
waiter = self._waiters.get(key)
|
|
if waiter is None or waiter.epoch != epoch:
|
|
return False, "本轮已取消"
|
|
future = waiter.future
|
|
try:
|
|
# shield:超时或断流时不把 Future 一起取消,便于区分迟到回执
|
|
return await asyncio.wait_for(asyncio.shield(future), self._timeout)
|
|
except asyncio.TimeoutError:
|
|
if not future.done():
|
|
future.set_result((False, "前端未回执"))
|
|
return False, "前端未回执"
|
|
finally:
|
|
current = self._waiters.get(key)
|
|
if current is not None and current.future is future:
|
|
self._waiters.pop(key, None)
|
|
|
|
def submit(self, thread_id: str, tool_call_id: str, ok: bool, message: str) -> bool:
|
|
"""对上当前代次的等待则唤醒。迟到或未知 id 返回 False。"""
|
|
key = (thread_id, tool_call_id)
|
|
waiter = self._waiters.get(key)
|
|
epoch = self._epoch.get(thread_id)
|
|
if waiter is None or epoch is None or waiter.epoch != epoch or waiter.future.done():
|
|
return False
|
|
waiter.future.set_result((bool(ok), message or ""))
|
|
return True
|
|
|
|
def _settle(
|
|
self,
|
|
thread_id: str,
|
|
*,
|
|
only_epoch: int | None,
|
|
keep_epoch: int | None,
|
|
message: str,
|
|
) -> None:
|
|
for key, waiter in list(self._waiters.items()):
|
|
if key[0] != thread_id:
|
|
continue
|
|
if only_epoch is not None and waiter.epoch != only_epoch:
|
|
continue
|
|
if keep_epoch is not None and waiter.epoch == keep_epoch:
|
|
continue
|
|
self._waiters.pop(key, None)
|
|
if not waiter.future.done():
|
|
waiter.future.set_result((False, message))
|
|
|
|
|
|
_gate: ClientToolGate | None = None
|
|
|
|
|
|
def get_client_tool_gate() -> ClientToolGate:
|
|
global _gate
|
|
if _gate is None:
|
|
_gate = ClientToolGate()
|
|
return _gate
|
|
|
|
|
|
class BoundClientToolTurn:
|
|
"""绑定到一次 stream_chat 的代次。"""
|
|
|
|
def __init__(self, gate: ClientToolGate, thread_id: str, epoch: int) -> None:
|
|
self._gate = gate
|
|
self._thread_id = thread_id
|
|
self._epoch = epoch
|
|
|
|
def arm(self, tool_call_id: str) -> None:
|
|
self._gate.arm(self._thread_id, self._epoch, tool_call_id)
|
|
|
|
async def wait_result(self, tool_call_id: str) -> str:
|
|
ok, message = await self._gate.wait(self._thread_id, self._epoch, tool_call_id)
|
|
return format_client_tool_result(ok, message)
|