feat: 新增agent

This commit is contained in:
2026-09-18 17:34:38 +08:00
parent 0d9b5a21c2
commit bc73668737
64 changed files with 3293 additions and 18 deletions
+35
View File
@@ -0,0 +1,35 @@
"""JWT 校验(对齐 Java JwtUtils:HS512,sub=userId,claim companyId)。"""
from __future__ import annotations
from typing import Any
import jwt
from fastapi import HTTPException, status
from config.settings import Settings
from domain.models import Actor
def parse_actor(settings: Settings, token: str) -> Actor:
try:
payload: dict[str, Any] = jwt.decode(
token,
settings.jwt_secret,
algorithms=[a.strip() for a in settings.jwt_algorithms.split(",") if a.strip()],
options={"require": ["sub", "exp"]},
)
except jwt.PyJWTError as e:
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail=f"无效令牌: {e}") from e
user_id = payload.get("sub")
company_id = payload.get("companyId")
if not user_id or company_id is None:
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="令牌缺少用户或公司信息")
return Actor(
user_id=str(user_id),
company_id=int(company_id),
company_role=payload.get("companyRole"),
is_super=bool(payload.get("super", False)),
)
+107
View File
@@ -0,0 +1,107 @@
"""按租户构建 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 ""
+45
View File
@@ -0,0 +1,45 @@
"""MCP 工具加载(按请求注入公司/用户头)。"""
from __future__ import annotations
import logging
from typing import Any
from config.settings import Settings
logger = logging.getLogger(__name__)
async def load_mcp_tools(
settings: Settings, *, company_id: int, user_id: str
) -> list[Any]:
if not settings.mcp_tools_enabled or not settings.mcp_bearer_token:
return []
try:
from langchain_mcp_adapters.client import MultiServerMCPClient
except ImportError:
logger.warning("未安装 langchain-mcp-adapters,跳过 MCP tools")
return []
headers = {
"Authorization": f"Bearer {settings.mcp_bearer_token}",
"X-Agent-Company-Id": str(company_id),
"X-Agent-User-Id": str(user_id),
}
try:
client = MultiServerMCPClient(
{
"ecom-dmb": {
"url": settings.mcp_base_url,
"transport": "streamable_http",
"headers": headers,
}
}
)
tools = await client.get_tools()
return list(tools or [])
except Exception:
logger.exception(
"加载 MCP tools 失败 company_id=%s(将降级为无工具对话)", company_id
)
return []
+43
View File
@@ -0,0 +1,43 @@
"""Mongo 连接与索引。"""
from __future__ import annotations
from motor.motor_asyncio import AsyncIOMotorClient, AsyncIOMotorDatabase
from config.settings import Settings
_client: AsyncIOMotorClient | None = None
async def get_db(settings: Settings) -> AsyncIOMotorDatabase:
global _client
if _client is None:
_client = AsyncIOMotorClient(settings.mongo_uri)
return _client[settings.mongo_db]
async def ensure_indexes(db: AsyncIOMotorDatabase) -> None:
await db.agent_sessions.create_index(
[("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)]
)
await db.agent_messages.create_index(
[("company_id", 1), ("user_id", 1), ("thread_id", 1), ("seq", 1)]
)
await db.agent_user_memory.create_index(
[("company_id", 1), ("user_id", 1), ("status", 1), ("kind", 1), ("updated_at", -1)]
)
await db.agent_user_memory.create_index(
[("company_id", 1), ("user_id", 1), ("key", 1)],
unique=True,
partialFilterExpression={"key": {"$type": "string"}},
)
async def close_mongo() -> None:
global _client
if _client is not None:
_client.close()
_client = None
@@ -0,0 +1,246 @@
"""会话 / 消息 / 用户记忆 Mongo 实现。"""
from __future__ import annotations
from datetime import datetime
from typing import Any
from bson import ObjectId
from motor.motor_asyncio import AsyncIOMotorDatabase
from domain.models import (
ChatMessage,
MemoryKind,
MemoryStatus,
MessageRole,
Session,
SessionStatus,
UserMemory,
)
from domain.ports import MemoryRepository, MessageRepository, SessionRepository
def _dt(v: Any) -> datetime:
if isinstance(v, datetime):
return v
return datetime.utcnow()
class MongoSessionRepository(SessionRepository):
def __init__(self, db: AsyncIOMotorDatabase) -> None:
self._col = db.agent_sessions
async def create(self, session: Session) -> Session:
doc = {
"thread_id": session.thread_id,
"company_id": session.company_id,
"user_id": session.user_id,
"title": session.title,
"status": session.status.value,
"summary": session.summary,
"created_at": session.created_at,
"updated_at": session.updated_at,
"last_message_at": session.last_message_at,
}
await self._col.insert_one(doc)
return session
async def get(self, company_id: int, user_id: str, thread_id: str) -> Session | None:
doc = await self._col.find_one(
{"company_id": company_id, "user_id": user_id, "thread_id": thread_id}
)
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]:
cursor = (
self._col.find(
{
"company_id": company_id,
"user_id": user_id,
"status": SessionStatus.ACTIVE.value,
}
)
.sort("updated_at", -1)
.limit(limit)
)
return [self._to_session(d) async for d in cursor]
async def update(self, session: Session) -> Session:
session.updated_at = datetime.utcnow()
await self._col.update_one(
{
"company_id": session.company_id,
"user_id": session.user_id,
"thread_id": session.thread_id,
},
{
"$set": {
"title": session.title,
"status": session.status.value,
"summary": session.summary,
"updated_at": session.updated_at,
"last_message_at": session.last_message_at,
}
},
)
return session
@staticmethod
def _to_session(doc: dict[str, Any]) -> Session:
return Session(
thread_id=doc["thread_id"],
company_id=int(doc["company_id"]),
user_id=str(doc["user_id"]),
title=doc.get("title") or "新对话",
status=SessionStatus(doc.get("status") or SessionStatus.ACTIVE.value),
summary=doc.get("summary"),
created_at=_dt(doc.get("created_at")),
updated_at=_dt(doc.get("updated_at")),
last_message_at=doc.get("last_message_at"),
)
class MongoMessageRepository(MessageRepository):
def __init__(self, db: AsyncIOMotorDatabase) -> None:
self._col = db.agent_messages
async def next_seq(self, company_id: int, user_id: str, thread_id: str) -> int:
doc = await self._col.find_one(
{"company_id": company_id, "user_id": user_id, "thread_id": thread_id},
sort=[("seq", -1)],
projection={"seq": 1},
)
return 1 if doc is None else int(doc["seq"]) + 1
async def append(self, message: ChatMessage) -> ChatMessage:
doc = {
"company_id": message.company_id,
"user_id": message.user_id,
"thread_id": message.thread_id,
"seq": message.seq,
"role": message.role.value,
"content": message.content,
"tool_name": message.tool_name,
"tool_call_id": message.tool_call_id,
"created_at": message.created_at,
}
result = await self._col.insert_one(doc)
message.id = str(result.inserted_id)
return message
async def list_recent(
self, company_id: int, user_id: str, thread_id: str, limit: int
) -> list[ChatMessage]:
cursor = (
self._col.find(
{"company_id": company_id, "user_id": user_id, "thread_id": thread_id}
)
.sort("seq", -1)
.limit(limit)
)
rows = [self._to_msg(d) async for d in cursor]
rows.reverse()
return rows
@staticmethod
def _to_msg(doc: dict[str, Any]) -> ChatMessage:
return ChatMessage(
id=str(doc.get("_id")),
company_id=int(doc["company_id"]),
user_id=str(doc["user_id"]),
thread_id=doc["thread_id"],
seq=int(doc["seq"]),
role=MessageRole(doc["role"]),
content=doc.get("content") or "",
tool_name=doc.get("tool_name"),
tool_call_id=doc.get("tool_call_id"),
created_at=_dt(doc.get("created_at")),
)
class MongoMemoryRepository(MemoryRepository):
def __init__(self, db: AsyncIOMotorDatabase) -> None:
self._col = db.agent_user_memory
async def list_active(
self, company_id: int, user_id: str, limit: int
) -> list[UserMemory]:
cursor = (
self._col.find(
{
"company_id": company_id,
"user_id": user_id,
"status": MemoryStatus.ACTIVE.value,
}
)
.sort("updated_at", -1)
.limit(limit)
)
return [self._to_mem(d) async for d in cursor]
async def upsert(self, memory: UserMemory) -> UserMemory:
memory.updated_at = datetime.utcnow()
payload = {
"company_id": memory.company_id,
"user_id": memory.user_id,
"kind": memory.kind.value,
"key": memory.key,
"text": memory.text,
"value": memory.value,
"source_thread_id": memory.source_thread_id,
"status": memory.status.value,
"confidence": memory.confidence,
"updated_at": memory.updated_at,
}
if memory.key:
existing = await self._col.find_one(
{
"company_id": memory.company_id,
"user_id": memory.user_id,
"key": memory.key,
"status": {"$ne": MemoryStatus.DELETED.value},
}
)
if existing:
await self._col.update_one({"_id": existing["_id"]}, {"$set": payload})
memory.id = str(existing["_id"])
memory.created_at = _dt(existing.get("created_at"))
return memory
payload["created_at"] = memory.created_at
result = await self._col.insert_one(payload)
memory.id = str(result.inserted_id)
return memory
async def soft_delete(self, company_id: int, user_id: str, memory_id: str) -> bool:
try:
oid = ObjectId(memory_id)
except Exception:
return False
result = await self._col.update_one(
{"_id": oid, "company_id": company_id, "user_id": user_id},
{
"$set": {
"status": MemoryStatus.DELETED.value,
"updated_at": datetime.utcnow(),
}
},
)
return result.modified_count > 0
@staticmethod
def _to_mem(doc: dict[str, Any]) -> UserMemory:
return UserMemory(
id=str(doc.get("_id")),
company_id=int(doc["company_id"]),
user_id=str(doc["user_id"]),
kind=MemoryKind(doc.get("kind") or MemoryKind.FACT.value),
key=doc.get("key"),
text=doc.get("text") or "",
value=doc.get("value") or {},
source_thread_id=doc.get("source_thread_id"),
status=MemoryStatus(doc.get("status") or MemoryStatus.ACTIVE.value),
confidence=float(doc.get("confidence") or 0.8),
created_at=_dt(doc.get("created_at")),
updated_at=_dt(doc.get("updated_at")),
)
+61
View File
@@ -0,0 +1,61 @@
"""Redis 缓存租户 LLM 运行时配置。"""
from __future__ import annotations
import json
import redis.asyncio as redis
from config.settings import Settings
from domain.models import LlmRuntimeConfig
from domain.ports import LlmRuntimeCache
class RedisLlmRuntimeCache(LlmRuntimeCache):
def __init__(self, client: redis.Redis) -> None:
self._r = client
@staticmethod
def _key(company_id: int) -> str:
return f"agent:llm:rt:{company_id}"
async def get(self, company_id: int) -> LlmRuntimeConfig | None:
raw = await self._r.get(self._key(company_id))
if not raw:
return None
data = json.loads(raw)
return LlmRuntimeConfig(
base_url=data["base_url"],
api_key=data["api_key"],
model=data["model"],
extra_headers=data.get("extra_headers") or {},
)
async def set(self, company_id: int, config: LlmRuntimeConfig, ttl_seconds: int) -> None:
payload = {
"base_url": config.base_url,
"api_key": config.api_key,
"model": config.model,
"extra_headers": config.extra_headers,
}
await self._r.set(self._key(company_id), json.dumps(payload), ex=ttl_seconds)
async def delete(self, company_id: int) -> None:
await self._r.delete(self._key(company_id))
_redis: redis.Redis | None = None
def get_redis(settings: Settings) -> redis.Redis:
global _redis
if _redis is None:
_redis = redis.from_url(settings.redis_url, decode_responses=True)
return _redis
async def close_redis() -> None:
global _redis
if _redis is not None:
await _redis.aclose()
_redis = None
@@ -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