mirror of
https://gitee.com/qqtt-ah/ecom-dmb.git
synced 2026-11-25 03:09:19 +08:00
feat: 重构 Agent 目录为 api/agent/infrastructure 分层并更新启动入口
This commit is contained in:
@@ -0,0 +1,122 @@
|
||||
"""按租户构建 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 后再查数,不要向用户索要日期范围。"
|
||||
"用户用名称或编码指代店铺、商品、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,
|
||||
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 ""
|
||||
@@ -0,0 +1,49 @@
|
||||
"""从 Server 内部接口拉取 LLM 运行时配置。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
|
||||
import httpx
|
||||
|
||||
from config.settings import Settings
|
||||
from domain.models import LlmRuntimeConfig
|
||||
from domain.ports import LlmRuntimeGateway
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class ServerLlmRuntimeGateway(LlmRuntimeGateway):
|
||||
"""GET /api/internal/agent/llm-runtime?companyId=…(Agent Bearer)。"""
|
||||
|
||||
def __init__(self, settings: Settings) -> None:
|
||||
self._settings = settings
|
||||
|
||||
async def fetch(self, company_id: int) -> LlmRuntimeConfig | None:
|
||||
url = f"{self._settings.server_base_url.rstrip('/')}/api/internal/agent/llm-runtime"
|
||||
headers = {"Authorization": f"Bearer {self._settings.mcp_bearer_token}"}
|
||||
try:
|
||||
async with httpx.AsyncClient(timeout=15.0) as client:
|
||||
resp = await client.get(
|
||||
url, params={"companyId": company_id}, headers=headers
|
||||
)
|
||||
if resp.status_code == 400:
|
||||
# 未配置
|
||||
return None
|
||||
resp.raise_for_status()
|
||||
body = resp.json()
|
||||
data = body.get("data") if isinstance(body, dict) else None
|
||||
if not isinstance(data, dict):
|
||||
return None
|
||||
return LlmRuntimeConfig(
|
||||
base_url=str(data.get("baseUrl") or "").rstrip("/"),
|
||||
api_key=str(data.get("apiKey") or ""),
|
||||
model=str(data.get("model") or ""),
|
||||
extra_headers={
|
||||
str(k): str(v)
|
||||
for k, v in (data.get("extraHeaders") or {}).items()
|
||||
},
|
||||
)
|
||||
except Exception:
|
||||
logger.exception("拉取 Server LLM runtime 失败 company_id=%s", company_id)
|
||||
return None
|
||||
Reference in New Issue
Block a user