mirror of
https://gitee.com/qqtt-ah/ecom-dmb.git
synced 2026-11-23 23:19:19 +08:00
108 lines
4.1 KiB
Python
108 lines
4.1 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 domain.models import ChatMessage, LlmRuntimeConfig, MessageRole
|
|
from domain.ports import ChatStreamer
|
|
|
|
_BASE_SYSTEM = (
|
|
"你是电商 DMB 系统的经营助手。回答简洁、可执行。"
|
|
"需要经营数据时优先调用可用工具;缺少参数时向用户确认。"
|
|
"若工具失败或无权限,请说明原因并给出可操作建议。"
|
|
)
|
|
|
|
|
|
class OpenAICompatibleStreamer(ChatStreamer):
|
|
async def stream_reply(
|
|
self,
|
|
*,
|
|
llm: LlmRuntimeConfig,
|
|
history: list[ChatMessage],
|
|
user_text: str,
|
|
memory_lines: list[str] | None = None,
|
|
tools: list[Any] | None = None,
|
|
) -> AsyncIterator[str]:
|
|
system = _BASE_SYSTEM
|
|
if memory_lines:
|
|
joined = "\n".join(f"- {line}" for line in memory_lines[:20])
|
|
system += f"\n\n以下是关于当前用户的长期记忆(可能过时,请谨慎引用):\n{joined}"
|
|
|
|
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 text
|
|
return
|
|
|
|
# 工具轮:先非流式执行 tool_calls,最后一轮流式输出正文
|
|
bound = model.bind_tools(tools)
|
|
tool_map = {t.name: t for t in tools if getattr(t, "name", None)}
|
|
for _ in range(5):
|
|
ai = await bound.ainvoke(messages)
|
|
messages.append(ai)
|
|
tool_calls = getattr(ai, "tool_calls", None) or []
|
|
if not tool_calls:
|
|
content = ai.content if isinstance(ai.content, str) else _chunk_text(ai.content)
|
|
if content:
|
|
# 按小段 yield,便于前端渐进展示
|
|
step = 24
|
|
for i in range(0, len(content), step):
|
|
yield content[i : i + step]
|
|
return
|
|
|
|
yield f"\n[调用工具: {', '.join(tc.get('name', '?') for tc in tool_calls)}]\n"
|
|
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))
|
|
|
|
yield "工具调用轮次过多,请缩小问题范围后重试。"
|
|
|
|
|
|
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 ""
|