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
+14
View File
@@ -0,0 +1,14 @@
JWT_SECRET=your-secret-key-here-must-be-at-least-64-bytes-long-for-hs512-algorithm-security
MONGO_URI=mongodb://ecom_dmb_agent_dev:ecom_dmb_agent_dev@192.168.3.100:27017/?authSource=ecom_dmb_agent_dev
MONGO_DB=ecom_dmb_agent_dev
# 与 Server 同 Redis DB,共享 agent:llm:rt:* 缓存
REDIS_URL=redis://:redis_qinghua@192.168.3.100:6379/2
SERVER_BASE_URL=http://localhost:8080
LLM_FALLBACK_ENABLED=true
LLM_FALLBACK_BASE_URL=https://api.deepseek.com/v1
LLM_FALLBACK_API_KEY=
LLM_FALLBACK_MODEL=deepseek-chat
CORS_ORIGINS=http://localhost:5173,http://localhost:5666
MCP_BASE_URL=http://localhost:8080/mcp
MCP_BEARER_TOKEN=dev-agent-mcp-token
MCP_TOOLS_ENABLED=true
+10
View File
@@ -0,0 +1,10 @@
.venv/
__pycache__/
*.py[cod]
.env
.pytest_cache/
.mypy_cache/
.ruff_cache/
*.egg-info/
dist/
build/
+337
View File
@@ -0,0 +1,337 @@
# Agent 客户端设计方案(v1)
> 状态:**已拍板,按本文落地**(2026-09-18)
> 范围:`apps/agent`(Python LangGraph)+ `apps/web` 独立聊天页 + 现有 `apps/server` MCP 增强
> 非目标:不直连业务库;不替代 Open API;不做公司级共享会话(v1)
---
## 1. 目标与边界
### 1.1 目标
- 多租户、多用户:隔离键 `company_id + user_id`
- 每用户独立长期记忆;多会话;聊天记录持久化(Mongo)
- Agent 通过 MCP 调 Java 后端能力(查数/办事),不直连 MySQL/业务 Mongo
- 前端提供**独立聊天页面**(登录后使用,复用现有鉴权与菜单体系)
- **租户自管模型凭证**:各公司配置 OpenAI Compatible `base_url` + `api_key` + `model`;Agent 调用时自动注入;Redis 缓存
### 1.2 边界
| 层 | 职责 | 不做什么 |
|----|------|----------|
| `apps/web` 聊天页 | UI、会话列表、流式展示;公司 LLM 配置表单(调 Server) | 不编排 LLM、不调 MCP、不持有明文长期 Key(仅提交时传一次) |
| `apps/agent` | 会话/记忆/编排/流式 API、调 MCP、注入租户 LLM 凭证 | 不持久业务单据、不实现业务规则、**不存模型 Key** |
| `apps/server` | MySQL 存公司模型配置;MCP `@McpTool`;内部 llm-runtime | 不存聊天记录(对话在 Agent Mongo) |
### 1.3 数据流
```text
[ web-antd 聊天页 ]
│ JWT
├─► Server GET/PUT /api/company/agent-llm-settings (MySQL 加密 Key)
└─► Agent /api/agent/sessions|chat|memories (Mongo 会话/记忆)
│
├─ Redis agent:llm:rt:{companyId} 或 Server /api/internal/agent/llm-runtime
├─ ChatOpenAI(base_url, api_key, model) 按租户注入
└─ MCP /mcp + X-Agent-Company-Id / X-Agent-User-Id → BI tools
```
---
## 2. 已拍板结论
| # | 议题 | 结论 |
|---|------|------|
| **A** | 会话归属 | 严格私有 `(company_id, user_id)` |
| **B** | 记忆范围 | 仅用户级 |
| **C** | 聊天页 | 挂在 `web-antd` 独立路由 |
| **D** | AI Chat UI 库 | 不引入;Ant Design Vue 自建 |
| **E** | Agent 形态 | `apps/agent` 独立 FastAPI 进程 |
| **F** | MCP 租户 | 按请求注入 company |
| **G** | 模型接入 | **OpenAI Compatible API**;租户自管 Key;Redis 缓存;Agent 自动注入 |
### 2.1 关于 D(聊天 UI)——摘要
不引入专门 AI Chat UI 库;用 Ant Design Vue 自建会话列表 + 气泡 + 输入 + SSE。
### 2.2 关于 G(OpenAI Compatible + 租户 Key)——结论
**认同,作为 v1 标准。**
理由:
- 一套 `base_url + api_key + model` 即可兼容 OpenAI / DeepSeek / 月之暗面 / SiliconFlow / 自建 vLLM 等,避免按厂商分支客户端。
- LangChain `ChatOpenAI`(或等价 OpenAI SDK)天然支持 `base_url`,与 LangGraph 无缝。
- Key 归租户:成本与限额由公司自负;平台不垫付模型费。
约束:
1. **真相源**:MySQL `agent_company_llm_settings`(见 `apps/server/sql/design/agent/`);`api_key` **AES-GCM 加密**(`ecom.agent.llm.secret` 或派生自 `jwt.secret`)。
2. **缓存**:Redis `agent:llm:rt:{company_id}` → `{base_url, api_key, model, …}`,TTL;配置变更时 DEL;**Agent 与 Server 须同 Redis DB**。
3. **注入**:Agent 只读 Redis / 内部接口明文;**禁止**下发完整 Key 给前端(读接口只返回 `apiKeyMasked`)。
4. **权限**:更新需公司 owner(或超管);权限码 `agent:llm-settings`。
5. **缺省**:未配置时聊天返回明确错误;`LLM_FALLBACK_*` 仅本地开发。
---
## 3. 总体架构
```text
apps/agent/
app/ # 接口层:HTTP / DTO / 鉴权依赖
application/ # 应用层:用例编排(发消息、列会话、恢复上下文)
domain/ # 领域层:Session / Message / Memory 模型与规则(无框架)
infrastructure/ # 基础设施:Mongo、LLM、MCP client、JWT 校验
graphs/ # LangGraph 图定义(可视为 application 的特殊编排)
config/ # 配置
```
依赖方向:**app → application → domain ← infrastructure**;`graphs` 只依赖 application/domain 端口,MCP/LLM 走 infrastructure 适配器。
### 3.1 分层职责
| 层 | 包 | 职责 | 禁止 |
|----|-----|------|------|
| 接口 | `app` | 路由、请求/响应模型、依赖注入、鉴权提取 | 拼 prompt、直连 Mongo、调 MCP SDK |
| 应用 | `application` | 「用户发一条消息」「新建会话」「加载记忆」用例、事务边界(逻辑) | 框架注解泄漏到 domain |
| 领域 | `domain` | 会话状态机、记忆条目规则、隔离键不变量 | HTTP、Motor、LangChain 类型 |
| 基础设施 | `infrastructure` | Mongo 仓库、MCP、ChatModel、JWT JWKS/本地校验 | 业务用例 if/else 堆砌 |
| 图 | `graphs` | LangGraph StateGraph、节点、边 | 写 Mongo 细节(经 repository 端口) |
---
## 4. 会话 / 聊天 / 记忆(Mongo)
### 4.1 库
- 独立库名建议:`ecom_dmb_agent`(与业务 Mongo 同实例不同库)
- 所有查询强制带 `company_id` + `user_id`
### 4.2 集合
#### `agent_sessions`
| 字段 | 说明 |
|------|------|
| `thread_id` | 会话 ID(UUID),作业务主键 |
| `company_id`, `user_id` | 隔离键 |
| `title` | 可空,首轮后可自动生成 |
| `status` | `active` / `archived` / `deleted` |
| `summary` | 会话滚动摘要(可选) |
| `created_at`, `updated_at`, `last_message_at` | |
唯一索引:`(company_id, user_id, thread_id)`
列表索引:`(company_id, user_id, status, updated_at desc)`
#### `agent_messages`
| 字段 | 说明 |
|------|------|
| `company_id`, `user_id`, `thread_id` | |
| `seq` | 会话内单调序号 |
| `role` | `user` / `assistant` / `system` / `tool` |
| `content` | 文本或结构化块 |
| `tool_name` / `tool_call_id` | tool 轨迹(可选) |
| `created_at` | |
索引:`(company_id, user_id, thread_id, seq)`
**产品真相源 = 本表**;打开会话只加载最近 N 条(或按 token 窗口),更早依赖 `sessions.summary`。
#### `agent_user_memory`
| 字段 | 说明 |
|------|------|
| `company_id`, `user_id` | |
| `kind` | `preference` / `fact` / `entity` / `summary` |
| `key` | 可选,同 key 覆盖更新 |
| `text` / `value` | |
| `source_thread_id` | 溯源 |
| `status` | `active` / `stale` / `deleted` |
| `confidence` | 0~1 |
| `created_at`, `updated_at`, `expires_at?` | |
索引:`(company_id, user_id, status, kind, updated_at)`;可选唯一 `(company_id, user_id, key)` where key 非空。
v1:**不做向量检索**;进图前取 Top-K active 记忆注入 system。显式「记住:…」可写入;自动抽取为 P2。
### 4.2.1 公司模型配置(MySQL,不在 Mongo)
见 `apps/server/sql/design/agent/agent_company_llm_settings_design.sql` 与迁移 `V20260919c__agent_company_llm_settings.sql`。
| 字段 | 说明 |
|------|------|
| `company_id` | 唯一 |
| `base_url` / `model` | OpenAI Compatible |
| `api_key_encrypted` / `api_key_suffix` | 密文 + 掩码后缀 |
| `extra_headers_json` | 可选 |
浏览器:`/api/company/agent-llm-settings`;Agent 内部:`/api/internal/agent/llm-runtime`。
### 4.3 与 LangGraph 的关系
| 概念 | 落点 |
|------|------|
| `thread_id` | 与 LangGraph `configurable.thread_id` 对齐 |
| 聊天记录 | Mongo `agent_messages`(产品真相) |
| Checkpointer | 另集合 `agent_graph_checkpoints`(仅运行时恢复,可同库) |
| 长期记忆 | `agent_user_memory`(跨 thread) |
写入时序(发消息用例):
1. 鉴权得到 `company_id`, `user_id`
2. 校验 `thread_id` 归属
3. 追加 user message → Mongo
4. 加载最近消息 + 用户记忆 → 构图输入
5. 流式执行 Graph → 边生成边推 SSE
6. 落库 assistant/tool messages
7. 异步:更新 session.summary;可选抽取记忆条目
---
## 5. Agent HTTP API(给前端)
前缀建议:`/api/agent`(Agent 服务自身端口,如 `8200`;网关可反代)。
| 方法 | 路径 | 说明 |
|------|------|------|
| GET | `/sessions` | 当前用户会话列表 |
| POST | `/sessions` | 新建会话 |
| PATCH | `/sessions/{thread_id}` | 改标题/归档 |
| GET | `/sessions/{thread_id}/messages` | 历史消息(分页/游标) |
| POST | `/sessions/{thread_id}/chat` | **流式**发消息(SSE) |
| GET | `/memories` | 查看自己的记忆条目(可透明) |
| DELETE | `/memories/{id}` | 用户删除某条记忆 |
公司 LLM 配置在 **Server**:`GET/PUT /api/company/agent-llm-settings`(不经 Agent)。
鉴权:`Authorization: Bearer <用户 JWT>`;Agent 用与 server 共享的 `JWT_SECRET` 校验 HS512。JWT:`sub` = userId,claim `companyId` 等与 Java `JwtUtils` 一致。
---
## 6. MCP 与多租户(server)
1. Agent 持有服务级 Bearer(`AGENT_MCP_TOKEN` / `ecom.agent.mcp.bearer-token`)
2. 每次请求头:`X-Agent-Company-Id`、`X-Agent-User-Id`(`AgentMcpAuthenticationFilter`)
3. `CurrentUserContext` 从 `AgentMcpAuthentication` 取租户;静态 `company-id` 仅本地 fallback
4. 内部路径 `/api/internal/agent/**` 同样走 Agent Bearer,JWT 过滤器跳过
权限:v1 MCP 按公司维度只读 BI;办事类 tool 二期再收紧到真实用户权限。
---
## 7. 前端(web-antd)
### 7.1 页面
- 路由示例:`/agent/chat`
- 菜单:一级「智能助手」
- 另:公司配置入口「模型 API」(或聊天页设置抽屉)维护 OpenAI Compatible 凭证
- 布局:**左会话列表 + 右消息区 + 底输入**;全页 `flex` + `min-h-0` 滚动(遵守现有 Spin/滚动规范)
### 7.2 组件(自建,不引入 AI UI 库)
```text
views/agent/chat/
index.vue # 页壳
components/
SessionSidebar.vue
MessageList.vue
MessageBubble.vue
ChatComposer.vue
ToolCallBlock.vue # 可选:折叠展示 tool 结果
composables/
useAgentChat.ts # 流式消费、本地消息缓冲
api/agent/ # 调 Agent 服务,非调 Java /api
```
### 7.3 配置
- `VITE_AGENT_API_URL`(dev 可代理到 `localhost:8200`)
- 请求头带现有 accessToken
---
## 8. `apps/agent` 工程结构(落地骨架)
```text
apps/agent/
pyproject.toml / requirements.txt
README.md
DESIGN.md # 本文
app/
main.py
deps.py # 当前用户
routers/sessions.py
routers/chat.py
routers/memories.py
application/
session_service.py
chat_service.py
memory_service.py
llm_settings_service.py # 现为 LlmRuntimeService:读 Redis/Server
domain/
models.py
ports.py
infrastructure/
mongo/
redis_cache.py
mcp_client.py
server_llm_gateway.py
jwt_auth.py
llm_factory.py
graphs/
assistant_graph.py
config/settings.py
```
技术选型(v1):
- FastAPI + uvicorn
- LangGraph + langchain-openai(OpenAI Compatible)+ langchain-mcp-adapters
- motor / pymongo、redis、httpx
- PyJWT、pydantic-settings
---
## 9. 分期落地
### P0(可演示)— 已完成
1. `apps/agent` 分层骨架 + 配置
2. Mongo 会话/消息;公司 LLM → **MySQL(Server)** + Redis 运行时
3. OpenAI Compatible 注入 + 流式 SSE
4. web-antd 独立聊天页 + LLM 配置入口
5. JWT 验签打通
### P1(接上现网能力)— 已完成
1. MCP client + server 按请求租户头
2. 挂上现有 BI tools(`langchain-mcp-adapters`)
3. 用户记忆读写与注入(显式「记住」)
4. (摘要压缩长上下文 → 仍 P2)
### P2
1. 记忆抽取异步任务
2. Checkpointer 持久化与失败恢复
3. 工具调用 UI 细化、引用卡片
4. 公司级记忆 / 共享会话(若产品需要)
5. 会话摘要压缩长上下文
---
## 10. 风险与约束
- Agent 与 Java 两套部署:CORS、网关、环境变量(`JWT_SECRET`、`AGENT_MCP_TOKEN`、`AGENT_LLM_SECRET`/`ecom.agent.llm.secret`、Mongo/Redis URI)要对齐;**Redis 须与 Server 同库**才能共享 LLM 缓存
- 切勿让浏览器直连 `/mcp`;切勿把完整 `api_key` 返回前端
- 租户 Key 泄露面:Redis 与进程内存;生产 Redis 需 ACL/独立 DB;日志禁止打印 Key
- 聊天含业务数据:Mongo 权限与备份纳入运维;删除会话应级联软删消息
- License:若需对「智能助手」门禁,二期加 `LicenseFeature`,v1 可用菜单权限控制
---
## 11. 文档维护
落地后同步:根目录 `AGENTS.md` 增加 `apps/agent`;`apps/server/docs/Agent与MCP接入及Boot升级说明.md` 勾选 LangGraph 项并注明多租户 MCP 与租户 LLM Key 约定。
+34
View File
@@ -0,0 +1,34 @@
# Ecom DMB Agent(Python / FastAPI / LangGraph)
设计见 [DESIGN.md](./DESIGN.md)。
## 本地运行
```bash
cd apps/agent
python -m venv .venv
source .venv/bin/activate
pip install -r requirements.txt
cp .env.example .env # JWT_SECRET / Mongo / Redis(与 Server 同库) / SERVER_BASE_URL / MCP
uvicorn app.main:app --reload --host 0.0.0.0 --port 8200
```
健康检查:`GET http://localhost:8200/health`
API 前缀:`/api/agent/...`(会话/聊天/记忆;与前端代理 `/api/agent` 对齐)
**模型 API 配置不在本服务**:浏览器走 Java `GET/PUT /api/company/agent-llm-settings`(MySQL 加密落库);Agent 经 Redis `agent:llm:rt:{companyId}` 或内部接口拉明文注入。
## 环境变量要点
| 变量 | 说明 |
|------|------|
| `JWT_SECRET` | 与 Java `jwt.secret` 一致 |
| `MONGO_URI` / `MONGO_DB` | Agent 独立库(sessions / messages / memory) |
| `REDIS_URL` | **与 Server 同 DB**,读 LLM 运行时缓存 |
| `SERVER_BASE_URL` | Java 根地址,内部拉 `/api/internal/agent/llm-runtime` |
| `MCP_BASE_URL` / `MCP_BEARER_TOKEN` | 调 Server `/mcp`,并带 `X-Agent-Company-Id` / `X-Agent-User-Id` |
| `LLM_FALLBACK_*` | 仅本地:公司未配置时的 OpenAI Compatible fallback |
## 分层
`app` → `application` → `domain` ← `infrastructure`
View File
+69
View File
@@ -0,0 +1,69 @@
"""FastAPI 依赖组装。"""
from __future__ import annotations
from fastapi import Depends, Header, HTTPException, status
from application.chat_service import ChatService
from application.llm_settings_service import LlmRuntimeService
from application.memory_service import MemoryService
from application.session_service import SessionService
from config.settings import Settings, get_settings
from domain.models import Actor
from infrastructure.jwt_auth import parse_actor
from infrastructure.llm_factory import OpenAICompatibleStreamer
from infrastructure.mongo.client import get_db
from infrastructure.mongo.repositories import (
MongoMemoryRepository,
MongoMessageRepository,
MongoSessionRepository,
)
from infrastructure.redis_cache import RedisLlmRuntimeCache, get_redis
from infrastructure.server_llm_gateway import ServerLlmRuntimeGateway
async def current_actor(
authorization: str | None = Header(default=None),
settings: Settings = Depends(get_settings),
) -> Actor:
if not authorization or not authorization.lower().startswith("bearer "):
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="缺少 Bearer Token")
token = authorization.split(" ", 1)[1].strip()
if not token:
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="缺少 Bearer Token")
return parse_actor(settings, token)
async def session_service(settings: Settings = Depends(get_settings)) -> SessionService:
db = await get_db(settings)
return SessionService(MongoSessionRepository(db))
async def memory_service(settings: Settings = Depends(get_settings)) -> MemoryService:
db = await get_db(settings)
return MemoryService(settings, MongoMemoryRepository(db))
async def llm_runtime_service(
settings: Settings = Depends(get_settings),
) -> LlmRuntimeService:
cache = RedisLlmRuntimeCache(get_redis(settings))
return LlmRuntimeService(settings, cache, ServerLlmRuntimeGateway(settings))
async def chat_service(
settings: Settings = Depends(get_settings),
sessions: SessionService = Depends(session_service),
llm_svc: LlmRuntimeService = Depends(llm_runtime_service),
mem_svc: MemoryService = Depends(memory_service),
) -> ChatService:
db = await get_db(settings)
return ChatService(
settings=settings,
sessions=sessions,
session_repo=MongoSessionRepository(db),
messages=MongoMessageRepository(db),
llm_runtime=llm_svc,
memory=mem_svc,
streamer=OpenAICompatibleStreamer(),
)
+57
View File
@@ -0,0 +1,57 @@
"""Agent FastAPI 入口。"""
from __future__ import annotations
from contextlib import asynccontextmanager
from fastapi import FastAPI, HTTPException, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
from app.response import fail
from app.routers import chat, memories, sessions
from config.settings import get_settings
from infrastructure.mongo.client import close_mongo, ensure_indexes, get_db
from infrastructure.redis_cache import close_redis
@asynccontextmanager
async def lifespan(_app: FastAPI):
settings = get_settings()
db = await get_db(settings)
await ensure_indexes(db)
yield
await close_mongo()
await close_redis()
def create_app() -> FastAPI:
settings = get_settings()
app = FastAPI(title=settings.app_name, lifespan=lifespan)
app.add_middleware(
CORSMiddleware,
allow_origins=settings.cors_origin_list,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
app.include_router(sessions.router, prefix="/api/agent")
app.include_router(chat.router, prefix="/api/agent")
app.include_router(memories.router, prefix="/api/agent")
@app.exception_handler(HTTPException)
async def http_exception_handler(_request: Request, exc: HTTPException):
detail = exc.detail if isinstance(exc.detail, str) else str(exc.detail)
return JSONResponse(
status_code=exc.status_code,
content=fail(detail, code=exc.status_code),
)
@app.get("/health")
async def health():
return {"ok": True, "service": settings.app_name}
return app
app = create_app()
+13
View File
@@ -0,0 +1,13 @@
"""与 Java ApiResponse 对齐的统一响应。"""
from __future__ import annotations
from typing import Any
def ok(data: Any = None, message: str = "操作成功") -> dict[str, Any]:
return {"code": 0, "message": message, "data": data}
def fail(message: str, code: int = 1) -> dict[str, Any]:
return {"code": code, "message": message, "data": None}
View File
+81
View File
@@ -0,0 +1,81 @@
"""对话与历史消息。"""
from __future__ import annotations
import json
from fastapi import APIRouter, Depends, HTTPException
from pydantic import BaseModel, Field
from sse_starlette.sse import EventSourceResponse
from app.deps import chat_service, current_actor
from app.response import ok
from application.chat_service import ChatService
from domain.models import Actor
router = APIRouter(prefix="/sessions", tags=["chat"])
class ChatBody(BaseModel):
content: str = Field(min_length=1, max_length=20000)
@router.get("/{thread_id}/messages")
async def list_messages(
thread_id: str,
actor: Actor = Depends(current_actor),
svc: ChatService = Depends(chat_service),
):
try:
rows = await svc.list_messages(actor, thread_id)
except LookupError as e:
raise HTTPException(status_code=404, detail=str(e)) from e
return ok(
{
"items": [
{
"id": m.id,
"seq": m.seq,
"role": m.role.value,
"content": m.content,
"createdAt": m.created_at.isoformat() + "Z",
}
for m in rows
]
}
)
@router.post("/{thread_id}/chat")
async def chat_stream(
thread_id: str,
body: ChatBody,
actor: Actor = Depends(current_actor),
svc: ChatService = Depends(chat_service),
):
"""SSE 流式,不走 ApiResponse 包装。"""
async def gen():
try:
async for chunk in svc.stream_chat(actor, thread_id, body.content):
yield {"event": "token", "data": json.dumps({"text": chunk}, ensure_ascii=False)}
yield {"event": "done", "data": "{}"}
except LookupError as e:
yield {"event": "error", "data": json.dumps({"message": str(e)}, ensure_ascii=False)}
except ValueError as e:
yield {"event": "error", "data": json.dumps({"message": str(e)}, ensure_ascii=False)}
except Exception as e:
yield {
"event": "error",
"data": json.dumps({"message": str(e)}, ensure_ascii=False),
}
return EventSourceResponse(
gen(),
headers={
"Cache-Control": "no-cache, no-transform",
"X-Accel-Buffering": "no",
"Connection": "keep-alive",
},
ping=15,
)
+33
View File
@@ -0,0 +1,33 @@
"""用户记忆 API。"""
from __future__ import annotations
from fastapi import APIRouter, Depends, HTTPException, status
from app.deps import current_actor, memory_service
from app.response import ok
from application.memory_service import MemoryService
from domain.models import Actor
router = APIRouter(prefix="/memories", tags=["memories"])
@router.get("")
async def list_memories(
actor: Actor = Depends(current_actor),
svc: MemoryService = Depends(memory_service),
):
items = await svc.list_public(actor)
return ok({"items": items})
@router.delete("/{memory_id}")
async def delete_memory(
memory_id: str,
actor: Actor = Depends(current_actor),
svc: MemoryService = Depends(memory_service),
):
deleted = await svc.delete(actor, memory_id)
if not deleted:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="记忆不存在")
return ok({"ok": True})
+78
View File
@@ -0,0 +1,78 @@
"""会话路由。"""
from __future__ import annotations
from fastapi import APIRouter, Depends, HTTPException
from pydantic import BaseModel, Field
from app.deps import current_actor, session_service
from app.response import ok
from application.session_service import SessionService
from domain.models import Actor
router = APIRouter(prefix="/sessions", tags=["sessions"])
class CreateSessionBody(BaseModel):
title: str | None = None
class RenameBody(BaseModel):
title: str = Field(min_length=1, max_length=200)
def _session_vo(s) -> dict:
return {
"threadId": s.thread_id,
"title": s.title,
"status": s.status.value,
"createdAt": s.created_at.isoformat() + "Z",
"updatedAt": s.updated_at.isoformat() + "Z",
"lastMessageAt": s.last_message_at.isoformat() + "Z" if s.last_message_at else None,
}
@router.get("")
async def list_sessions(
actor: Actor = Depends(current_actor),
svc: SessionService = Depends(session_service),
):
rows = await svc.list_mine(actor)
return ok({"items": [_session_vo(s) for s in rows]})
@router.post("")
async def create_session(
body: CreateSessionBody,
actor: Actor = Depends(current_actor),
svc: SessionService = Depends(session_service),
):
s = await svc.create(actor, body.title)
return ok(_session_vo(s))
@router.patch("/{thread_id}")
async def rename_session(
thread_id: str,
body: RenameBody,
actor: Actor = Depends(current_actor),
svc: SessionService = Depends(session_service),
):
try:
s = await svc.rename(actor, thread_id, body.title)
except LookupError as e:
raise HTTPException(status_code=404, detail=str(e)) from e
return ok(_session_vo(s))
@router.post("/{thread_id}/archive")
async def archive_session(
thread_id: str,
actor: Actor = Depends(current_actor),
svc: SessionService = Depends(session_service),
):
try:
s = await svc.archive(actor, thread_id)
except LookupError as e:
raise HTTPException(status_code=404, detail=str(e)) from e
return ok(_session_vo(s))
View File
+109
View File
@@ -0,0 +1,109 @@
"""对话用例:落库 + 记忆注入 + MCP tools + 流式生成。"""
from __future__ import annotations
from datetime import datetime
from typing import AsyncIterator
from application.llm_settings_service import LlmRuntimeService
from application.memory_service import MemoryService
from application.session_service import SessionService
from config.settings import Settings
from domain.models import Actor, ChatMessage, MessageRole
from domain.ports import ChatStreamer, MessageRepository, SessionRepository
from infrastructure.mcp_client import load_mcp_tools
class ChatService:
def __init__(
self,
settings: Settings,
sessions: SessionService,
session_repo: SessionRepository,
messages: MessageRepository,
llm_runtime: LlmRuntimeService,
memory: MemoryService,
streamer: ChatStreamer,
) -> None:
self._settings = settings
self._sessions = sessions
self._session_repo = session_repo
self._messages = messages
self._llm_runtime = llm_runtime
self._memory = memory
self._streamer = streamer
async def list_messages(self, actor: Actor, thread_id: str) -> list[ChatMessage]:
await self._sessions.require_owned(actor, thread_id)
return await self._messages.list_recent(
actor.company_id,
actor.user_id,
thread_id,
self._settings.chat_history_limit,
)
async def stream_chat(
self, actor: Actor, thread_id: str, content: str
) -> AsyncIterator[str]:
text = (content or "").strip()
if not text:
raise ValueError("消息不能为空")
session = await self._sessions.require_owned(actor, thread_id)
llm = await self._llm_runtime.resolve_runtime(actor.company_id)
await self._memory.maybe_capture_from_user(
actor, thread_id=thread_id, text=text
)
memory_lines = await self._memory.lines_for_prompt(actor)
tools = await load_mcp_tools(
self._settings, company_id=actor.company_id, user_id=actor.user_id
)
history = await self._messages.list_recent(
actor.company_id,
actor.user_id,
thread_id,
self._settings.chat_history_limit,
)
seq = await self._messages.next_seq(actor.company_id, actor.user_id, thread_id)
user_msg = ChatMessage(
company_id=actor.company_id,
user_id=actor.user_id,
thread_id=thread_id,
seq=seq,
role=MessageRole.USER,
content=text,
)
await self._messages.append(user_msg)
if session.title == "新对话":
session.title = text[:40] + ("…" if len(text) > 40 else "")
session.last_message_at = datetime.utcnow()
await self._session_repo.update(session)
parts: list[str] = []
async for chunk in self._streamer.stream_reply(
llm=llm,
history=history,
user_text=text,
memory_lines=memory_lines,
tools=tools or None,
):
parts.append(chunk)
yield chunk
full = "".join(parts).strip() or "(模型未返回内容)"
a_seq = await self._messages.next_seq(actor.company_id, actor.user_id, thread_id)
await self._messages.append(
ChatMessage(
company_id=actor.company_id,
user_id=actor.user_id,
thread_id=thread_id,
seq=a_seq,
role=MessageRole.ASSISTANT,
content=full,
)
)
session.last_message_at = datetime.utcnow()
await self._session_repo.update(session)
@@ -0,0 +1,48 @@
"""租户 LLM 运行时解析:Redis(Server 写入)→ Server 内部 API → 本地 fallback。"""
from __future__ import annotations
from fastapi import HTTPException, status
from config.settings import Settings
from domain.models import LlmRuntimeConfig
from domain.ports import LlmRuntimeCache, LlmRuntimeGateway
class LlmRuntimeService:
def __init__(
self,
settings: Settings,
cache: LlmRuntimeCache,
gateway: LlmRuntimeGateway,
) -> None:
self._settings = settings
self._cache = cache
self._gateway = gateway
async def resolve_runtime(self, company_id: int) -> LlmRuntimeConfig:
cached = await self._cache.get(company_id)
if cached is not None and cached.api_key:
return cached
remote = await self._gateway.fetch(company_id)
if remote is not None and remote.api_key and remote.base_url and remote.model:
await self._cache.set(
company_id, remote, self._settings.llm_cache_ttl_seconds
)
return remote
if (
self._settings.llm_fallback_enabled
and self._settings.llm_fallback_api_key
):
return LlmRuntimeConfig(
base_url=self._settings.llm_fallback_base_url.rstrip("/"),
api_key=self._settings.llm_fallback_api_key,
model=self._settings.llm_fallback_model,
)
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="当前公司尚未配置模型 API,请先在智能助手设置中填写 OpenAI Compatible 凭证",
)
+66
View File
@@ -0,0 +1,66 @@
"""用户记忆用例。"""
from __future__ import annotations
import hashlib
import re
from domain.models import Actor, MemoryKind, UserMemory
from domain.ports import MemoryRepository
from config.settings import Settings
_REMEMBER_RE = re.compile(
r"^(?:请?记住|记住一下)[::\s]*(.+)$",
re.DOTALL,
)
class MemoryService:
def __init__(self, settings: Settings, repo: MemoryRepository) -> None:
self._settings = settings
self._repo = repo
async def list_public(self, actor: Actor, limit: int = 50) -> list[dict]:
rows = await self._repo.list_active(actor.company_id, actor.user_id, limit)
return [
{
"id": m.id,
"kind": m.kind.value,
"key": m.key,
"text": m.text,
"updatedAt": m.updated_at.isoformat() + "Z",
}
for m in rows
]
async def delete(self, actor: Actor, memory_id: str) -> bool:
return await self._repo.soft_delete(actor.company_id, actor.user_id, memory_id)
async def lines_for_prompt(self, actor: Actor) -> list[str]:
rows = await self._repo.list_active(
actor.company_id, actor.user_id, self._settings.memory_inject_limit
)
return [m.text.strip() for m in rows if m.text and m.text.strip()]
async def maybe_capture_from_user(
self, actor: Actor, *, thread_id: str, text: str
) -> None:
"""显式「记住…」指令写入记忆;自动抽取留给 P2。"""
m = _REMEMBER_RE.match((text or "").strip())
if not m:
return
body = m.group(1).strip()
if not body:
return
key = "remember:" + hashlib.sha1(body.encode("utf-8")).hexdigest()[:16]
await self._repo.upsert(
UserMemory(
company_id=actor.company_id,
user_id=actor.user_id,
kind=MemoryKind.PREFERENCE,
key=key,
text=body[:1000],
source_thread_id=thread_id,
)
)
+46
View File
@@ -0,0 +1,46 @@
"""会话用例。"""
from __future__ import annotations
import uuid
from datetime import datetime
from domain.models import Actor, Session, SessionStatus
from domain.ports import SessionRepository
class SessionService:
def __init__(self, sessions: SessionRepository) -> None:
self._sessions = sessions
async def create(self, actor: Actor, title: str | None = None) -> Session:
now = datetime.utcnow()
session = Session(
thread_id=str(uuid.uuid4()),
company_id=actor.company_id,
user_id=actor.user_id,
title=(title or "新对话").strip() or "新对话",
status=SessionStatus.ACTIVE,
created_at=now,
updated_at=now,
)
return await self._sessions.create(session)
async def list_mine(self, actor: Actor) -> list[Session]:
return await self._sessions.list_active(actor.company_id, actor.user_id)
async def require_owned(self, actor: Actor, thread_id: str) -> Session:
session = await self._sessions.get(actor.company_id, actor.user_id, thread_id)
if session is None or session.status == SessionStatus.DELETED:
raise LookupError("会话不存在")
return session
async def rename(self, actor: Actor, thread_id: str, title: str) -> Session:
session = await self.require_owned(actor, thread_id)
session.title = title.strip() or session.title
return await self._sessions.update(session)
async def archive(self, actor: Actor, thread_id: str) -> Session:
session = await self.require_owned(actor, thread_id)
session.status = SessionStatus.ARCHIVED
return await self._sessions.update(session)
View File
+50
View File
@@ -0,0 +1,50 @@
"""应用配置(环境变量)。"""
from functools import lru_cache
from pydantic_settings import BaseSettings, SettingsConfigDict
class Settings(BaseSettings):
model_config = SettingsConfigDict(env_file=".env", env_file_encoding="utf-8", extra="ignore")
app_name: str = "ecom-dmb-agent"
host: str = "0.0.0.0"
port: int = 8200
cors_origins: str = "http://localhost:5173,http://localhost:5666"
# 与 Java server jwt.secret 一致(HS512)
jwt_secret: str = "your-secret-key-here-must-be-at-least-64-bytes-long-for-hs512-algorithm-security"
jwt_algorithms: str = "HS512"
mongo_uri: str = "mongodb://ecom_dmb_agent_dev:ecom_dmb_agent_dev@192.168.3.100:27017/?authSource=ecom_dmb_agent_dev"
mongo_db: str = "ecom_dmb_agent_dev"
# 须与 Server Redis 同库,才能命中 agent:llm:rt:{companyId}
redis_url: str = "redis://:redis_qinghua@192.168.3.100:6379/2"
llm_cache_ttl_seconds: int = 600
# Java Server 根地址(内部拉 LLM 运行时)
server_base_url: str = "http://localhost:8080"
# 仅本地开发:公司未配置时的 fallback(生产勿用)
llm_fallback_enabled: bool = True
llm_fallback_base_url: str = "https://api.openai.com/v1"
llm_fallback_api_key: str = ""
llm_fallback_model: str = "gpt-4o-mini"
mcp_base_url: str = "http://localhost:8080/mcp"
mcp_bearer_token: str = "dev-agent-mcp-token"
mcp_tools_enabled: bool = True
chat_history_limit: int = 40
memory_inject_limit: int = 12
@property
def cors_origin_list(self) -> list[str]:
return [o.strip() for o in self.cors_origins.split(",") if o.strip()]
@lru_cache
def get_settings() -> Settings:
return Settings()
View File
+105
View File
@@ -0,0 +1,105 @@
"""领域模型(无框架依赖)。"""
from __future__ import annotations
from dataclasses import dataclass, field
from datetime import datetime
from enum import Enum
from typing import Any
class SessionStatus(str, Enum):
ACTIVE = "active"
ARCHIVED = "archived"
DELETED = "deleted"
class MessageRole(str, Enum):
USER = "user"
ASSISTANT = "assistant"
SYSTEM = "system"
TOOL = "tool"
class MemoryKind(str, Enum):
PREFERENCE = "preference"
FACT = "fact"
ENTITY = "entity"
SUMMARY = "summary"
class MemoryStatus(str, Enum):
ACTIVE = "active"
STALE = "stale"
DELETED = "deleted"
@dataclass(frozen=True)
class Actor:
"""当前请求主体。"""
user_id: str
company_id: int
company_role: str | None = None
is_super: bool = False
def can_manage_llm(self) -> bool:
if self.is_super:
return True
role = (self.company_role or "").lower()
return role in {"owner", "admin"}
@dataclass
class Session:
thread_id: str
company_id: int
user_id: str
title: str = "新对话"
status: SessionStatus = SessionStatus.ACTIVE
summary: str | None = None
created_at: datetime = field(default_factory=datetime.utcnow)
updated_at: datetime = field(default_factory=datetime.utcnow)
last_message_at: datetime | None = None
@dataclass
class ChatMessage:
company_id: int
user_id: str
thread_id: str
seq: int
role: MessageRole
content: str
tool_name: str | None = None
tool_call_id: str | None = None
created_at: datetime = field(default_factory=datetime.utcnow)
id: str | None = None
@dataclass
class UserMemory:
"""用户级长期记忆条目。"""
company_id: int
user_id: str
kind: MemoryKind
text: str
key: str | None = None
value: dict[str, Any] = field(default_factory=dict)
source_thread_id: str | None = None
status: MemoryStatus = MemoryStatus.ACTIVE
confidence: float = 0.8
created_at: datetime = field(default_factory=datetime.utcnow)
updated_at: datetime = field(default_factory=datetime.utcnow)
id: str | None = None
@dataclass(frozen=True)
class LlmRuntimeConfig:
"""注入 LLM 客户端的运行时配置(含明文 key,仅进程内)。"""
base_url: str
api_key: str
model: str
extra_headers: dict[str, str] = field(default_factory=dict)
+81
View File
@@ -0,0 +1,81 @@
"""领域端口(依赖倒置)。"""
from __future__ import annotations
from abc import ABC, abstractmethod
from typing import Any, AsyncIterator
from domain.models import ChatMessage, LlmRuntimeConfig, Session, UserMemory
class SessionRepository(ABC):
@abstractmethod
async def create(self, session: Session) -> Session: ...
@abstractmethod
async def get(self, company_id: int, user_id: str, thread_id: str) -> Session | None: ...
@abstractmethod
async def list_active(self, company_id: int, user_id: str, limit: int = 50) -> list[Session]: ...
@abstractmethod
async def update(self, session: Session) -> Session: ...
class MessageRepository(ABC):
@abstractmethod
async def append(self, message: ChatMessage) -> ChatMessage: ...
@abstractmethod
async def list_recent(
self, company_id: int, user_id: str, thread_id: str, limit: int
) -> list[ChatMessage]: ...
@abstractmethod
async def next_seq(self, company_id: int, user_id: str, thread_id: str) -> int: ...
class MemoryRepository(ABC):
@abstractmethod
async def list_active(
self, company_id: int, user_id: str, limit: int
) -> list[UserMemory]: ...
@abstractmethod
async def upsert(self, memory: UserMemory) -> UserMemory: ...
@abstractmethod
async def soft_delete(self, company_id: int, user_id: str, memory_id: str) -> bool: ...
class LlmRuntimeCache(ABC):
@abstractmethod
async def get(self, company_id: int) -> LlmRuntimeConfig | None: ...
@abstractmethod
async def set(self, company_id: int, config: LlmRuntimeConfig, ttl_seconds: int) -> None: ...
@abstractmethod
async def delete(self, company_id: int) -> None: ...
class LlmRuntimeGateway(ABC):
"""从 Server 拉取运行时模型配置(MySQL 真相源)。"""
@abstractmethod
async def fetch(self, company_id: int) -> LlmRuntimeConfig | None: ...
class ChatStreamer(ABC):
"""流式生成助手回复。"""
@abstractmethod
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]: ...
View File
+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
+14
View File
@@ -0,0 +1,14 @@
# Agent 服务依赖(Python 3.11+)
fastapi>=0.115.0
uvicorn[standard]>=0.32.0
pydantic>=2.9.0
pydantic-settings>=2.6.0
PyJWT>=2.9.0
motor>=3.6.0
redis>=5.2.0
httpx>=0.27.0
langchain-core>=0.3.0
langchain-openai>=0.2.0
langchain-mcp-adapters>=0.1.0
langgraph>=0.2.0
sse-starlette>=2.1.0