mirror of
https://gitee.com/qqtt-ah/ecom-dmb.git
synced 2026-11-23 23:19:19 +08:00
feat: 拼多多发布页接入场景智能体与表单改写工具
This commit is contained in:
@@ -1,4 +1,4 @@
|
||||
"""Agent 编排:工具装载与(预留)图运行时;不写 Mongo。"""
|
||||
"""Agent 编排:按会话 scene 装载工具。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -6,7 +6,7 @@ from typing import Any
|
||||
|
||||
from application.memory_service import MemoryService
|
||||
from config.settings import Settings
|
||||
from domain.models import Actor
|
||||
from domain.models import SCENE_ECOM_GOODS_PUBLISH, SCENE_GENERAL, Actor
|
||||
|
||||
|
||||
async def load_tools_for_turn(
|
||||
@@ -14,13 +14,43 @@ async def load_tools_for_turn(
|
||||
*,
|
||||
actor: Actor,
|
||||
memory: MemoryService,
|
||||
scene: str = SCENE_GENERAL,
|
||||
client_tools: list[Any] | None = None,
|
||||
) -> list[Any]:
|
||||
"""本轮可用工具 = builtin + 记忆 search/load/save + MCP。"""
|
||||
"""general:builtin + memory + 全部 MCP;发布场景:builtin + 目录/拼多多 MCP + 前端 ui_ 工具。"""
|
||||
from agent.tools.builtin import builtin_tools
|
||||
from agent.tools.memory import memory_tools
|
||||
from infrastructure.mcp.client import load_mcp_tools
|
||||
|
||||
scene_value = (scene or SCENE_GENERAL).strip() or SCENE_GENERAL
|
||||
tools: list[Any] = [*builtin_tools()]
|
||||
|
||||
if scene_value == SCENE_ECOM_GOODS_PUBLISH:
|
||||
mcp_tools = await load_mcp_tools(
|
||||
settings,
|
||||
company_id=actor.company_id,
|
||||
user_id=actor.user_id,
|
||||
)
|
||||
# 发布场景:目录 + 拼多多渠道;不挂经营 BI
|
||||
mcp_tools = [
|
||||
t
|
||||
for t in mcp_tools
|
||||
if _tool_name(t).startswith(("catalog_", "pdd_")) or _tool_name(t) == "mcp_ping"
|
||||
]
|
||||
tools.extend(mcp_tools)
|
||||
if client_tools:
|
||||
tools.extend(client_tools)
|
||||
return tools
|
||||
|
||||
tools.extend(memory_tools(memory, actor))
|
||||
mcp_tools = await load_mcp_tools(
|
||||
settings, company_id=actor.company_id, user_id=actor.user_id
|
||||
)
|
||||
return [*builtin_tools(), *memory_tools(memory, actor), *mcp_tools]
|
||||
tools.extend(mcp_tools)
|
||||
if client_tools:
|
||||
tools.extend(client_tools)
|
||||
return tools
|
||||
|
||||
|
||||
def _tool_name(tool: Any) -> str:
|
||||
return str(getattr(tool, "name", None) or "")
|
||||
|
||||
@@ -8,6 +8,13 @@ _LABELS: dict[str, str] = {
|
||||
"memory_save": "保存记忆",
|
||||
"get_current_time": "确认业务日期",
|
||||
"catalog_search": "查找店铺/商品",
|
||||
"catalog_sku_detail": "查找内部规格",
|
||||
"pdd_goods_search": "查找拼多多商品",
|
||||
"pdd_goods_detail": "读取拼多多商品",
|
||||
"ui_get_publish_snapshot": "读取发布表单",
|
||||
"ui_set_goods_name": "填写商品标题",
|
||||
"ui_set_goods_desc": "填写商品描述",
|
||||
"ui_set_spec_axes": "设置规格轴",
|
||||
}
|
||||
|
||||
|
||||
@@ -19,8 +26,10 @@ def tool_status_label(name: str) -> str:
|
||||
if key in _LABELS:
|
||||
return _LABELS[key]
|
||||
lower = key.lower()
|
||||
if lower.startswith("catalog_"):
|
||||
return "查找店铺/商品"
|
||||
if lower.startswith("ui_"):
|
||||
return "编辑发布表单"
|
||||
if lower.startswith("catalog_") or lower.startswith("pdd_"):
|
||||
return "查找商品信息"
|
||||
if "order" in lower or "sales" in lower or "bi_" in lower or "stat" in lower:
|
||||
return "查询经营数据"
|
||||
return "查询经营数据"
|
||||
return "处理中"
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
"""发布场景前端工具:读快照用请求体注入;写工具由 streamer 推 client_tool 事件。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from typing import Any
|
||||
|
||||
from langchain_core.tools import StructuredTool
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
|
||||
class _EmptyArgs(BaseModel):
|
||||
pass
|
||||
|
||||
|
||||
class SetGoodsNameArgs(BaseModel):
|
||||
goodsName: str = Field(description="商品标题,建议 60 字内")
|
||||
|
||||
|
||||
class SetGoodsDescArgs(BaseModel):
|
||||
goodsDesc: str = Field(description="商品描述纯文本")
|
||||
|
||||
|
||||
class SpecAxis(BaseModel):
|
||||
name: str = Field(description="规格维名称,如 颜色、尺码")
|
||||
values: list[str] = Field(description="该维下的规格值列表")
|
||||
|
||||
|
||||
class SetSpecAxesArgs(BaseModel):
|
||||
axes: list[SpecAxis] = Field(
|
||||
description="完整规格轴;将替换表单现有规格轴并重建 SKU 行"
|
||||
)
|
||||
|
||||
|
||||
def build_publish_client_tools(
|
||||
*,
|
||||
form_snapshot: dict[str, Any] | None,
|
||||
) -> list[Any]:
|
||||
def get_snapshot() -> str:
|
||||
return json.dumps(form_snapshot or {}, ensure_ascii=False, default=str)
|
||||
|
||||
def set_goods_name(goodsName: str) -> str:
|
||||
return f"已请求写入标题:{goodsName}"
|
||||
|
||||
def set_goods_desc(goodsDesc: str) -> str:
|
||||
return "已请求写入商品描述"
|
||||
|
||||
def set_spec_axes(axes: list[Any]) -> str:
|
||||
n = len(axes or [])
|
||||
return f"已请求写入 {n} 个规格维,页面将重建 SKU 行"
|
||||
|
||||
return [
|
||||
StructuredTool.from_function(
|
||||
func=get_snapshot,
|
||||
name="ui_get_publish_snapshot",
|
||||
description="读取当前发布表单快照:标题、描述、类目、规格轴、SKU 行(含商家编码)等。改表前应先调用。",
|
||||
args_schema=_EmptyArgs,
|
||||
),
|
||||
StructuredTool.from_function(
|
||||
func=set_goods_name,
|
||||
name="ui_set_goods_name",
|
||||
description="写入商品标题到发布表单。",
|
||||
args_schema=SetGoodsNameArgs,
|
||||
),
|
||||
StructuredTool.from_function(
|
||||
func=set_goods_desc,
|
||||
name="ui_set_goods_desc",
|
||||
description="写入商品描述到发布表单。",
|
||||
args_schema=SetGoodsDescArgs,
|
||||
),
|
||||
StructuredTool.from_function(
|
||||
func=set_spec_axes,
|
||||
name="ui_set_spec_axes",
|
||||
description="设置规格轴(维名+值列表)。页面会按笛卡尔积重建 SKU 行。",
|
||||
args_schema=SetSpecAxesArgs,
|
||||
),
|
||||
]
|
||||
|
||||
|
||||
def is_client_tool_name(name: str) -> bool:
|
||||
return (name or "").startswith("ui_")
|
||||
@@ -18,6 +18,8 @@ router = APIRouter(prefix="/sessions", tags=["chat"])
|
||||
|
||||
class ChatBody(BaseModel):
|
||||
content: str = Field(min_length=1, max_length=20000)
|
||||
# 发布场景:当前表单快照,供 ui_get_publish_snapshot
|
||||
formSnapshot: dict | None = None
|
||||
|
||||
|
||||
@router.get("/{thread_id}/messages")
|
||||
@@ -57,7 +59,12 @@ async def chat_stream(
|
||||
|
||||
async def gen():
|
||||
try:
|
||||
async for event in svc.stream_chat(actor, thread_id, body.content):
|
||||
async for event in svc.stream_chat(
|
||||
actor,
|
||||
thread_id,
|
||||
body.content,
|
||||
form_snapshot=body.formSnapshot,
|
||||
):
|
||||
if event.kind == "token" and event.text:
|
||||
yield {
|
||||
"event": "token",
|
||||
@@ -75,6 +82,19 @@ async def chat_stream(
|
||||
ensure_ascii=False,
|
||||
),
|
||||
}
|
||||
elif event.kind == "client_tool":
|
||||
yield {
|
||||
"event": "client_tool",
|
||||
"data": json.dumps(
|
||||
{
|
||||
"toolCallId": event.tool_call_id,
|
||||
"name": event.name,
|
||||
"args": event.args or {},
|
||||
"label": event.label,
|
||||
},
|
||||
ensure_ascii=False,
|
||||
),
|
||||
}
|
||||
yield {"event": "done", "data": "{}"}
|
||||
except LookupError as e:
|
||||
yield {"event": "error", "data": json.dumps({"message": str(e)}, ensure_ascii=False)}
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from api.deps import current_actor, session_service
|
||||
@@ -17,6 +17,10 @@ class CreateSessionBody(BaseModel):
|
||||
title: str | None = None
|
||||
llmProviderId: int | None = None
|
||||
llmModel: str | None = None
|
||||
scene: str | None = None
|
||||
sceneRef: str | None = None
|
||||
# 同 scene+sceneRef 已有活跃会话则复用(发布草稿一会话)
|
||||
reuseBySceneRef: bool = False
|
||||
|
||||
|
||||
class PatchSessionBody(BaseModel):
|
||||
@@ -30,6 +34,8 @@ def _session_vo(s) -> dict:
|
||||
"threadId": s.thread_id,
|
||||
"title": s.title,
|
||||
"status": s.status.value,
|
||||
"scene": s.scene or "general",
|
||||
"sceneRef": s.scene_ref,
|
||||
"llmProviderId": s.llm_provider_id,
|
||||
"llmModel": s.llm_model,
|
||||
"createdAt": s.created_at.isoformat() + "Z",
|
||||
@@ -40,10 +46,11 @@ def _session_vo(s) -> dict:
|
||||
|
||||
@router.get("")
|
||||
async def list_sessions(
|
||||
scene: str | None = Query(default="general"),
|
||||
actor: Actor = Depends(current_actor),
|
||||
svc: SessionService = Depends(session_service),
|
||||
):
|
||||
rows = await svc.list_mine(actor)
|
||||
rows = await svc.list_mine(actor, scene=scene)
|
||||
return ok({"items": [_session_vo(s) for s in rows]})
|
||||
|
||||
|
||||
@@ -53,11 +60,19 @@ async def create_session(
|
||||
actor: Actor = Depends(current_actor),
|
||||
svc: SessionService = Depends(session_service),
|
||||
):
|
||||
scene = (body.scene or "general").strip() or "general"
|
||||
ref = (body.sceneRef or "").strip() or None
|
||||
if body.reuseBySceneRef and ref:
|
||||
existing = await svc.find_by_scene_ref(actor, scene=scene, scene_ref=ref)
|
||||
if existing is not None:
|
||||
return ok(_session_vo(existing))
|
||||
s = await svc.create(
|
||||
actor,
|
||||
body.title,
|
||||
llm_provider_id=body.llmProviderId,
|
||||
llm_model=body.llmModel,
|
||||
scene=scene,
|
||||
scene_ref=ref,
|
||||
)
|
||||
return ok(_session_vo(s))
|
||||
|
||||
|
||||
@@ -45,13 +45,19 @@ class ChatService:
|
||||
)
|
||||
|
||||
async def stream_chat(
|
||||
self, actor: Actor, thread_id: str, content: str
|
||||
self,
|
||||
actor: Actor,
|
||||
thread_id: str,
|
||||
content: str,
|
||||
*,
|
||||
form_snapshot: dict | None = None,
|
||||
) -> AsyncIterator[StreamEvent]:
|
||||
text = (content or "").strip()
|
||||
if not text:
|
||||
raise ValueError("消息不能为空")
|
||||
|
||||
session = await self._sessions.require_owned(actor, thread_id)
|
||||
scene = session.scene or "general"
|
||||
llm = await self._llm_runtime.resolve_runtime(
|
||||
actor.company_id,
|
||||
provider_id=session.llm_provider_id,
|
||||
@@ -67,18 +73,33 @@ class ChatService:
|
||||
changed = True
|
||||
if changed:
|
||||
await self._session_repo.update(session)
|
||||
just_saved = await self._memory.maybe_capture_from_user(
|
||||
actor, thread_id=thread_id, text=text
|
||||
)
|
||||
memory_count = await self._memory.count_active(actor)
|
||||
|
||||
just_saved = None
|
||||
memory_count = 0
|
||||
if scene == "general":
|
||||
just_saved = await self._memory.maybe_capture_from_user(
|
||||
actor, thread_id=thread_id, text=text
|
||||
)
|
||||
memory_count = await self._memory.count_active(actor)
|
||||
|
||||
system_prompt = build_system_prompt(
|
||||
memory_count=memory_count,
|
||||
memory_just_saved=just_saved,
|
||||
scene=scene,
|
||||
)
|
||||
|
||||
client_tools = None
|
||||
if scene == "ecom_goods_publish":
|
||||
from agent.tools.publish_ui import build_publish_client_tools
|
||||
|
||||
client_tools = build_publish_client_tools(form_snapshot=form_snapshot)
|
||||
|
||||
tools = await load_tools_for_turn(
|
||||
self._settings,
|
||||
actor=actor,
|
||||
memory=self._memory,
|
||||
scene=scene,
|
||||
client_tools=client_tools,
|
||||
)
|
||||
|
||||
raw_history = await self._messages.list_recent(
|
||||
|
||||
@@ -25,6 +25,9 @@ class SessionService:
|
||||
title: str | None = None,
|
||||
llm_provider_id: int | None = None,
|
||||
llm_model: str | None = None,
|
||||
*,
|
||||
scene: str | None = None,
|
||||
scene_ref: str | None = None,
|
||||
) -> Session:
|
||||
now = datetime.utcnow()
|
||||
model = (llm_model or "").strip() or None
|
||||
@@ -40,12 +43,16 @@ class SessionService:
|
||||
provider_id = rt.provider_id if rt.provider_id is not None else provider_id
|
||||
except Exception:
|
||||
pass
|
||||
scene_value = (scene or "general").strip() or "general"
|
||||
ref = (scene_ref or "").strip() or None
|
||||
session = Session(
|
||||
thread_id=str(uuid.uuid4()),
|
||||
company_id=actor.company_id,
|
||||
user_id=actor.user_id,
|
||||
title=(title or "新对话").strip() or "新对话",
|
||||
status=SessionStatus.ACTIVE,
|
||||
scene=scene_value,
|
||||
scene_ref=ref,
|
||||
llm_provider_id=provider_id,
|
||||
llm_model=model,
|
||||
created_at=now,
|
||||
@@ -53,8 +60,23 @@ class SessionService:
|
||||
)
|
||||
return await self._sessions.create(session)
|
||||
|
||||
async def list_mine(self, actor: Actor) -> list[Session]:
|
||||
return await self._sessions.list_active(actor.company_id, actor.user_id)
|
||||
async def list_mine(
|
||||
self, actor: Actor, *, scene: str | None = None
|
||||
) -> list[Session]:
|
||||
return await self._sessions.list_active(
|
||||
actor.company_id, actor.user_id, scene=scene
|
||||
)
|
||||
|
||||
async def find_by_scene_ref(
|
||||
self, actor: Actor, *, scene: str, scene_ref: str
|
||||
) -> Session | None:
|
||||
"""同一 scene_ref 复用已有活跃会话(一草稿一会话)。"""
|
||||
return await self._sessions.find_active_by_scene_ref(
|
||||
actor.company_id,
|
||||
actor.user_id,
|
||||
scene=scene,
|
||||
scene_ref=scene_ref,
|
||||
)
|
||||
|
||||
async def require_owned(self, actor: Actor, thread_id: str) -> Session:
|
||||
session = await self._sessions.get(actor.company_id, actor.user_id, thread_id)
|
||||
|
||||
@@ -2,6 +2,8 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from domain.models import SCENE_ECOM_GOODS_PUBLISH, SCENE_GENERAL
|
||||
|
||||
_BASE_SYSTEM = (
|
||||
"你是电商 DMB 系统的经营助手。回答简洁、可执行、结论先行。"
|
||||
"需要经营数据时优先调用可用工具。"
|
||||
@@ -24,12 +26,31 @@ _BASE_SYSTEM = (
|
||||
"若工具失败或无权限,请说明原因并给出可操作建议。"
|
||||
)
|
||||
|
||||
_PUBLISH_SYSTEM = (
|
||||
"你是电商 DMB 的拼多多商品发布助手,帮助用户在系统草稿里完善标题、规格轴、属性与价格等。"
|
||||
"当前表单在浏览器里;改表单必须调用 ui_ 开头的前端工具,不要只口头说已修改。"
|
||||
"查内部商品/SKU:catalog_search、catalog_sku_detail(按 skuCode)。"
|
||||
"查已同步的拼多多渠道商品:pdd_goods_search、pdd_goods_detail(只查本地库)。"
|
||||
"常见流程:根据表单已有 SKU 编码 → catalog_sku_detail / pdd_goods_search → "
|
||||
"挑选或按用户指定模仿某条渠道商品 → 生成标题并用 ui_set_goods_name 写入;"
|
||||
"规格只通过 ui_set_spec_axes 写规格轴,页面会自动笛卡尔积重建 SKU 行。"
|
||||
"用户未指定时,可自行选择最接近的渠道商品模仿,或结合内部商品信息自由发挥;"
|
||||
"用户指定风格或指定模仿哪条时以用户为准。"
|
||||
"一期不要处理图片上传或改图。"
|
||||
"禁止向用户索要或复述数字 ID;多条命中时用名称/编码说明。"
|
||||
"回答简洁;工具失败时说明原因与可操作建议。"
|
||||
)
|
||||
|
||||
|
||||
def build_system_prompt(
|
||||
*,
|
||||
memory_count: int = 0,
|
||||
memory_just_saved: str | None = None,
|
||||
scene: str = SCENE_GENERAL,
|
||||
) -> str:
|
||||
if (scene or SCENE_GENERAL).strip() == SCENE_ECOM_GOODS_PUBLISH:
|
||||
return _PUBLISH_SYSTEM
|
||||
|
||||
system = _BASE_SYSTEM
|
||||
if memory_count > 0:
|
||||
system += (
|
||||
|
||||
@@ -58,6 +58,10 @@ class Session:
|
||||
title: str = "新对话"
|
||||
status: SessionStatus = SessionStatus.ACTIVE
|
||||
summary: str | None = None
|
||||
# general=经营助手;ecom_goods_publish=拼多多商品发布编辑
|
||||
scene: str = "general"
|
||||
# 场景业务键,如发布草稿 draftId
|
||||
scene_ref: str | None = None
|
||||
# 会话选用的提供商 + 模型(同名 model 靠 provider 消歧)
|
||||
llm_provider_id: int | None = None
|
||||
llm_model: str | None = None
|
||||
@@ -66,6 +70,10 @@ class Session:
|
||||
last_message_at: datetime | None = None
|
||||
|
||||
|
||||
SCENE_GENERAL = "general"
|
||||
SCENE_ECOM_GOODS_PUBLISH = "ecom_goods_publish"
|
||||
|
||||
|
||||
@dataclass
|
||||
class ChatMessage:
|
||||
company_id: int
|
||||
@@ -114,13 +122,15 @@ class LlmRuntimeConfig:
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class StreamEvent:
|
||||
"""流式片段:正文 token 或工具状态(工具状态不进落库正文)。"""
|
||||
"""流式片段:正文 token、服务端工具状态、或需前端执行的 client tool。"""
|
||||
|
||||
kind: str # token | tool
|
||||
kind: str # token | tool | client_tool | pending_client_tools
|
||||
text: str | None = None
|
||||
phase: str | None = None # start | end
|
||||
name: str | None = None
|
||||
label: str | None = None
|
||||
tool_call_id: str | None = None
|
||||
args: dict | None = None
|
||||
|
||||
@staticmethod
|
||||
def token(text: str) -> StreamEvent:
|
||||
@@ -129,3 +139,23 @@ class StreamEvent:
|
||||
@staticmethod
|
||||
def tool(*, phase: str, name: str, label: str) -> StreamEvent:
|
||||
return StreamEvent(kind="tool", phase=phase, name=name, label=label)
|
||||
|
||||
@staticmethod
|
||||
def client_tool(
|
||||
*,
|
||||
tool_call_id: str,
|
||||
name: str,
|
||||
args: dict | None,
|
||||
label: str,
|
||||
) -> StreamEvent:
|
||||
return StreamEvent(
|
||||
kind="client_tool",
|
||||
tool_call_id=tool_call_id,
|
||||
name=name,
|
||||
args=args or {},
|
||||
label=label,
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def pending_client_tools() -> StreamEvent:
|
||||
return StreamEvent(kind="pending_client_tools")
|
||||
|
||||
@@ -16,7 +16,24 @@ class SessionRepository(ABC):
|
||||
async def get(self, company_id: int, user_id: str, thread_id: str) -> Session | None: ...
|
||||
|
||||
@abstractmethod
|
||||
async def list_active(self, company_id: int, user_id: str, limit: int = 50) -> list[Session]: ...
|
||||
async def list_active(
|
||||
self,
|
||||
company_id: int,
|
||||
user_id: str,
|
||||
limit: int = 50,
|
||||
*,
|
||||
scene: str | None = None,
|
||||
) -> list[Session]: ...
|
||||
|
||||
@abstractmethod
|
||||
async def find_active_by_scene_ref(
|
||||
self,
|
||||
company_id: int,
|
||||
user_id: str,
|
||||
*,
|
||||
scene: str,
|
||||
scene_ref: str,
|
||||
) -> Session | None: ...
|
||||
|
||||
@abstractmethod
|
||||
async def update(self, session: Session) -> Session: ...
|
||||
|
||||
@@ -9,6 +9,7 @@ from langchain_core.messages import AIMessage, HumanMessage, SystemMessage, Tool
|
||||
from langchain_openai import ChatOpenAI
|
||||
|
||||
from agent.tools.labels import tool_status_label
|
||||
from agent.tools.publish_ui import is_client_tool_name
|
||||
from domain.models import ChatMessage, LlmRuntimeConfig, MessageRole, StreamEvent
|
||||
from domain.ports import ChatStreamer
|
||||
|
||||
@@ -88,6 +89,13 @@ 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:
|
||||
|
||||
@@ -21,7 +21,10 @@ async def ensure_indexes(db: AsyncIOMotorDatabase) -> None:
|
||||
[("company_id", 1), ("user_id", 1), ("thread_id", 1)], unique=True
|
||||
)
|
||||
await db.agent_sessions.create_index(
|
||||
[("company_id", 1), ("user_id", 1), ("status", 1), ("updated_at", -1)]
|
||||
[("company_id", 1), ("user_id", 1), ("status", 1), ("scene", 1), ("updated_at", -1)]
|
||||
)
|
||||
await db.agent_sessions.create_index(
|
||||
[("company_id", 1), ("user_id", 1), ("scene", 1), ("scene_ref", 1), ("status", 1)]
|
||||
)
|
||||
await db.agent_messages.create_index(
|
||||
[("company_id", 1), ("user_id", 1), ("thread_id", 1), ("seq", 1)]
|
||||
|
||||
@@ -48,6 +48,8 @@ class MongoSessionRepository(SessionRepository):
|
||||
"title": session.title,
|
||||
"status": session.status.value,
|
||||
"summary": session.summary,
|
||||
"scene": session.scene or "general",
|
||||
"scene_ref": session.scene_ref,
|
||||
"llm_provider_id": session.llm_provider_id,
|
||||
"llm_model": session.llm_model,
|
||||
"created_at": session.created_at,
|
||||
@@ -63,20 +65,59 @@ class MongoSessionRepository(SessionRepository):
|
||||
)
|
||||
return None if doc is None else self._to_session(doc)
|
||||
|
||||
async def list_active(self, company_id: int, user_id: str, limit: int = 50) -> list[Session]:
|
||||
async def list_active(
|
||||
self,
|
||||
company_id: int,
|
||||
user_id: str,
|
||||
limit: int = 50,
|
||||
*,
|
||||
scene: str | None = None,
|
||||
) -> list[Session]:
|
||||
query: dict[str, Any] = {
|
||||
"company_id": company_id,
|
||||
"user_id": user_id,
|
||||
"status": SessionStatus.ACTIVE.value,
|
||||
}
|
||||
# 缺省只列经营助手;旧文档无 scene 字段视为 general
|
||||
want = (scene or "general").strip() or "general"
|
||||
if want == "general":
|
||||
query["$or"] = [
|
||||
{"scene": "general"},
|
||||
{"scene": {"$exists": False}},
|
||||
{"scene": None},
|
||||
]
|
||||
else:
|
||||
query["scene"] = want
|
||||
cursor = (
|
||||
self._col.find(
|
||||
{
|
||||
"company_id": company_id,
|
||||
"user_id": user_id,
|
||||
"status": SessionStatus.ACTIVE.value,
|
||||
}
|
||||
)
|
||||
self._col.find(query)
|
||||
.sort("updated_at", -1)
|
||||
.limit(limit)
|
||||
)
|
||||
return [self._to_session(d) async for d in cursor]
|
||||
|
||||
async def find_active_by_scene_ref(
|
||||
self,
|
||||
company_id: int,
|
||||
user_id: str,
|
||||
*,
|
||||
scene: str,
|
||||
scene_ref: str,
|
||||
) -> Session | None:
|
||||
ref = (scene_ref or "").strip()
|
||||
if not ref:
|
||||
return None
|
||||
doc = await self._col.find_one(
|
||||
{
|
||||
"company_id": company_id,
|
||||
"user_id": user_id,
|
||||
"status": SessionStatus.ACTIVE.value,
|
||||
"scene": (scene or "").strip() or "general",
|
||||
"scene_ref": ref,
|
||||
},
|
||||
sort=[("updated_at", -1)],
|
||||
)
|
||||
return self._to_session(doc) if doc else None
|
||||
|
||||
async def update(self, session: Session) -> Session:
|
||||
session.updated_at = datetime.utcnow()
|
||||
await self._col.update_one(
|
||||
@@ -90,6 +131,8 @@ class MongoSessionRepository(SessionRepository):
|
||||
"title": session.title,
|
||||
"status": session.status.value,
|
||||
"summary": session.summary,
|
||||
"scene": session.scene or "general",
|
||||
"scene_ref": session.scene_ref,
|
||||
"llm_provider_id": session.llm_provider_id,
|
||||
"llm_model": session.llm_model,
|
||||
"updated_at": session.updated_at,
|
||||
@@ -108,6 +151,8 @@ class MongoSessionRepository(SessionRepository):
|
||||
title=doc.get("title") or "新对话",
|
||||
status=SessionStatus(doc.get("status") or SessionStatus.ACTIVE.value),
|
||||
summary=doc.get("summary"),
|
||||
scene=(doc.get("scene") or "general"),
|
||||
scene_ref=doc.get("scene_ref"),
|
||||
llm_provider_id=_optional_int(doc.get("llm_provider_id")),
|
||||
llm_model=doc.get("llm_model"),
|
||||
created_at=_dt(doc.get("created_at")),
|
||||
|
||||
+34
@@ -5,6 +5,7 @@ import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
||||
import org.springframework.stereotype.Component;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.mcp.adapter.catalog.model.CatalogProductHitVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.mcp.adapter.catalog.model.CatalogShopHitVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.mcp.adapter.catalog.model.CatalogSkuDetailVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.mcp.adapter.catalog.model.CatalogSkuHitVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.platform.model.enums.PlatformCode;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.mapper.ProductMapper;
|
||||
@@ -114,6 +115,39 @@ public class CatalogLookupAdapter {
|
||||
return new Slice<>(hits, rows.size() >= FETCH);
|
||||
}
|
||||
|
||||
/** 按 SKU 编码精准取详情;未命中返回 null。 */
|
||||
public CatalogSkuDetailVO getSkuByCode(Long companyId, String skuCode) {
|
||||
if (companyId == null || skuCode == null || skuCode.isBlank()) {
|
||||
return null;
|
||||
}
|
||||
LambdaQueryWrapper<ProductSkuPO> wrapper = new LambdaQueryWrapper<>();
|
||||
wrapper.eq(ProductSkuPO::getCompanyId, companyId)
|
||||
.eq(ProductSkuPO::getSkuCode, skuCode.trim())
|
||||
.last("LIMIT 1");
|
||||
ProductSkuPO sku = productSkuMapper.selectOne(wrapper);
|
||||
if (sku == null) {
|
||||
return null;
|
||||
}
|
||||
ProductPO product = sku.getProductId() == null ? null : productMapper.selectById(sku.getProductId());
|
||||
if (product != null && !companyId.equals(product.getCompanyId())) {
|
||||
product = null;
|
||||
}
|
||||
return CatalogSkuDetailVO.builder()
|
||||
.id(sku.getId())
|
||||
.skuCode(sku.getSkuCode())
|
||||
.name(sku.getName())
|
||||
.barcode(sku.getBarcode())
|
||||
.attrs(sku.getAttrs())
|
||||
.specCombinationKey(sku.getSpecCombinationKey())
|
||||
.imageUrl(sku.getImageUrl())
|
||||
.status(sku.getStatus())
|
||||
.productId(sku.getProductId())
|
||||
.productName(product == null ? null : product.getName())
|
||||
.productCode(product == null ? null : product.getProductCode())
|
||||
.hint("已命中内部 SKU,可据此生成标题或规格轴;不要向用户复述数字 id。")
|
||||
.build();
|
||||
}
|
||||
|
||||
private List<Long> matchingProductIds(Long companyId, String keyword) {
|
||||
LambdaQueryWrapper<ProductPO> wrapper = new LambdaQueryWrapper<>();
|
||||
wrapper.eq(ProductPO::getCompanyId, companyId)
|
||||
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.agent.mcp.adapter.catalog.model;
|
||||
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
|
||||
/** 内部 SKU 详情瘦项,供发布场景生成标题/规格。 */
|
||||
@Data
|
||||
@Builder
|
||||
public class CatalogSkuDetailVO {
|
||||
private Long id;
|
||||
private String skuCode;
|
||||
private String name;
|
||||
private String barcode;
|
||||
private String attrs;
|
||||
private String specCombinationKey;
|
||||
private String imageUrl;
|
||||
private Integer status;
|
||||
private Long productId;
|
||||
private String productName;
|
||||
private String productCode;
|
||||
private String hint;
|
||||
}
|
||||
+190
@@ -0,0 +1,190 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.agent.mcp.adapter.pdd;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
||||
import org.springframework.stereotype.Component;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.mcp.adapter.pdd.model.PddGoodsDetailSlimVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.mcp.adapter.pdd.model.PddGoodsHitVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.mcp.adapter.pdd.model.PddGoodsSkuSlimVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.channel.pdd.goods.mapper.PddGoodsMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.channel.pdd.goods.mapper.PddGoodsSkuMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.channel.pdd.goods.model.po.PddGoodsPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.channel.pdd.goods.model.po.PddGoodsSkuPO;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* 租户内检索已同步的拼多多渠道商品(不调 POP 实时接口)。
|
||||
*/
|
||||
@Component
|
||||
public class PddGoodsLookupAdapter {
|
||||
|
||||
static final int FETCH = 40;
|
||||
static final int LIMIT = 8;
|
||||
static final int SKU_SAMPLE = 6;
|
||||
|
||||
private final PddGoodsMapper pddGoodsMapper;
|
||||
private final PddGoodsSkuMapper pddGoodsSkuMapper;
|
||||
|
||||
public PddGoodsLookupAdapter(PddGoodsMapper pddGoodsMapper, PddGoodsSkuMapper pddGoodsSkuMapper) {
|
||||
this.pddGoodsMapper = pddGoodsMapper;
|
||||
this.pddGoodsSkuMapper = pddGoodsSkuMapper;
|
||||
}
|
||||
|
||||
public Slice<PddGoodsHitVO> search(Long companyId, String keyword, Long shopId) {
|
||||
String kw = keyword.trim();
|
||||
Set<Long> goodsRowIds = new LinkedHashSet<>();
|
||||
|
||||
LambdaQueryWrapper<PddGoodsPO> byName = baseGoodsQuery(companyId, shopId);
|
||||
byName.and(w -> w.like(PddGoodsPO::getGoodsName, kw).or().eq(PddGoodsPO::getGoodsId, kw));
|
||||
for (PddGoodsPO g : pddGoodsMapper.selectPage(new Page<>(1, FETCH, false), byName).getRecords()) {
|
||||
goodsRowIds.add(g.getId());
|
||||
}
|
||||
|
||||
LambdaQueryWrapper<PddGoodsSkuPO> byOuter = new LambdaQueryWrapper<>();
|
||||
byOuter.eq(PddGoodsSkuPO::getCompanyId, companyId)
|
||||
.and(w -> w.eq(PddGoodsSkuPO::getOuterId, kw)
|
||||
.or().eq(PddGoodsSkuPO::getOuterGoodsId, kw)
|
||||
.or().like(PddGoodsSkuPO::getOuterId, kw)
|
||||
.or().like(PddGoodsSkuPO::getOuterGoodsId, kw));
|
||||
List<PddGoodsSkuPO> skuHits = pddGoodsSkuMapper
|
||||
.selectPage(new Page<>(1, FETCH, false), byOuter)
|
||||
.getRecords();
|
||||
for (PddGoodsSkuPO sku : skuHits) {
|
||||
if (sku.getGoodsRowId() != null) {
|
||||
goodsRowIds.add(sku.getGoodsRowId());
|
||||
}
|
||||
}
|
||||
|
||||
if (goodsRowIds.isEmpty()) {
|
||||
return new Slice<>(List.of(), false);
|
||||
}
|
||||
|
||||
List<PddGoodsPO> goods = pddGoodsMapper.selectBatchIds(goodsRowIds).stream()
|
||||
.filter(g -> companyId.equals(g.getCompanyId()))
|
||||
.filter(g -> !Integer.valueOf(1).equals(g.getIsPlatformDeleted()))
|
||||
.filter(g -> shopId == null || shopId.equals(g.getShopId()))
|
||||
.sorted((a, b) -> Integer.compare(score(kw, a.getGoodsName(), a.getGoodsId()),
|
||||
score(kw, b.getGoodsName(), b.getGoodsId())))
|
||||
.toList();
|
||||
boolean truncated = goods.size() > LIMIT || skuHits.size() >= FETCH;
|
||||
List<PddGoodsHitVO> hits = new ArrayList<>();
|
||||
for (PddGoodsPO g : head(goods)) {
|
||||
List<PddGoodsSkuPO> skus = listSkus(companyId, g.getId());
|
||||
hits.add(PddGoodsHitVO.builder()
|
||||
.id(g.getId())
|
||||
.goodsId(g.getGoodsId())
|
||||
.goodsName(g.getGoodsName())
|
||||
.shopId(g.getShopId())
|
||||
.mallId(g.getMallId())
|
||||
.isOnsale(g.getIsOnsale())
|
||||
.sampleOuterIds(sample(skus.stream().map(PddGoodsSkuPO::getOuterId).toList()))
|
||||
.sampleOuterGoodsIds(sample(skus.stream().map(PddGoodsSkuPO::getOuterGoodsId).toList()))
|
||||
.build());
|
||||
}
|
||||
return new Slice<>(hits, truncated);
|
||||
}
|
||||
|
||||
public PddGoodsDetailSlimVO detail(Long companyId, Long goodsRowId, String goodsId, Long shopId) {
|
||||
PddGoodsPO goods = null;
|
||||
if (goodsRowId != null) {
|
||||
goods = pddGoodsMapper.selectById(goodsRowId);
|
||||
} else if (goodsId != null && !goodsId.isBlank()) {
|
||||
LambdaQueryWrapper<PddGoodsPO> w = baseGoodsQuery(companyId, shopId);
|
||||
w.eq(PddGoodsPO::getGoodsId, goodsId.trim()).last("LIMIT 1");
|
||||
goods = pddGoodsMapper.selectOne(w);
|
||||
}
|
||||
if (goods == null || !companyId.equals(goods.getCompanyId())
|
||||
|| Integer.valueOf(1).equals(goods.getIsPlatformDeleted())) {
|
||||
return null;
|
||||
}
|
||||
List<PddGoodsSkuSlimVO> skus = listSkus(companyId, goods.getId()).stream()
|
||||
.map(s -> PddGoodsSkuSlimVO.builder()
|
||||
.skuId(s.getSkuId())
|
||||
.spec(s.getSpec())
|
||||
.specDetails(s.getSpecDetails())
|
||||
.outerGoodsId(s.getOuterGoodsId())
|
||||
.outerId(s.getOuterId())
|
||||
.build())
|
||||
.toList();
|
||||
return PddGoodsDetailSlimVO.builder()
|
||||
.id(goods.getId())
|
||||
.goodsId(goods.getGoodsId())
|
||||
.goodsName(goods.getGoodsName())
|
||||
.shopId(goods.getShopId())
|
||||
.mallId(goods.getMallId())
|
||||
.isOnsale(goods.getIsOnsale())
|
||||
.isMoreSku(goods.getIsMoreSku())
|
||||
.skus(skus)
|
||||
.hint("可模仿本商品的标题与规格结构(spec/specDetails);写回表单时只改规格轴,由页面重建 SKU 行。")
|
||||
.build();
|
||||
}
|
||||
|
||||
private List<PddGoodsSkuPO> listSkus(Long companyId, Long goodsRowId) {
|
||||
if (goodsRowId == null) {
|
||||
return List.of();
|
||||
}
|
||||
LambdaQueryWrapper<PddGoodsSkuPO> w = new LambdaQueryWrapper<>();
|
||||
w.eq(PddGoodsSkuPO::getCompanyId, companyId)
|
||||
.eq(PddGoodsSkuPO::getGoodsRowId, goodsRowId)
|
||||
.last("LIMIT 80");
|
||||
return pddGoodsSkuMapper.selectList(w);
|
||||
}
|
||||
|
||||
private static LambdaQueryWrapper<PddGoodsPO> baseGoodsQuery(Long companyId, Long shopId) {
|
||||
LambdaQueryWrapper<PddGoodsPO> w = new LambdaQueryWrapper<>();
|
||||
w.eq(PddGoodsPO::getCompanyId, companyId)
|
||||
.and(q -> q.isNull(PddGoodsPO::getIsPlatformDeleted)
|
||||
.or().ne(PddGoodsPO::getIsPlatformDeleted, 1));
|
||||
if (shopId != null) {
|
||||
w.eq(PddGoodsPO::getShopId, shopId);
|
||||
}
|
||||
return w;
|
||||
}
|
||||
|
||||
private static List<String> sample(List<String> values) {
|
||||
return values.stream()
|
||||
.filter(Objects::nonNull)
|
||||
.map(String::trim)
|
||||
.filter(s -> !s.isEmpty())
|
||||
.distinct()
|
||||
.limit(SKU_SAMPLE)
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
private static <T> List<T> head(List<T> rows) {
|
||||
if (rows.size() <= LIMIT) {
|
||||
return rows;
|
||||
}
|
||||
return rows.subList(0, LIMIT);
|
||||
}
|
||||
|
||||
static int score(String keyword, String... fields) {
|
||||
String key = keyword.toLowerCase(Locale.ROOT);
|
||||
int best = 3;
|
||||
for (String field : fields) {
|
||||
if (field == null || field.isBlank()) {
|
||||
continue;
|
||||
}
|
||||
String value = field.trim().toLowerCase(Locale.ROOT);
|
||||
if (value.equals(key)) {
|
||||
return 0;
|
||||
}
|
||||
if (value.startsWith(key)) {
|
||||
best = Math.min(best, 1);
|
||||
} else if (value.contains(key)) {
|
||||
best = Math.min(best, 2);
|
||||
}
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
public record Slice<T>(List<T> items, boolean truncated) {
|
||||
}
|
||||
}
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.agent.mcp.adapter.pdd.model;
|
||||
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/** 渠道拼多多商品瘦详情。 */
|
||||
@Data
|
||||
@Builder
|
||||
public class PddGoodsDetailSlimVO {
|
||||
private Long id;
|
||||
private String goodsId;
|
||||
private String goodsName;
|
||||
private Long shopId;
|
||||
private Long mallId;
|
||||
private Integer isOnsale;
|
||||
private Integer isMoreSku;
|
||||
private String hint;
|
||||
private List<PddGoodsSkuSlimVO> skus;
|
||||
}
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.agent.mcp.adapter.pdd.model;
|
||||
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/** 渠道拼多多商品检索命中。 */
|
||||
@Data
|
||||
@Builder
|
||||
public class PddGoodsHitVO {
|
||||
private Long id;
|
||||
private String goodsId;
|
||||
private String goodsName;
|
||||
private Long shopId;
|
||||
private Long mallId;
|
||||
private Integer isOnsale;
|
||||
private List<String> sampleOuterIds;
|
||||
private List<String> sampleOuterGoodsIds;
|
||||
}
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.agent.mcp.adapter.pdd.model;
|
||||
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/** pdd_goods_search 返回体。 */
|
||||
@Data
|
||||
@Builder
|
||||
public class PddGoodsSearchSlimVO {
|
||||
private String keyword;
|
||||
private boolean truncated;
|
||||
private String hint;
|
||||
private List<PddGoodsHitVO> items;
|
||||
}
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.agent.mcp.adapter.pdd.model;
|
||||
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
|
||||
/** 渠道 SKU 瘦项。 */
|
||||
@Data
|
||||
@Builder
|
||||
public class PddGoodsSkuSlimVO {
|
||||
private String skuId;
|
||||
private String spec;
|
||||
private String specDetails;
|
||||
private String outerGoodsId;
|
||||
private String outerId;
|
||||
}
|
||||
+19
@@ -6,6 +6,7 @@ import top.xyquan.ecomdmbbackend.modules.agent.mcp.adapter.catalog.CatalogLookup
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.mcp.adapter.catalog.model.CatalogProductHitVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.mcp.adapter.catalog.model.CatalogSearchSlimVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.mcp.adapter.catalog.model.CatalogShopHitVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.mcp.adapter.catalog.model.CatalogSkuDetailVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.mcp.adapter.catalog.model.CatalogSkuHitVO;
|
||||
import top.xyquan.ecomdmbbackend.utils.CurrentUserContext;
|
||||
|
||||
@@ -52,6 +53,24 @@ public class CatalogMcpFacade {
|
||||
hint(total, truncated));
|
||||
}
|
||||
|
||||
public CatalogSkuDetailVO skuDetail(String skuCode) {
|
||||
String code = skuCode == null ? "" : skuCode.trim();
|
||||
if (code.isEmpty()) {
|
||||
return CatalogSkuDetailVO.builder()
|
||||
.hint("skuCode 不能为空。用内部规格编码查询。")
|
||||
.build();
|
||||
}
|
||||
Long companyId = currentUserContext.getCurrentCompanyId();
|
||||
CatalogSkuDetailVO detail = catalogLookupAdapter.getSkuByCode(companyId, code);
|
||||
if (detail == null) {
|
||||
return CatalogSkuDetailVO.builder()
|
||||
.skuCode(code)
|
||||
.hint("未找到该 SKU 编码。可改用 catalog_search kind=sku 模糊搜,或确认编码是否正确。")
|
||||
.build();
|
||||
}
|
||||
return detail;
|
||||
}
|
||||
|
||||
private static boolean want(String kind, String target) {
|
||||
return "all".equals(kind) || target.equals(kind);
|
||||
}
|
||||
|
||||
+80
@@ -0,0 +1,80 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.agent.mcp.application;
|
||||
|
||||
import org.springframework.stereotype.Service;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.mcp.adapter.pdd.PddGoodsLookupAdapter;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.mcp.adapter.pdd.PddGoodsLookupAdapter.Slice;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.mcp.adapter.pdd.model.PddGoodsDetailSlimVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.mcp.adapter.pdd.model.PddGoodsHitVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.mcp.adapter.pdd.model.PddGoodsSearchSlimVO;
|
||||
import top.xyquan.ecomdmbbackend.utils.CurrentUserContext;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 拼多多渠道商品 MCP:只查本地已同步数据。
|
||||
*/
|
||||
@Service
|
||||
public class PddMcpFacade {
|
||||
|
||||
private final PddGoodsLookupAdapter pddGoodsLookupAdapter;
|
||||
private final CurrentUserContext currentUserContext;
|
||||
|
||||
public PddMcpFacade(PddGoodsLookupAdapter pddGoodsLookupAdapter,
|
||||
CurrentUserContext currentUserContext) {
|
||||
this.pddGoodsLookupAdapter = pddGoodsLookupAdapter;
|
||||
this.currentUserContext = currentUserContext;
|
||||
}
|
||||
|
||||
public PddGoodsSearchSlimVO search(String keyword, Long shopId) {
|
||||
String kw = keyword == null ? "" : keyword.trim();
|
||||
if (kw.isEmpty()) {
|
||||
return PddGoodsSearchSlimVO.builder()
|
||||
.keyword(kw)
|
||||
.truncated(false)
|
||||
.hint("keyword 不能为空。可用商品名、平台 goodsId、商家编码 outerId/outerGoodsId 搜索。")
|
||||
.items(List.of())
|
||||
.build();
|
||||
}
|
||||
if (kw.length() > 64) {
|
||||
kw = kw.substring(0, 64);
|
||||
}
|
||||
Long companyId = currentUserContext.getCurrentCompanyId();
|
||||
Slice<PddGoodsHitVO> slice = pddGoodsLookupAdapter.search(companyId, kw, shopId);
|
||||
int total = slice.items().size();
|
||||
String hint = switch (total) {
|
||||
case 0 -> "本地未命中已同步商品。可换编码/名称,或先在渠道商品里同步后再试。不要向用户要数字 ID。";
|
||||
case 1 -> "唯一命中。用返回的 id 调 pdd_goods_detail 取规格结构与标题。";
|
||||
default -> "多条命中。可自行选择最接近的一条模仿标题/规格,或请用户指定;禁止索要数字 ID。";
|
||||
};
|
||||
if (slice.truncated()) {
|
||||
hint += "结果已截断。";
|
||||
}
|
||||
return PddGoodsSearchSlimVO.builder()
|
||||
.keyword(kw)
|
||||
.truncated(slice.truncated())
|
||||
.hint(hint)
|
||||
.items(slice.items())
|
||||
.build();
|
||||
}
|
||||
|
||||
public PddGoodsDetailSlimVO detail(Long goodsRowId, String goodsId, Long shopId) {
|
||||
if (goodsRowId == null && (goodsId == null || goodsId.isBlank())) {
|
||||
return PddGoodsDetailSlimVO.builder()
|
||||
.hint("请提供 goodsRowId(搜索结果的 id)或 goodsId。")
|
||||
.skus(List.of())
|
||||
.build();
|
||||
}
|
||||
Long companyId = currentUserContext.getCurrentCompanyId();
|
||||
PddGoodsDetailSlimVO detail = pddGoodsLookupAdapter.detail(
|
||||
companyId, goodsRowId, goodsId, shopId);
|
||||
if (detail == null) {
|
||||
return PddGoodsDetailSlimVO.builder()
|
||||
.id(goodsRowId)
|
||||
.goodsId(goodsId)
|
||||
.hint("未找到该渠道商品(可能未同步或已平台删除)。")
|
||||
.skus(List.of())
|
||||
.build();
|
||||
}
|
||||
return detail;
|
||||
}
|
||||
}
|
||||
+10
@@ -4,6 +4,7 @@ import org.springaicommunity.mcp.annotation.McpTool;
|
||||
import org.springaicommunity.mcp.annotation.McpToolParam;
|
||||
import org.springframework.stereotype.Component;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.mcp.adapter.catalog.model.CatalogSearchSlimVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.mcp.adapter.catalog.model.CatalogSkuDetailVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.mcp.application.CatalogMcpFacade;
|
||||
|
||||
/**
|
||||
@@ -29,4 +30,13 @@ public class CatalogMcpTools {
|
||||
@McpToolParam(description = "shop / product / sku / all,默认 all", required = false) String kind) {
|
||||
return catalogMcpFacade.search(keyword, kind);
|
||||
}
|
||||
|
||||
@McpTool(
|
||||
name = "catalog_sku_detail",
|
||||
description = "按内部 SKU 编码精准查询规格详情(名称、所属商品、规格键、条码等)。"
|
||||
+ "发布商品、改标题/规格前,若用户已填商家编码或内部 skuCode,优先调本工具取内部商品信息。")
|
||||
public CatalogSkuDetailVO skuDetail(
|
||||
@McpToolParam(description = "内部 SKU 编码 skuCode,必填", required = true) String skuCode) {
|
||||
return catalogMcpFacade.skuDetail(skuCode);
|
||||
}
|
||||
}
|
||||
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.agent.mcp.tools;
|
||||
|
||||
import org.springaicommunity.mcp.annotation.McpTool;
|
||||
import org.springaicommunity.mcp.annotation.McpToolParam;
|
||||
import org.springframework.stereotype.Component;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.mcp.adapter.pdd.model.PddGoodsDetailSlimVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.mcp.adapter.pdd.model.PddGoodsSearchSlimVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.mcp.application.PddMcpFacade;
|
||||
|
||||
/**
|
||||
* 拼多多渠道商品 MCP:供发布场景模仿标题/规格。
|
||||
*/
|
||||
@Component
|
||||
public class PddMcpTools {
|
||||
|
||||
private final PddMcpFacade pddMcpFacade;
|
||||
|
||||
public PddMcpTools(PddMcpFacade pddMcpFacade) {
|
||||
this.pddMcpFacade = pddMcpFacade;
|
||||
}
|
||||
|
||||
@McpTool(
|
||||
name = "pdd_goods_search",
|
||||
description = "在当前租户已同步的拼多多渠道商品中检索。"
|
||||
+ "可用商品名、平台 goodsId、SKU 商家编码 outerId(out_sku_sn)或 outerGoodsId。"
|
||||
+ "只查本地库,不实时拉 POP。发布场景生成标题/规格前先搜再 detail。")
|
||||
public PddGoodsSearchSlimVO search(
|
||||
@McpToolParam(description = "商品名 / goodsId / outerId / outerGoodsId", required = true) String keyword,
|
||||
@McpToolParam(description = "渠道店铺 shopId,可选", required = false) Long shopId) {
|
||||
return pddMcpFacade.search(keyword, shopId);
|
||||
}
|
||||
|
||||
@McpTool(
|
||||
name = "pdd_goods_detail",
|
||||
description = "取已同步拼多多商品瘦详情:标题、规格文字、各 SKU 的 outerId/spec。"
|
||||
+ "goodsRowId 优先(来自 pdd_goods_search 的 id);也可用 goodsId。")
|
||||
public PddGoodsDetailSlimVO detail(
|
||||
@McpToolParam(description = "本地渠道商品行 id(搜索结果 id)", required = false) Long goodsRowId,
|
||||
@McpToolParam(description = "平台 goodsId", required = false) String goodsId,
|
||||
@McpToolParam(description = "渠道店铺 shopId,可选", required = false) Long shopId) {
|
||||
return pddMcpFacade.detail(goodsRowId, goodsId, shopId);
|
||||
}
|
||||
}
|
||||
@@ -5,10 +5,15 @@ import { requestClient } from '#/api/request';
|
||||
/** Agent 服务走 /api/agent,开发态由 Vite 代理到 :8200 */
|
||||
|
||||
export namespace AgentVO {
|
||||
/** general=经营助手;ecom_goods_publish=拼多多商品发布 */
|
||||
export type SessionScene = 'general' | 'ecom_goods_publish' | string;
|
||||
|
||||
export interface Session {
|
||||
threadId: string;
|
||||
title: string;
|
||||
status: string;
|
||||
scene?: SessionScene;
|
||||
sceneRef?: string | null;
|
||||
llmProviderId?: number | null;
|
||||
llmModel?: string | null;
|
||||
createdAt?: string;
|
||||
@@ -16,6 +21,14 @@ export namespace AgentVO {
|
||||
lastMessageAt?: string | null;
|
||||
}
|
||||
|
||||
/** SSE client_tool:前端执行后模型侧已乐观回传 */
|
||||
export interface ClientToolCall {
|
||||
toolCallId: string;
|
||||
name: string;
|
||||
args: Record<string, unknown>;
|
||||
label?: string;
|
||||
}
|
||||
|
||||
export interface Message {
|
||||
id?: string;
|
||||
seq: number;
|
||||
@@ -60,19 +73,30 @@ export namespace AgentVO {
|
||||
}
|
||||
}
|
||||
|
||||
export async function listAgentSessionsApi() {
|
||||
return requestClient.get<{ items: AgentVO.Session[] }>('/agent/sessions');
|
||||
export async function listAgentSessionsApi(options?: {
|
||||
scene?: AgentVO.SessionScene;
|
||||
}) {
|
||||
return requestClient.get<{ items: AgentVO.Session[] }>('/agent/sessions', {
|
||||
params: { scene: options?.scene ?? 'general' },
|
||||
});
|
||||
}
|
||||
|
||||
export async function createAgentSessionApi(options?: {
|
||||
title?: string;
|
||||
llmProviderId?: number;
|
||||
llmModel?: string;
|
||||
scene?: AgentVO.SessionScene;
|
||||
sceneRef?: string;
|
||||
/** 同 scene+sceneRef 已有活跃会话则复用 */
|
||||
reuseBySceneRef?: boolean;
|
||||
}) {
|
||||
return requestClient.post<AgentVO.Session>('/agent/sessions', {
|
||||
title: options?.title,
|
||||
llmProviderId: options?.llmProviderId,
|
||||
llmModel: options?.llmModel,
|
||||
scene: options?.scene,
|
||||
sceneRef: options?.sceneRef,
|
||||
reuseBySceneRef: options?.reuseBySceneRef,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -189,12 +213,16 @@ export async function probeAgentLlmModelsApi(body: {
|
||||
export function streamAgentChat(options: {
|
||||
threadId: string;
|
||||
content: string;
|
||||
/** 发布场景:当前表单快照,供 ui_get_publish_snapshot */
|
||||
formSnapshot?: Record<string, unknown>;
|
||||
onToken: (text: string) => void;
|
||||
onTool?: (payload: {
|
||||
phase: string;
|
||||
name?: string;
|
||||
label: string;
|
||||
}) => void;
|
||||
/** 前端工具:乐观执行改表单 */
|
||||
onClientTool?: (call: AgentVO.ClientToolCall) => void;
|
||||
onDone?: () => void;
|
||||
onError?: (message: string) => void;
|
||||
}): AbortController {
|
||||
@@ -212,7 +240,12 @@ export function streamAgentChat(options: {
|
||||
Accept: 'text/event-stream',
|
||||
...(token ? { Authorization: `Bearer ${token}` } : {}),
|
||||
},
|
||||
body: JSON.stringify({ content: options.content }),
|
||||
body: JSON.stringify({
|
||||
content: options.content,
|
||||
...(options.formSnapshot
|
||||
? { formSnapshot: options.formSnapshot }
|
||||
: {}),
|
||||
}),
|
||||
signal: controller.signal,
|
||||
});
|
||||
if (!res.ok || !res.body) {
|
||||
@@ -263,6 +296,25 @@ export function streamAgentChat(options: {
|
||||
} catch {
|
||||
/* ignore malformed tool events */
|
||||
}
|
||||
} else if (event === 'client_tool') {
|
||||
try {
|
||||
const parsed = JSON.parse(data) as {
|
||||
toolCallId?: string;
|
||||
name?: string;
|
||||
args?: Record<string, unknown>;
|
||||
label?: string;
|
||||
};
|
||||
if (parsed.name) {
|
||||
options.onClientTool?.({
|
||||
toolCallId: parsed.toolCallId || parsed.name,
|
||||
name: parsed.name,
|
||||
args: parsed.args || {},
|
||||
label: parsed.label,
|
||||
});
|
||||
}
|
||||
} catch {
|
||||
/* ignore malformed client_tool events */
|
||||
}
|
||||
} else if (event === 'error') {
|
||||
try {
|
||||
const parsed = JSON.parse(data) as { message?: string };
|
||||
|
||||
@@ -3,7 +3,11 @@ import { computed, ref } from 'vue';
|
||||
import { defineStore } from 'pinia';
|
||||
|
||||
/** 三套业务侧栏各自一份布局,互不影响 */
|
||||
export type ColSidebarKind = 'company' | 'ec-shop' | 'pdd-shop';
|
||||
export type ColSidebarKind =
|
||||
| 'company'
|
||||
| 'ec-shop'
|
||||
| 'pdd-shop'
|
||||
| 'pdd-publish-agent';
|
||||
|
||||
export interface ColSidebarLayout {
|
||||
/** 展开宽度(百分比) */
|
||||
@@ -16,11 +20,17 @@ const DEFAULT_LAYOUT: ColSidebarLayout = {
|
||||
collapsed: false,
|
||||
};
|
||||
|
||||
const AGENT_DEFAULT_LAYOUT: ColSidebarLayout = {
|
||||
width: 28,
|
||||
collapsed: false,
|
||||
};
|
||||
|
||||
function createDefaultLayouts(): Record<ColSidebarKind, ColSidebarLayout> {
|
||||
return {
|
||||
'ec-shop': { ...DEFAULT_LAYOUT },
|
||||
'pdd-shop': { ...DEFAULT_LAYOUT },
|
||||
company: { ...DEFAULT_LAYOUT },
|
||||
'pdd-publish-agent': { ...AGENT_DEFAULT_LAYOUT },
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -190,7 +190,7 @@ function onSessionClick(threadId: string) {
|
||||
async function refreshSessions() {
|
||||
loadingSessions.value = true;
|
||||
try {
|
||||
const res = await listAgentSessionsApi();
|
||||
const res = await listAgentSessionsApi({ scene: 'general' });
|
||||
sessions.value = res.items || [];
|
||||
if (!composingNew.value && !activeThreadId.value && sessions.value[0]) {
|
||||
activeThreadId.value = sessions.value[0].threadId;
|
||||
@@ -281,6 +281,7 @@ async function ensureSession(): Promise<string | null> {
|
||||
const s = await createAgentSessionApi({
|
||||
llmProviderId: parsed?.providerId,
|
||||
llmModel: parsed?.model,
|
||||
scene: 'general',
|
||||
});
|
||||
composingNew.value = false;
|
||||
sessions.value = [s, ...sessions.value];
|
||||
|
||||
+130
@@ -2983,6 +2983,136 @@ function resetAll() {
|
||||
specIdCache.clear();
|
||||
}
|
||||
|
||||
/** —— 智能体命令面:读快照 / 执行 ui_* —— */
|
||||
|
||||
function getFormSnapshot() {
|
||||
return {
|
||||
goodsName: form.goodsName,
|
||||
goodsDesc: form.goodsDesc,
|
||||
pddShopId: form.pddShopId,
|
||||
catId: form.catId,
|
||||
marketPriceYuan: form.marketPriceYuan,
|
||||
costTemplateId: form.costTemplateId,
|
||||
shipmentLimitSecond: form.shipmentLimitSecond,
|
||||
twoPiecesDiscount: form.twoPiecesDiscount,
|
||||
specAxes: specAxes.value.map((a) => ({
|
||||
name: a.name,
|
||||
catalogKey: a.catalogKey,
|
||||
values: effectiveSpecValues(a).map((v) => labelOfAxisValue(a, v)),
|
||||
})),
|
||||
skuRows: skuRows.value.map((r) => ({
|
||||
skuName: r.skuName,
|
||||
outSkuSn: r.outSkuSn,
|
||||
quantity: r.quantity,
|
||||
weight: r.weight,
|
||||
saleValues: { ...r.saleValues },
|
||||
internalSkuId: r.internalSkuId,
|
||||
productName: r.productName,
|
||||
internalSkuName: r.internalSkuName,
|
||||
})),
|
||||
specCatalog: specCatalog.value.map((c) => ({
|
||||
name: c.name,
|
||||
catalogKey: c.catalogKey,
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
function applySetGoodsName(args: Record<string, unknown>) {
|
||||
const name = String(args.goodsName ?? '').trim();
|
||||
if (!name) return { ok: false, message: '标题为空' };
|
||||
form.goodsName = name.slice(0, 120);
|
||||
return { ok: true, message: `已写入标题:${form.goodsName}` };
|
||||
}
|
||||
|
||||
function applySetGoodsDesc(args: Record<string, unknown>) {
|
||||
form.goodsDesc = String(args.goodsDesc ?? '');
|
||||
return { ok: true, message: '已写入商品描述' };
|
||||
}
|
||||
|
||||
/** 按名称匹配类目规格目录;无目录时建自由轴 */
|
||||
function applySetSpecAxes(args: Record<string, unknown>) {
|
||||
const raw = args.axes;
|
||||
if (!Array.isArray(raw) || raw.length === 0) {
|
||||
return { ok: false, message: '规格轴为空' };
|
||||
}
|
||||
const maxAxes = Math.min(2, Math.max(1, specCatalog.value.length || 2));
|
||||
const limited = raw.slice(0, maxAxes);
|
||||
const usedCatalog = new Set<string>();
|
||||
const next: SpecAxis[] = [];
|
||||
|
||||
for (const item of limited) {
|
||||
if (!item || typeof item !== 'object') continue;
|
||||
const row = item as { name?: unknown; values?: unknown };
|
||||
const axisName = String(row.name ?? '').trim();
|
||||
const valuesRaw = Array.isArray(row.values) ? row.values : [];
|
||||
const labels = valuesRaw
|
||||
.map((v) => String(v ?? '').trim())
|
||||
.filter(Boolean);
|
||||
if (!axisName) continue;
|
||||
|
||||
const match =
|
||||
specCatalog.value.find(
|
||||
(c) =>
|
||||
!usedCatalog.has(c.catalogKey) &&
|
||||
(c.name === axisName || c.name.includes(axisName) || axisName.includes(c.name)),
|
||||
) ||
|
||||
specCatalog.value.find((c) => !usedCatalog.has(c.catalogKey));
|
||||
|
||||
if (match) {
|
||||
usedCatalog.add(match.catalogKey);
|
||||
const axis = createAxisFromCatalog(match);
|
||||
axis.selectedValues =
|
||||
labels.length > 0
|
||||
? labels.map((t) => resolveSpecValueToken(axis, t))
|
||||
: [''];
|
||||
next.push(axis);
|
||||
} else {
|
||||
const key = `agent_${axisName}_${specAxisRowSeq}`;
|
||||
next.push({
|
||||
rowId: specAxisRowSeq++,
|
||||
catalogKey: key,
|
||||
key,
|
||||
name: axisName,
|
||||
presetOptions: [],
|
||||
selectedValues: labels.length > 0 ? labels : [''],
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (next.length === 0) {
|
||||
return { ok: false, message: '未能解析任何规格维' };
|
||||
}
|
||||
specAxes.value = next;
|
||||
syncSkuRowsFromSpecs();
|
||||
return {
|
||||
ok: true,
|
||||
message: `已设置 ${next.length} 个规格维,SKU 行 ${skuRows.value.length} 条`,
|
||||
};
|
||||
}
|
||||
|
||||
function applyClientTool(name: string, args: Record<string, unknown>) {
|
||||
switch (name) {
|
||||
case 'ui_get_publish_snapshot':
|
||||
return {
|
||||
ok: true,
|
||||
message: '快照已由请求体注入,无需前端写入',
|
||||
};
|
||||
case 'ui_set_goods_name':
|
||||
return applySetGoodsName(args);
|
||||
case 'ui_set_goods_desc':
|
||||
return applySetGoodsDesc(args);
|
||||
case 'ui_set_spec_axes':
|
||||
return applySetSpecAxes(args);
|
||||
default:
|
||||
return { ok: false, message: `未支持的前端工具:${name}` };
|
||||
}
|
||||
}
|
||||
|
||||
defineExpose({
|
||||
getFormSnapshot,
|
||||
applyClientTool,
|
||||
});
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
document.removeEventListener('pointerdown', onOverlayPointerDown, true);
|
||||
clearLocalImages();
|
||||
|
||||
@@ -0,0 +1,540 @@
|
||||
<script lang="ts" setup>
|
||||
/**
|
||||
* 拼多多发布页右侧智能体栏:一草稿一会话,执行 client_tool 改表单。
|
||||
*/
|
||||
import { computed, nextTick, onBeforeUnmount, ref, watch } from 'vue';
|
||||
|
||||
import {
|
||||
MenuFoldOutlined,
|
||||
MenuUnfoldOutlined,
|
||||
SendOutlined,
|
||||
} from '@ant-design/icons-vue';
|
||||
import { Button, Empty, Input, Select, Spin, Tooltip, message } from 'ant-design-vue';
|
||||
import { ChatItem } from '@tdesign-vue-next/chat';
|
||||
import 'tdesign-vue-next/es/style/index.css';
|
||||
import '@tdesign-vue-next/chat/es/style/index.css';
|
||||
|
||||
import {
|
||||
createAgentSessionApi,
|
||||
listAgentEnabledLlmModelsApi,
|
||||
listAgentMessagesApi,
|
||||
patchAgentSessionApi,
|
||||
streamAgentChat,
|
||||
type AgentVO,
|
||||
} from '#/api/agent';
|
||||
|
||||
import type { PublishEditorAgentApi } from './publish-agent-commands';
|
||||
|
||||
defineOptions({ name: 'PddPublishAgentPanel' });
|
||||
|
||||
const props = defineProps<{
|
||||
draftId: number;
|
||||
collapsed?: boolean;
|
||||
/** 编辑器命令面(ref) */
|
||||
editorApi: PublishEditorAgentApi | null;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
expand: [];
|
||||
collapse: [];
|
||||
}>();
|
||||
|
||||
const SCENE = 'ecom_goods_publish' as const;
|
||||
|
||||
const starterPrompts = [
|
||||
'根据已填的 SKU 商家编码,找相似拼多多商品并生成标题',
|
||||
'参考渠道商品帮我整理规格轴',
|
||||
'把当前标题改得更适合拼多多搜索',
|
||||
];
|
||||
|
||||
type BubbleView = {
|
||||
id: string;
|
||||
role: 'user' | 'assistant';
|
||||
name: string;
|
||||
content: string;
|
||||
textLoading: boolean;
|
||||
};
|
||||
|
||||
const loadingSession = ref(true);
|
||||
const loadingMessages = ref(false);
|
||||
const sending = ref(false);
|
||||
const session = ref<AgentVO.Session | null>(null);
|
||||
const messages = ref<AgentVO.Message[]>([]);
|
||||
const streamingText = ref('');
|
||||
const toolStatusLabel = ref('');
|
||||
const toolStatusActive = ref(false);
|
||||
const draft = ref('');
|
||||
const enabledModels = ref<AgentVO.LlmModelItem[]>([]);
|
||||
const selectedModelKey = ref<string | undefined>(undefined);
|
||||
const patchingModel = ref(false);
|
||||
const messagePaneRef = ref<HTMLElement | null>(null);
|
||||
let abort: AbortController | null = null;
|
||||
let messagesLoadSeq = 0;
|
||||
|
||||
function modelKey(providerId: number, model: string) {
|
||||
return `${providerId}::${model}`;
|
||||
}
|
||||
|
||||
function parseModelKey(key: string | undefined) {
|
||||
if (!key) return null;
|
||||
const idx = key.indexOf('::');
|
||||
if (idx <= 0) return null;
|
||||
const providerId = Number(key.slice(0, idx));
|
||||
const model = key.slice(idx + 2);
|
||||
if (!Number.isFinite(providerId) || !model) return null;
|
||||
return { providerId, model };
|
||||
}
|
||||
|
||||
const modelOptions = computed(() => {
|
||||
const groups = new Map<
|
||||
string,
|
||||
{ label: string; options: Array<{ value: string; label: string }> }
|
||||
>();
|
||||
for (const m of enabledModels.value) {
|
||||
const gLabel = m.providerDisplayName || `提供商 #${m.providerId}`;
|
||||
const gKey = String(m.providerId);
|
||||
if (!groups.has(gKey)) {
|
||||
groups.set(gKey, { label: gLabel, options: [] });
|
||||
}
|
||||
groups.get(gKey)!.options.push({
|
||||
value: modelKey(m.providerId, m.model),
|
||||
label: m.label || m.model,
|
||||
});
|
||||
}
|
||||
return [...groups.values()];
|
||||
});
|
||||
|
||||
const showStarter = computed(
|
||||
() =>
|
||||
messages.value.length === 0 &&
|
||||
!loadingMessages.value &&
|
||||
!loadingSession.value,
|
||||
);
|
||||
|
||||
const bubbleViews = computed<BubbleView[]>(() =>
|
||||
messages.value.map((m, idx) => {
|
||||
const isStreamingAssistant =
|
||||
sending.value &&
|
||||
idx === messages.value.length - 1 &&
|
||||
m.role === 'assistant';
|
||||
const text = isStreamingAssistant
|
||||
? streamingText.value || m.content || ''
|
||||
: m.content || '';
|
||||
const role = m.role === 'user' ? 'user' : 'assistant';
|
||||
return {
|
||||
id: m.id || `${m.seq}-${idx}`,
|
||||
role,
|
||||
name: role === 'user' ? '我' : '发布助手',
|
||||
content: text,
|
||||
textLoading: isStreamingAssistant && !text && !toolStatusActive.value,
|
||||
};
|
||||
}),
|
||||
);
|
||||
|
||||
function defaultModelKey() {
|
||||
const d = enabledModels.value.find((m) => m.isDefault);
|
||||
const pick = d || enabledModels.value[0];
|
||||
return pick ? modelKey(pick.providerId, pick.model) : undefined;
|
||||
}
|
||||
|
||||
function syncSelectedFromSession() {
|
||||
const s = session.value;
|
||||
if (s?.llmProviderId != null && s.llmModel) {
|
||||
selectedModelKey.value = modelKey(s.llmProviderId, s.llmModel);
|
||||
return;
|
||||
}
|
||||
if (!selectedModelKey.value) {
|
||||
selectedModelKey.value = defaultModelKey();
|
||||
}
|
||||
}
|
||||
|
||||
function scrollChatToBottom() {
|
||||
const el = messagePaneRef.value;
|
||||
if (!el) return;
|
||||
el.scrollTop = el.scrollHeight;
|
||||
}
|
||||
|
||||
async function loadEnabledModels() {
|
||||
try {
|
||||
const res = await listAgentEnabledLlmModelsApi();
|
||||
enabledModels.value = res.items || [];
|
||||
if (!selectedModelKey.value) {
|
||||
selectedModelKey.value = defaultModelKey();
|
||||
}
|
||||
} catch {
|
||||
/* 模型列表失败不阻断会话 */
|
||||
}
|
||||
}
|
||||
|
||||
/** 复用或创建本草稿的发布场景会话 */
|
||||
async function ensureSession(): Promise<string | null> {
|
||||
if (session.value?.threadId) return session.value.threadId;
|
||||
const parsed = parseModelKey(selectedModelKey.value);
|
||||
const s = await createAgentSessionApi({
|
||||
title: `发布草稿 #${props.draftId}`,
|
||||
llmProviderId: parsed?.providerId,
|
||||
llmModel: parsed?.model,
|
||||
scene: SCENE,
|
||||
sceneRef: String(props.draftId),
|
||||
reuseBySceneRef: true,
|
||||
});
|
||||
session.value = s;
|
||||
syncSelectedFromSession();
|
||||
return s.threadId;
|
||||
}
|
||||
|
||||
async function loadMessages(threadId: string) {
|
||||
const seq = ++messagesLoadSeq;
|
||||
loadingMessages.value = true;
|
||||
try {
|
||||
const res = await listAgentMessagesApi(threadId);
|
||||
if (seq !== messagesLoadSeq) return;
|
||||
messages.value = (res.items || []).filter(
|
||||
(m) => m.role === 'user' || m.role === 'assistant',
|
||||
);
|
||||
} catch (e: any) {
|
||||
if (seq !== messagesLoadSeq) return;
|
||||
message.error(e?.message || '加载消息失败');
|
||||
} finally {
|
||||
if (seq === messagesLoadSeq) loadingMessages.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function bootstrap() {
|
||||
loadingSession.value = true;
|
||||
messages.value = [];
|
||||
session.value = null;
|
||||
try {
|
||||
await loadEnabledModels();
|
||||
const threadId = await ensureSession();
|
||||
if (threadId) await loadMessages(threadId);
|
||||
} catch (e: any) {
|
||||
message.error(e?.message || '初始化发布助手失败');
|
||||
} finally {
|
||||
loadingSession.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
watch(
|
||||
() => props.draftId,
|
||||
() => {
|
||||
abort?.abort();
|
||||
void bootstrap();
|
||||
},
|
||||
{ immediate: true },
|
||||
);
|
||||
|
||||
async function onModelChange(key: string) {
|
||||
if (!key || !key.includes('::')) return;
|
||||
selectedModelKey.value = key;
|
||||
const parsed = parseModelKey(key);
|
||||
const threadId = session.value?.threadId;
|
||||
if (!threadId || !parsed) return;
|
||||
patchingModel.value = true;
|
||||
try {
|
||||
const s = await patchAgentSessionApi(threadId, {
|
||||
llmProviderId: parsed.providerId,
|
||||
llmModel: parsed.model,
|
||||
});
|
||||
session.value = { ...session.value!, ...s };
|
||||
} catch (e: any) {
|
||||
message.error(e?.message || '切换模型失败');
|
||||
syncSelectedFromSession();
|
||||
} finally {
|
||||
patchingModel.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
function appendStreamToken(t: string) {
|
||||
if (toolStatusActive.value) {
|
||||
toolStatusActive.value = false;
|
||||
toolStatusLabel.value = '';
|
||||
}
|
||||
streamingText.value += t;
|
||||
const idx = messages.value.length - 1;
|
||||
const last = messages.value[idx];
|
||||
if (last?.role === 'assistant') {
|
||||
messages.value[idx] = { ...last, content: streamingText.value };
|
||||
}
|
||||
void nextTick().then(scrollChatToBottom);
|
||||
}
|
||||
|
||||
function onStreamTool(payload: { phase: string; label: string }) {
|
||||
if (payload.phase === 'start') {
|
||||
toolStatusActive.value = true;
|
||||
toolStatusLabel.value = payload.label;
|
||||
void nextTick().then(scrollChatToBottom);
|
||||
} else if (payload.phase === 'end') {
|
||||
toolStatusLabel.value = payload.label;
|
||||
}
|
||||
}
|
||||
|
||||
function onClientTool(call: AgentVO.ClientToolCall) {
|
||||
const api = props.editorApi;
|
||||
if (!api) return;
|
||||
if (call.name === 'ui_get_publish_snapshot') return;
|
||||
const result = api.applyClientTool(call.name, call.args || {});
|
||||
if (!result.ok) {
|
||||
message.warning(result.message || '表单写入失败');
|
||||
}
|
||||
}
|
||||
|
||||
async function send(textOverride?: string) {
|
||||
const text = (textOverride ?? draft.value).trim();
|
||||
if (!text || sending.value) return;
|
||||
|
||||
sending.value = true;
|
||||
let threadId: string | undefined = session.value?.threadId;
|
||||
if (!threadId) {
|
||||
try {
|
||||
threadId = (await ensureSession()) ?? undefined;
|
||||
} catch (e: any) {
|
||||
sending.value = false;
|
||||
message.error(e?.message || '新建会话失败');
|
||||
return;
|
||||
}
|
||||
}
|
||||
if (!threadId) {
|
||||
sending.value = false;
|
||||
return;
|
||||
}
|
||||
|
||||
streamingText.value = '';
|
||||
toolStatusActive.value = false;
|
||||
toolStatusLabel.value = '';
|
||||
draft.value = '';
|
||||
messages.value.push({
|
||||
seq: (messages.value.at(-1)?.seq || 0) + 1,
|
||||
role: 'user',
|
||||
content: text,
|
||||
});
|
||||
messages.value.push({
|
||||
seq: (messages.value.at(-1)?.seq || 0) + 1,
|
||||
role: 'assistant',
|
||||
content: '',
|
||||
});
|
||||
await nextTick();
|
||||
scrollChatToBottom();
|
||||
|
||||
const formSnapshot = props.editorApi?.getFormSnapshot() as
|
||||
| Record<string, unknown>
|
||||
| undefined;
|
||||
|
||||
abort?.abort();
|
||||
abort = streamAgentChat({
|
||||
threadId,
|
||||
content: text,
|
||||
formSnapshot,
|
||||
onToken: appendStreamToken,
|
||||
onTool: onStreamTool,
|
||||
onClientTool,
|
||||
onDone: () => {
|
||||
const finalText = streamingText.value;
|
||||
const idx = messages.value.length - 1;
|
||||
const last = messages.value[idx];
|
||||
if (last?.role === 'assistant') {
|
||||
messages.value[idx] = { ...last, content: finalText || last.content };
|
||||
}
|
||||
sending.value = false;
|
||||
streamingText.value = '';
|
||||
toolStatusActive.value = false;
|
||||
toolStatusLabel.value = '';
|
||||
},
|
||||
onError: (msg) => {
|
||||
sending.value = false;
|
||||
const idx = messages.value.length - 1;
|
||||
const last = messages.value[idx];
|
||||
if (last?.role === 'assistant' && !last.content && !streamingText.value) {
|
||||
messages.value[idx] = { ...last, content: `错误:${msg}` };
|
||||
}
|
||||
streamingText.value = '';
|
||||
toolStatusActive.value = false;
|
||||
toolStatusLabel.value = '';
|
||||
message.error(msg);
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
function applyStarterPrompt(text: string) {
|
||||
draft.value = text;
|
||||
}
|
||||
|
||||
function onStop() {
|
||||
abort?.abort();
|
||||
sending.value = false;
|
||||
toolStatusActive.value = false;
|
||||
toolStatusLabel.value = '';
|
||||
}
|
||||
|
||||
onBeforeUnmount(() => abort?.abort());
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<!-- 收起:窄条 -->
|
||||
<div
|
||||
v-if="collapsed"
|
||||
class="border-border bg-card flex h-full w-14 shrink-0 flex-col items-center border-l py-3"
|
||||
>
|
||||
<Tooltip title="展开发布助手" placement="left">
|
||||
<Button type="text" @click="emit('expand')">
|
||||
<template #icon><MenuUnfoldOutlined /></template>
|
||||
</Button>
|
||||
</Tooltip>
|
||||
<div
|
||||
class="text-muted-foreground mt-4 write-vertical-right text-xs tracking-widest"
|
||||
style="writing-mode: vertical-rl"
|
||||
>
|
||||
发布助手
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 展开 -->
|
||||
<aside
|
||||
v-else
|
||||
class="border-border bg-card flex h-full min-h-0 w-full min-w-[280px] flex-col border-l"
|
||||
>
|
||||
<header
|
||||
class="flex h-12 shrink-0 items-center gap-2 border-b border-border px-3"
|
||||
>
|
||||
<span class="min-w-0 flex-1 truncate text-sm font-medium">发布助手</span>
|
||||
<Select
|
||||
:value="selectedModelKey"
|
||||
:options="modelOptions"
|
||||
:loading="patchingModel"
|
||||
:disabled="sending || enabledModels.length === 0"
|
||||
placeholder="模型"
|
||||
class="w-36 shrink-0"
|
||||
size="small"
|
||||
:allow-clear="false"
|
||||
@change="(v) => onModelChange(String(v ?? ''))"
|
||||
/>
|
||||
<Tooltip title="收起">
|
||||
<Button type="text" size="small" @click="emit('collapse')">
|
||||
<template #icon><MenuFoldOutlined /></template>
|
||||
</Button>
|
||||
</Tooltip>
|
||||
</header>
|
||||
|
||||
<div class="relative flex min-h-0 flex-1 flex-col">
|
||||
<div
|
||||
v-if="loadingSession || loadingMessages"
|
||||
class="absolute inset-0 z-10 flex items-center justify-center bg-background/50"
|
||||
>
|
||||
<Spin size="small" />
|
||||
</div>
|
||||
|
||||
<div
|
||||
ref="messagePaneRef"
|
||||
class="publish-agent-chat t-chat t-chat--normal min-h-0 flex-1 overflow-y-auto py-3"
|
||||
>
|
||||
<div
|
||||
v-if="showStarter"
|
||||
class="flex h-full flex-col justify-center px-1 py-4"
|
||||
>
|
||||
<div class="text-sm font-medium">帮你完善本页草稿</div>
|
||||
<p class="text-muted-foreground mt-2 text-xs leading-5">
|
||||
可按已填 SKU 编码查内部/拼多多商品,生成标题并写回规格轴。改表单会直接落到左侧编辑区。
|
||||
</p>
|
||||
<div class="mt-3 flex flex-col gap-1.5">
|
||||
<button
|
||||
v-for="item in starterPrompts"
|
||||
:key="item"
|
||||
type="button"
|
||||
class="hover:border-primary hover:bg-primary/5 rounded-md border border-border bg-background px-2.5 py-1.5 text-left text-xs transition-colors"
|
||||
@click="applyStarterPrompt(item)"
|
||||
>
|
||||
{{ item }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<Empty
|
||||
v-else-if="!loadingSession && !loadingMessages && messages.length === 0"
|
||||
class="mt-16"
|
||||
description="开始提问吧"
|
||||
/>
|
||||
<ChatItem
|
||||
v-for="item in bubbleViews"
|
||||
:key="item.id"
|
||||
class="publish-agent-item"
|
||||
:role="item.role"
|
||||
:name="item.name"
|
||||
:content="item.content"
|
||||
:text-loading="item.textLoading"
|
||||
variant="base"
|
||||
animation="gradient"
|
||||
/>
|
||||
<div
|
||||
v-if="toolStatusActive && toolStatusLabel"
|
||||
class="text-muted-foreground flex items-center gap-2 px-1 py-1 text-xs"
|
||||
>
|
||||
<span
|
||||
class="border-primary/40 inline-block size-3 animate-spin rounded-full border-2 border-t-transparent"
|
||||
/>
|
||||
<span>{{ toolStatusLabel }}…</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="shrink-0 border-t border-border p-2">
|
||||
<div class="flex gap-1.5">
|
||||
<Input.TextArea
|
||||
v-model:value="draft"
|
||||
:auto-size="{ minRows: 2, maxRows: 5 }"
|
||||
:disabled="sending"
|
||||
placeholder="描述你想改的标题、规格…"
|
||||
class="flex-1"
|
||||
@keydown.enter.exact.prevent="() => send()"
|
||||
/>
|
||||
<div class="flex flex-col gap-1">
|
||||
<Button
|
||||
v-if="sending"
|
||||
type="default"
|
||||
size="small"
|
||||
@click="onStop"
|
||||
>
|
||||
停止
|
||||
</Button>
|
||||
<Button
|
||||
v-else
|
||||
type="primary"
|
||||
size="small"
|
||||
:disabled="!draft.trim()"
|
||||
@click="() => send()"
|
||||
>
|
||||
<template #icon><SendOutlined /></template>
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</aside>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
/*
|
||||
* TDesign `.t-chat { padding: 0 }` 会盖掉 Tailwind px-*,容器左右留白写这里。
|
||||
* 不要动 `.t-chat__detail` 的 padding,那是气泡内文字边距。
|
||||
*/
|
||||
.publish-agent-chat.t-chat {
|
||||
--td-bg-color-container: transparent;
|
||||
padding: 12px 16px !important;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
.publish-agent-item {
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
.publish-agent-item :deep(.t-chat__inner) {
|
||||
box-sizing: border-box;
|
||||
padding-inline: 4px;
|
||||
}
|
||||
.publish-agent-item :deep(.t-chat__content) {
|
||||
width: auto;
|
||||
max-width: calc(100% - 8px);
|
||||
}
|
||||
.publish-agent-item :deep(.t-chat__inner.user) {
|
||||
justify-content: flex-end;
|
||||
}
|
||||
.publish-agent-item :deep(.t-chat__avatar),
|
||||
.publish-agent-item :deep(.t-chat__name) {
|
||||
display: none;
|
||||
}
|
||||
</style>
|
||||
@@ -1,10 +1,14 @@
|
||||
<script lang="ts" setup>
|
||||
import { computed } from 'vue';
|
||||
import { computed, ref } from 'vue';
|
||||
import { useRoute, useRouter } from 'vue-router';
|
||||
|
||||
import { Page } from '@vben/common-ui';
|
||||
|
||||
import { useColSidebarLayout } from '#/store/col-sidebar-layout';
|
||||
|
||||
import PddGoodsPublishEditor from '../components/PddGoodsPublishEditor.vue';
|
||||
import PddPublishAgentPanel from './PddPublishAgentPanel.vue';
|
||||
import type { PublishEditorAgentApi } from './publish-agent-commands';
|
||||
|
||||
defineOptions({ name: 'PddGoodsPublishDeskEdit' });
|
||||
|
||||
@@ -17,6 +21,23 @@ const draftId = computed(() => {
|
||||
return Number.isFinite(n) ? n : null;
|
||||
});
|
||||
|
||||
const editorRef = ref<PublishEditorAgentApi | null>(null);
|
||||
const { width: agentWidthPct, collapsed: agentCollapsed } =
|
||||
useColSidebarLayout('pdd-publish-agent');
|
||||
|
||||
const agentPaneStyle = computed(() => {
|
||||
if (agentCollapsed.value) {
|
||||
return { width: '56px', flex: '0 0 56px' };
|
||||
}
|
||||
const pct = Math.min(42, Math.max(22, agentWidthPct.value));
|
||||
return {
|
||||
width: `${pct}%`,
|
||||
flex: `0 0 ${pct}%`,
|
||||
maxWidth: '480px',
|
||||
minWidth: '300px',
|
||||
};
|
||||
});
|
||||
|
||||
function goBack() {
|
||||
void router.push('/pdd/goods/publish');
|
||||
}
|
||||
@@ -47,15 +68,35 @@ function goBack() {
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<PddGoodsPublishEditor
|
||||
<div
|
||||
v-if="draftId"
|
||||
class="h-full min-h-0"
|
||||
variant="page"
|
||||
:open="true"
|
||||
:draft-id="draftId"
|
||||
@close="goBack"
|
||||
@success="goBack"
|
||||
@draft-saved="() => undefined"
|
||||
/>
|
||||
class="flex min-h-0 flex-1 overflow-hidden"
|
||||
>
|
||||
<div class="flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden">
|
||||
<PddGoodsPublishEditor
|
||||
ref="editorRef"
|
||||
class="h-full min-h-0"
|
||||
variant="page"
|
||||
:open="true"
|
||||
:draft-id="draftId"
|
||||
@close="goBack"
|
||||
@success="goBack"
|
||||
@draft-saved="() => undefined"
|
||||
/>
|
||||
</div>
|
||||
<div
|
||||
class="flex h-full min-h-0 shrink-0 flex-col overflow-hidden"
|
||||
:style="agentPaneStyle"
|
||||
>
|
||||
<PddPublishAgentPanel
|
||||
class="h-full min-h-0"
|
||||
:draft-id="draftId"
|
||||
:collapsed="agentCollapsed"
|
||||
:editor-api="editorRef"
|
||||
@expand="agentCollapsed = false"
|
||||
@collapse="agentCollapsed = true"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</Page>
|
||||
</template>
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
/**
|
||||
* 发布编辑器暴露给智能体栏的命令面:读快照 + 执行 ui_* 前端工具。
|
||||
*/
|
||||
|
||||
export type PublishSpecAxisSnapshot = {
|
||||
name: string;
|
||||
values: string[];
|
||||
catalogKey?: string;
|
||||
};
|
||||
|
||||
export type PublishSkuRowSnapshot = {
|
||||
skuName: string;
|
||||
outSkuSn: string;
|
||||
quantity: number;
|
||||
weight: number;
|
||||
saleValues: Record<string, string>;
|
||||
internalSkuId?: number;
|
||||
productName?: string;
|
||||
internalSkuName?: string;
|
||||
};
|
||||
|
||||
/** 注入 Agent 的表单快照(瘦字段,避免图片等大对象) */
|
||||
export type PublishFormSnapshot = {
|
||||
goodsName: string;
|
||||
goodsDesc: string;
|
||||
pddShopId?: number;
|
||||
catId?: number;
|
||||
marketPriceYuan?: number;
|
||||
costTemplateId?: number;
|
||||
shipmentLimitSecond?: number;
|
||||
twoPiecesDiscount?: number;
|
||||
specAxes: PublishSpecAxisSnapshot[];
|
||||
skuRows: PublishSkuRowSnapshot[];
|
||||
/** 当前类目可选规格维,便于模型选对轴名 */
|
||||
specCatalog: Array<{ name: string; catalogKey: string }>;
|
||||
};
|
||||
|
||||
export type ClientToolResult = {
|
||||
ok: boolean;
|
||||
message: string;
|
||||
};
|
||||
|
||||
/** 编辑器 defineExpose 契约 */
|
||||
export type PublishEditorAgentApi = {
|
||||
getFormSnapshot: () => PublishFormSnapshot;
|
||||
applyClientTool: (
|
||||
name: string,
|
||||
args: Record<string, unknown>,
|
||||
) => ClientToolResult;
|
||||
};
|
||||
Reference in New Issue
Block a user