Files
ecom-dmb/apps/agent/infrastructure/llm_factory.py
T

119 lines
4.6 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""按租户构建 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 系统的经营助手。回答简洁、可执行。"
"需要经营数据时优先调用可用工具。"
"用户说近 N 天、昨天、本周、本月等相对日期时,先调用 get_current_time,"
"用返回的 ranges 或 today 换算 yyyy-MM-dd 后再查数,不要向用户索要日期范围。"
"仅当缺少店铺、商品等业务标识时才向用户确认。"
"若工具失败或无权限,请说明原因并给出可操作建议。"
)
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
# 工具轮:每轮用 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 text
if gathered is None:
yield "(模型未返回内容)"
return
messages.append(gathered)
tool_calls = getattr(gathered, "tool_calls", None) or []
if not tool_calls:
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 ""