mirror of
https://gitee.com/qqtt-ah/ecom-dmb.git
synced 2026-11-24 09:49:19 +08:00
feat: 发布页前端工具改为等待浏览器回执后再继续模型
This commit is contained in:
@@ -6,6 +6,7 @@ from datetime import datetime
|
||||
from typing import AsyncIterator
|
||||
|
||||
from agent.runtime import load_tools_for_turn
|
||||
from application.client_tool_gate import BoundClientToolTurn, get_client_tool_gate
|
||||
from application.context_window import resolve_context_window, trim_history_to_budget
|
||||
from application.llm_settings_service import LlmRuntimeService
|
||||
from application.memory_service import MemoryService
|
||||
@@ -154,21 +155,28 @@ class ChatService:
|
||||
|
||||
parts: list[str] = []
|
||||
new_response_id: str | None = None
|
||||
async for event in self._streamer.stream_reply(
|
||||
llm=llm,
|
||||
history=history,
|
||||
user_text=text,
|
||||
system_prompt=system_prompt,
|
||||
tools=tools or None,
|
||||
max_tool_result_chars=max_tool_chars,
|
||||
previous_response_id=chain_id,
|
||||
):
|
||||
if event.kind == "response_chain" and event.response_id:
|
||||
new_response_id = event.response_id
|
||||
continue
|
||||
if event.kind == "token" and event.text:
|
||||
parts.append(event.text)
|
||||
yield event
|
||||
gate = get_client_tool_gate()
|
||||
epoch = gate.begin(thread_id)
|
||||
turn = BoundClientToolTurn(gate, thread_id, epoch)
|
||||
try:
|
||||
async for event in self._streamer.stream_reply(
|
||||
llm=llm,
|
||||
history=history,
|
||||
user_text=text,
|
||||
system_prompt=system_prompt,
|
||||
tools=tools or None,
|
||||
max_tool_result_chars=max_tool_chars,
|
||||
previous_response_id=chain_id,
|
||||
client_tool_turn=turn,
|
||||
):
|
||||
if event.kind == "response_chain" and event.response_id:
|
||||
new_response_id = event.response_id
|
||||
continue
|
||||
if event.kind == "token" and event.text:
|
||||
parts.append(event.text)
|
||||
yield event
|
||||
finally:
|
||||
gate.end(thread_id, epoch)
|
||||
|
||||
full = "".join(parts).strip() or "(模型未返回内容)"
|
||||
a_seq = await self._messages.next_seq(actor.company_id, actor.user_id, thread_id)
|
||||
|
||||
@@ -0,0 +1,127 @@
|
||||
"""前端工具回执门闩:进程内按会话代次等待,供 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)
|
||||
@@ -34,6 +34,7 @@ _PUBLISH_SYSTEM = (
|
||||
"你是电商 DMB 的拼多多商品发布助手,帮助用户在系统草稿里完善标题、规格轴、属性与价格等。"
|
||||
"当前表单快照已在下方【当前发布表单】中给出,直接根据快照改表,不要再去「读取」表单。"
|
||||
"改表单必须调用 ui_set_goods_name / ui_set_goods_desc / ui_set_spec_axes,不要只口头说已修改。"
|
||||
"这些工具的返回值是页面真实写入结果;以「写入失败」开头时说明原因,不要声称已经改好。"
|
||||
"查内部商品/SKU:catalog_search、catalog_sku_detail(按 skuCode)。"
|
||||
"查已同步的拼多多渠道商品:pdd_goods_search、pdd_goods_detail(只查本地库)。"
|
||||
"常见流程:根据表单已有 SKU 编码 → catalog_sku_detail / pdd_goods_search → "
|
||||
|
||||
Reference in New Issue
Block a user