mirror of
https://gitee.com/qqtt-ah/ecom-dmb.git
synced 2026-11-23 23:19:19 +08:00
156 lines
6.6 KiB
Python
156 lines
6.6 KiB
Python
"""按租户构建 OpenAI Compatible Chat 模型并流式输出(可带 MCP tools)。"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import json
|
||
from typing import Any, AsyncIterator
|
||
|
||
from langchain_core.messages import AIMessage, HumanMessage, SystemMessage, ToolMessage
|
||
from langchain_openai import ChatOpenAI
|
||
|
||
from agent.tools.labels import tool_status_label
|
||
from domain.models import ChatMessage, LlmRuntimeConfig, MessageRole, StreamEvent
|
||
from domain.ports import ChatStreamer
|
||
|
||
_BASE_SYSTEM = (
|
||
"你是电商 DMB 系统的经营助手。回答简洁、可执行。"
|
||
"需要经营数据时优先调用可用工具。"
|
||
"你具备跨会话的用户级长期记忆,但内容不会自动注入对话。"
|
||
"需要称呼、偏好或用户事实时:先 memory_search,必要时再 memory_load;"
|
||
"禁止编造未载入的记忆,也不要声称没有长期记忆能力。"
|
||
"向用户介绍记忆时:用自然语言短列表(如「我记得你希望被叫做 ahua」),"
|
||
"禁止输出 ref、Mongo id、字段名、更新时间或表格。"
|
||
"用户问「有哪些记忆」时:search 后直接按摘要口头列举即可,不必强行 load。"
|
||
"用户要求记住某事:可用 memory_save,或若系统提示「本轮已写入长期记忆」则明确确认已跨会话保存;确认时只复述内容。"
|
||
"用户说近 N 天、昨天、本周、本月等相对日期时,先调用 get_current_time,"
|
||
"用返回的 ranges 或 today 换算 yyyy-MM-dd 后再查数,不要向用户索要日期范围。"
|
||
"用户用名称或编码指代店铺、商品、SKU 时,先调用 catalog_search;"
|
||
"恰好一条就用返回的 id 继续查数;多条只列名称和编码让用户选。"
|
||
"用户消息含 [引用] 且带 id= 时,直接用这些 id,不必再搜索,也不要向用户复述 id。"
|
||
"禁止向用户索要店铺 ID、商品 ID 或 SKU ID。"
|
||
"若只给了引用、没有具体问题,按近 7 天概览回答该对象。"
|
||
"若工具失败或无权限,请说明原因并给出可操作建议。"
|
||
)
|
||
|
||
|
||
class OpenAICompatibleStreamer(ChatStreamer):
|
||
async def stream_reply(
|
||
self,
|
||
*,
|
||
llm: LlmRuntimeConfig,
|
||
history: list[ChatMessage],
|
||
user_text: str,
|
||
tools: list[Any] | None = None,
|
||
memory_count: int = 0,
|
||
memory_just_saved: str | None = None,
|
||
) -> AsyncIterator[StreamEvent]:
|
||
system = _BASE_SYSTEM
|
||
if memory_count > 0:
|
||
system += f"\n\n当前用户约有 {memory_count} 条长期记忆,需要时用 memory_search / memory_load。"
|
||
if memory_just_saved:
|
||
system += f"\n\n【本轮已写入长期记忆】{memory_just_saved}"
|
||
|
||
model = ChatOpenAI(
|
||
api_key=llm.api_key,
|
||
base_url=llm.base_url,
|
||
model=llm.model,
|
||
temperature=0.3,
|
||
streaming=True,
|
||
default_headers=llm.extra_headers or None,
|
||
)
|
||
messages: list[Any] = [SystemMessage(content=system)]
|
||
for m in history:
|
||
if m.role == MessageRole.USER:
|
||
messages.append(HumanMessage(content=m.content))
|
||
elif m.role == MessageRole.ASSISTANT:
|
||
messages.append(AIMessage(content=m.content))
|
||
messages.append(HumanMessage(content=user_text))
|
||
|
||
if not tools:
|
||
async for chunk in model.astream(messages):
|
||
text = _chunk_text(chunk.content)
|
||
if text:
|
||
yield StreamEvent.token(text)
|
||
return
|
||
|
||
# 工具轮:每轮用 astream 边生成边推 token;出现 tool_call 再执行工具后继续
|
||
bound = model.bind_tools(tools)
|
||
tool_map = {t.name: t for t in tools if getattr(t, "name", None)}
|
||
for _ in range(5):
|
||
gathered = None
|
||
saw_tool = False
|
||
async for chunk in bound.astream(messages):
|
||
gathered = chunk if gathered is None else gathered + chunk
|
||
if getattr(chunk, "tool_call_chunks", None) or getattr(chunk, "tool_calls", None):
|
||
saw_tool = True
|
||
continue
|
||
if saw_tool:
|
||
continue
|
||
text = _chunk_text(getattr(chunk, "content", None))
|
||
if text:
|
||
yield StreamEvent.token(text)
|
||
if gathered is None:
|
||
yield StreamEvent.token("(模型未返回内容)")
|
||
return
|
||
messages.append(gathered)
|
||
tool_calls = getattr(gathered, "tool_calls", None) or []
|
||
if not tool_calls:
|
||
return
|
||
|
||
# 去重保序的工具状态(同轮多次同名只显示一次文案)
|
||
seen: set[str] = set()
|
||
for tc in tool_calls:
|
||
name = tc.get("name") or ""
|
||
if name in seen:
|
||
continue
|
||
seen.add(name)
|
||
yield StreamEvent.tool(
|
||
phase="start",
|
||
name=name,
|
||
label=tool_status_label(name),
|
||
)
|
||
|
||
for tc in tool_calls:
|
||
name = tc.get("name") or ""
|
||
args = tc.get("args") or {}
|
||
call_id = tc.get("id") or name
|
||
tool = tool_map.get(name)
|
||
try:
|
||
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(ToolMessage(content=str(result)[:8000], tool_call_id=call_id))
|
||
|
||
for name in seen:
|
||
yield StreamEvent.tool(
|
||
phase="end",
|
||
name=name,
|
||
label=tool_status_label(name),
|
||
)
|
||
|
||
yield StreamEvent.token("工具调用轮次过多,请缩小问题范围后重试。")
|
||
|
||
|
||
def _chunk_text(content: Any) -> str:
|
||
if isinstance(content, str):
|
||
return content
|
||
if isinstance(content, list):
|
||
parts: list[str] = []
|
||
for part in content:
|
||
if isinstance(part, dict) and part.get("type") == "text":
|
||
t = part.get("text")
|
||
if t:
|
||
parts.append(str(t))
|
||
elif isinstance(part, str):
|
||
parts.append(part)
|
||
return "".join(parts)
|
||
return ""
|