mirror of
https://gitee.com/qqtt-ah/ecom-dmb.git
synced 2026-11-24 13:09:19 +08:00
feat: 发布页前端工具改为等待浏览器回执后再继续模型
This commit is contained in:
@@ -1,4 +1,8 @@
|
||||
"""发布场景前端写工具:读快照注入 system;写工具由 streamer 推 client_tool 事件。"""
|
||||
"""发布场景前端写工具。
|
||||
|
||||
只向模型注册 schema。真正写入发生在浏览器;streamer 推 client_tool 后等待回执,
|
||||
不把这里的占位返回值当成 ToolMessage。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
|
||||
@@ -8,9 +8,11 @@ from fastapi import APIRouter, Depends, HTTPException
|
||||
from pydantic import BaseModel, Field
|
||||
from sse_starlette.sse import EventSourceResponse
|
||||
|
||||
from api.deps import chat_service, current_actor
|
||||
from api.deps import chat_service, current_actor, session_service
|
||||
from api.response import ok
|
||||
from application.chat_service import ChatService
|
||||
from application.client_tool_gate import get_client_tool_gate
|
||||
from application.session_service import SessionService
|
||||
from domain.models import Actor
|
||||
|
||||
router = APIRouter(prefix="/sessions", tags=["chat"])
|
||||
@@ -22,6 +24,14 @@ class ChatBody(BaseModel):
|
||||
formSnapshot: dict | None = None
|
||||
|
||||
|
||||
class ClientToolResultBody(BaseModel):
|
||||
"""浏览器执行 ui_set_* 后的真实结果,唤醒挂起的工具轮。"""
|
||||
|
||||
toolCallId: str = Field(min_length=1, max_length=200)
|
||||
ok: bool
|
||||
message: str = Field(default="", max_length=2000)
|
||||
|
||||
|
||||
@router.get("/{thread_id}/messages")
|
||||
async def list_messages(
|
||||
thread_id: str,
|
||||
@@ -115,3 +125,24 @@ async def chat_stream(
|
||||
},
|
||||
ping=15,
|
||||
)
|
||||
|
||||
|
||||
@router.post("/{thread_id}/client-tool-results")
|
||||
async def submit_client_tool_result(
|
||||
thread_id: str,
|
||||
body: ClientToolResultBody,
|
||||
actor: Actor = Depends(current_actor),
|
||||
sessions: SessionService = Depends(session_service),
|
||||
):
|
||||
"""前端工具回执。对上当前轮等待则 accepted=true;迟到或未知 id 仍 200,避免打断页面。"""
|
||||
try:
|
||||
await sessions.require_owned(actor, thread_id)
|
||||
except LookupError as e:
|
||||
raise HTTPException(status_code=404, detail=str(e)) from e
|
||||
accepted = get_client_tool_gate().submit(
|
||||
thread_id,
|
||||
body.toolCallId.strip(),
|
||||
body.ok,
|
||||
body.message,
|
||||
)
|
||||
return ok({"accepted": accepted})
|
||||
|
||||
@@ -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 → "
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from abc import ABC, abstractmethod
|
||||
from typing import Any, AsyncIterator
|
||||
from typing import Any, AsyncIterator, Protocol
|
||||
|
||||
from domain.models import (
|
||||
ChatMessage,
|
||||
@@ -144,6 +144,14 @@ class LlmProtocolCapabilityCache(ABC):
|
||||
) -> None: ...
|
||||
|
||||
|
||||
class ClientToolTurn(Protocol):
|
||||
"""一轮聊天里前端工具的回执等待:先 arm 再推 SSE,再 wait_result。"""
|
||||
|
||||
def arm(self, tool_call_id: str) -> None: ...
|
||||
|
||||
async def wait_result(self, tool_call_id: str) -> str: ...
|
||||
|
||||
|
||||
class ChatStreamer(ABC):
|
||||
"""流式生成助手回复。"""
|
||||
|
||||
@@ -158,4 +166,5 @@ class ChatStreamer(ABC):
|
||||
tools: list[Any] | None = None,
|
||||
max_tool_result_chars: int = 4000,
|
||||
previous_response_id: str | None = None,
|
||||
client_tool_turn: ClientToolTurn | None = None,
|
||||
) -> AsyncIterator[StreamEvent]: ...
|
||||
|
||||
@@ -22,7 +22,7 @@ from domain.models import (
|
||||
MessageRole,
|
||||
StreamEvent,
|
||||
)
|
||||
from domain.ports import ChatStreamer, LlmProtocolCapabilityCache
|
||||
from domain.ports import ChatStreamer, ClientToolTurn, LlmProtocolCapabilityCache
|
||||
from infrastructure.llm.api_style import (
|
||||
ProtocolAttempt,
|
||||
classify_protocol_error,
|
||||
@@ -55,6 +55,7 @@ class OpenAICompatibleStreamer(ChatStreamer):
|
||||
tools: list[Any] | None = None,
|
||||
max_tool_result_chars: int = 8000,
|
||||
previous_response_id: str | None = None,
|
||||
client_tool_turn: ClientToolTurn | None = None,
|
||||
) -> AsyncIterator[StreamEvent]:
|
||||
chain_id = (previous_response_id or "").strip() or None
|
||||
style = normalize_api_style(llm.api_style)
|
||||
@@ -93,6 +94,7 @@ class OpenAICompatibleStreamer(ChatStreamer):
|
||||
use_responses=attempt.use_responses,
|
||||
use_store=attempt.use_store,
|
||||
previous_response_id=use_chain_id,
|
||||
client_tool_turn=client_tool_turn,
|
||||
):
|
||||
if event.kind == "token" and event.text:
|
||||
yielded_any = True
|
||||
@@ -302,6 +304,7 @@ class OpenAICompatibleStreamer(ChatStreamer):
|
||||
use_responses: bool,
|
||||
use_store: bool,
|
||||
previous_response_id: str | None,
|
||||
client_tool_turn: ClientToolTurn | None = None,
|
||||
) -> AsyncIterator[StreamEvent]:
|
||||
kwargs: dict[str, Any] = {
|
||||
"api_key": llm.api_key,
|
||||
@@ -417,24 +420,32 @@ class OpenAICompatibleStreamer(ChatStreamer):
|
||||
name = tc.get("name") or ""
|
||||
args = tc.get("args") or {}
|
||||
call_id = tc.get("id") or name
|
||||
if is_client_tool_name(name):
|
||||
yield StreamEvent.client_tool(
|
||||
tool_call_id=str(call_id),
|
||||
name=name,
|
||||
args=args if isinstance(args, dict) else {},
|
||||
label=tool_status_label(name),
|
||||
)
|
||||
tool = tool_map.get(name)
|
||||
try:
|
||||
if tool is None:
|
||||
result = f"未知工具: {name}"
|
||||
if is_client_tool_name(name):
|
||||
# 占位函数不代表页面已写入;先登记等待再推事件,回执到达后才进 ToolMessage
|
||||
tool_args = args if isinstance(args, dict) else {}
|
||||
if client_tool_turn is None:
|
||||
result = "写入失败:前端回执通道未配置"
|
||||
else:
|
||||
client_tool_turn.arm(str(call_id))
|
||||
yield StreamEvent.client_tool(
|
||||
tool_call_id=str(call_id),
|
||||
name=name,
|
||||
args=tool_args,
|
||||
label=tool_status_label(name),
|
||||
)
|
||||
result = await client_tool_turn.wait_result(str(call_id))
|
||||
else:
|
||||
raw = await tool.ainvoke(args)
|
||||
result = (
|
||||
raw
|
||||
if isinstance(raw, str)
|
||||
else json.dumps(raw, ensure_ascii=False, default=str)
|
||||
)
|
||||
tool = tool_map.get(name)
|
||||
if tool is None:
|
||||
result = f"未知工具: {name}"
|
||||
else:
|
||||
raw = await tool.ainvoke(args)
|
||||
result = (
|
||||
raw
|
||||
if isinstance(raw, str)
|
||||
else json.dumps(raw, ensure_ascii=False, default=str)
|
||||
)
|
||||
except Exception as e: # noqa: BLE001
|
||||
result = f"工具执行失败: {e}"
|
||||
messages.append(
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
"""前端工具回执门闩:代次隔离、超时与迟到提交。"""
|
||||
|
||||
import asyncio
|
||||
|
||||
from application.client_tool_gate import (
|
||||
ClientToolGate,
|
||||
format_client_tool_result,
|
||||
)
|
||||
|
||||
|
||||
def test_format_failure_prefix():
|
||||
assert format_client_tool_result(True, "已写入标题") == "已写入标题"
|
||||
assert format_client_tool_result(False, "标题为空").startswith("写入失败")
|
||||
|
||||
|
||||
def test_submit_wakes_current_epoch_only():
|
||||
gate = ClientToolGate(timeout_seconds=1)
|
||||
|
||||
async def scenario():
|
||||
epoch = gate.begin("t1")
|
||||
gate.arm("t1", epoch, "call-1")
|
||||
late = gate.begin("t1")
|
||||
assert late != epoch
|
||||
assert gate.submit("t1", "call-1", True, "旧轮") is False
|
||||
gate.arm("t1", late, "call-2")
|
||||
assert gate.submit("t1", "call-2", True, "已写入标题") is True
|
||||
ok, message = await gate.wait("t1", late, "call-2")
|
||||
assert ok is True
|
||||
assert message == "已写入标题"
|
||||
assert gate.submit("t1", "call-2", True, "再次") is False
|
||||
|
||||
asyncio.run(scenario())
|
||||
|
||||
|
||||
def test_timeout_when_no_submit():
|
||||
gate = ClientToolGate(timeout_seconds=0.05)
|
||||
|
||||
async def scenario():
|
||||
epoch = gate.begin("t2")
|
||||
gate.arm("t2", epoch, "call")
|
||||
ok, message = await gate.wait("t2", epoch, "call")
|
||||
assert ok is False
|
||||
assert message == "前端未回执"
|
||||
|
||||
asyncio.run(scenario())
|
||||
Reference in New Issue
Block a user