mirror of
https://gitee.com/qqtt-ah/ecom-dmb.git
synced 2026-11-25 16:29:20 +08:00
feat: 新增agent
This commit is contained in:
@@ -8,6 +8,7 @@
|
|||||||
apps/
|
apps/
|
||||||
web/ # 前端(原 ecom-dmb-frontend,pnpm+turbo,应用 apps/web-antd)
|
web/ # 前端(原 ecom-dmb-frontend,pnpm+turbo,应用 apps/web-antd)
|
||||||
server/ # 主后端(原 ecom-dmb-backend,Spring Boot)
|
server/ # 主后端(原 ecom-dmb-backend,Spring Boot)
|
||||||
|
agent/ # 智能助手(FastAPI/LangGraph;会话 Mongo;模型 Key 落 Server MySQL)
|
||||||
license-server/ # 授权(原 ecom-license:server/ + tui/)
|
license-server/ # 授权(原 ecom-license:server/ + tui/)
|
||||||
browser-extension/ # 浏览器扩展
|
browser-extension/ # 浏览器扩展
|
||||||
order-generator/ # 刷单/删单测试工具
|
order-generator/ # 刷单/删单测试工具
|
||||||
@@ -32,6 +33,15 @@ deploy/ # 部署 TUI(原 ecom-deploy),流程见 deploy/MANU
|
|||||||
- lefthook 钩子会对暂存文件自动 prettier/eslint/stylelint `--fix`,commitlint 强制 conventional commit,不要绕过
|
- lefthook 钩子会对暂存文件自动 prettier/eslint/stylelint `--fix`,commitlint 强制 conventional commit,不要绕过
|
||||||
- 代码内 `#/` 别名 = `src/`
|
- 代码内 `#/` 别名 = `src/`
|
||||||
- **web-antd 视图里不要用 `<Spin :spinning>` 整块包住可滚动列表**(ant-spin-container 破坏滚动链);滚动依赖 `flex-1 min-h-0 overflow-y-auto`,加载态拆细(详见 `.cursor/rules/antd-spin-scrollable-layout.mdc`)
|
- **web-antd 视图里不要用 `<Spin :spinning>` 整块包住可滚动列表**(ant-spin-container 破坏滚动链);滚动依赖 `flex-1 min-h-0 overflow-y-auto`,加载态拆细(详见 `.cursor/rules/antd-spin-scrollable-layout.mdc`)
|
||||||
|
- 智能助手页:`views/agent/chat`;开发代理 `/api/agent` → `localhost:8200`(见 `vite.config.mts`)
|
||||||
|
|
||||||
|
## Agent(apps/agent)
|
||||||
|
|
||||||
|
- Python 3.11+;设计 `apps/agent/DESIGN.md`
|
||||||
|
- `cd apps/agent && python -m venv .venv && source .venv/bin/activate && pip install -r requirements.txt`
|
||||||
|
- 配置 `.env`(参考 `.env.example`):`JWT_SECRET` 须与 Java `jwt.secret` 一致
|
||||||
|
- 运行:`uvicorn app.main:app --reload --port 8200`
|
||||||
|
- 租户自管 OpenAI Compatible 凭证(Mongo 加密 + Redis 缓存);聊天/会话在 Agent Mongo 库
|
||||||
|
|
||||||
## 授权(apps/license-server)
|
## 授权(apps/license-server)
|
||||||
|
|
||||||
|
|||||||
@@ -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
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
.venv/
|
||||||
|
__pycache__/
|
||||||
|
*.py[cod]
|
||||||
|
.env
|
||||||
|
.pytest_cache/
|
||||||
|
.mypy_cache/
|
||||||
|
.ruff_cache/
|
||||||
|
*.egg-info/
|
||||||
|
dist/
|
||||||
|
build/
|
||||||
@@ -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 约定。
|
||||||
@@ -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`
|
||||||
@@ -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(),
|
||||||
|
)
|
||||||
@@ -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()
|
||||||
@@ -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}
|
||||||
@@ -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,
|
||||||
|
)
|
||||||
@@ -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})
|
||||||
@@ -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))
|
||||||
@@ -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 凭证",
|
||||||
|
)
|
||||||
@@ -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,
|
||||||
|
)
|
||||||
|
)
|
||||||
@@ -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)
|
||||||
@@ -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()
|
||||||
@@ -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)
|
||||||
@@ -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]: ...
|
||||||
@@ -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)),
|
||||||
|
)
|
||||||
@@ -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 ""
|
||||||
@@ -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 []
|
||||||
@@ -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")),
|
||||||
|
)
|
||||||
@@ -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
|
||||||
@@ -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
|
||||||
@@ -155,7 +155,7 @@ Boot 4 = Spring Framework 7 + Jakarta EE 11 + **Jackson 3** + Security 7 等,
|
|||||||
3. [x] 引入 Spring AI 1.1.8 BOM + `spring-ai-starter-mcp-server-webmvc`,配置 STREAMABLE `/mcp`
|
3. [x] 引入 Spring AI 1.1.8 BOM + `spring-ai-starter-mcp-server-webmvc`,配置 STREAMABLE `/mcp`
|
||||||
4. [x] Security:`/mcp` 跳过 JWT + Agent Bearer(`ecom.agent.mcp.bearer-token` / `AGENT_MCP_TOKEN`);含探测 tool `mcp_ping`
|
4. [x] Security:`/mcp` 跳过 JWT + Agent Bearer(`ecom.agent.mcp.bearer-token` / `AGENT_MCP_TOKEN`);含探测 tool `mcp_ping`
|
||||||
5. [x] 落地 BI 只读 tool:`bi_workbench_finance` / `bi_shop_overview` / `bi_product_overview`(瘦返回;租户 `ecom.agent.mcp.company-id`)
|
5. [x] 落地 BI 只读 tool:`bi_workbench_finance` / `bi_shop_overview` / `bi_product_overview`(瘦返回;租户 `ecom.agent.mcp.company-id`)
|
||||||
6. [ ] 新建 Python LangGraph 工程,接 MCP HTTP
|
6. [x] Python LangGraph Agent(`apps/agent`):会话/记忆 Mongo;模型 Key 在 **MySQL**;MCP 多租户头 + BI tools
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,27 @@
|
|||||||
|
-- ========================================
|
||||||
|
-- Agent:公司模型 API 配置(OpenAI Compatible)
|
||||||
|
-- 表 agent_company_llm_settings
|
||||||
|
-- 迁移:V20260919c__agent_company_llm_settings.sql
|
||||||
|
-- ========================================
|
||||||
|
-- 约定:
|
||||||
|
-- 1) 按 company_id 一行;api_key 加密存储,接口只回掩码
|
||||||
|
-- 2) Agent 进程经内部接口取运行时明文,Redis 缓存 agent:llm:rt:{companyId}
|
||||||
|
-- 3) 与聊天会话 Mongo 分离:凭证归业务库(MySQL),对话归 Agent Mongo
|
||||||
|
-- ========================================
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS `agent_company_llm_settings` (
|
||||||
|
`id` bigint UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '主键',
|
||||||
|
`company_id` bigint UNSIGNED NOT NULL COMMENT '公司ID',
|
||||||
|
`base_url` varchar(500) NOT NULL COMMENT 'OpenAI Compatible Base URL',
|
||||||
|
`api_key_encrypted` varchar(2000) NOT NULL COMMENT 'API Key 密文',
|
||||||
|
`api_key_suffix` varchar(16) NOT NULL DEFAULT '' COMMENT 'Key 末几位(展示掩码)',
|
||||||
|
`model` varchar(200) NOT NULL COMMENT '默认模型名',
|
||||||
|
`extra_headers_json` json NULL COMMENT '可选额外请求头',
|
||||||
|
`create_by` bigint UNSIGNED NULL COMMENT '创建人用户ID',
|
||||||
|
`update_by` bigint UNSIGNED NULL COMMENT '更新人用户ID',
|
||||||
|
`create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
`update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
|
||||||
|
PRIMARY KEY (`id`),
|
||||||
|
UNIQUE KEY `uk_agent_llm_company` (`company_id`),
|
||||||
|
CONSTRAINT `fk_agent_llm_company` FOREIGN KEY (`company_id`) REFERENCES `org_company` (`id`) ON DELETE CASCADE
|
||||||
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci COMMENT='公司 Agent 模型 API 配置';
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
-- 智能助手菜单(聊天页挂 web-antd /agent/chat)
|
||||||
|
INSERT INTO `sys_menu` (`id`, `parent_id`, `super`, `route_name`, `title`, `path`, `component`, `redirect`, `icon`, `type`, `visible`, `status`, `keep_alive`, `order`)
|
||||||
|
SELECT 14080, NULL, 0, 'AgentAssistant', '智能助手', '/agent/chat', '/agent/chat/index', '', 'lucide:bot', 'menu', 1, 1, 0, 14
|
||||||
|
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_menu` WHERE `id` = 14080 OR `route_name` = 'AgentAssistant');
|
||||||
|
|
||||||
|
INSERT INTO `sys_permission` (`id`, `parent_id`, `code`, `name`, `type`, `status`, `remark`, `sort_order`)
|
||||||
|
SELECT 4800, (SELECT id FROM `sys_permission` WHERE `code` = 'data' LIMIT 1), 'agent', '智能助手', 'module', 1, '', 50
|
||||||
|
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `id` = 4800 OR `code` = 'agent');
|
||||||
|
|
||||||
|
INSERT INTO `sys_permission` (`id`, `parent_id`, `code`, `name`, `type`, `status`, `remark`, `sort_order`)
|
||||||
|
SELECT 4801, (SELECT id FROM `sys_permission` WHERE `code` = 'agent' LIMIT 1), 'agent:chat', '对话', 'api', 1, '', 1
|
||||||
|
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `id` = 4801 OR `code` = 'agent:chat');
|
||||||
|
|
||||||
|
INSERT INTO `sys_permission` (`id`, `parent_id`, `code`, `name`, `type`, `status`, `remark`, `sort_order`)
|
||||||
|
SELECT 4802, (SELECT id FROM `sys_permission` WHERE `code` = 'agent' LIMIT 1), 'agent:llm-settings', '模型配置', 'api', 1, '', 2
|
||||||
|
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `id` = 4802 OR `code` = 'agent:llm-settings');
|
||||||
|
|
||||||
|
INSERT IGNORE INTO `sys_menu_permission` (`menu_id`, `permission_id`)
|
||||||
|
SELECT m.id, p.id
|
||||||
|
FROM `sys_menu` m
|
||||||
|
JOIN `sys_permission` p ON p.code IN ('agent:chat', 'agent:llm-settings')
|
||||||
|
WHERE m.route_name = 'AgentAssistant';
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
-- 公司 Agent 模型 API 配置(OpenAI Compatible)
|
||||||
|
CREATE TABLE IF NOT EXISTS `agent_company_llm_settings` (
|
||||||
|
`id` bigint UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '主键',
|
||||||
|
`company_id` bigint UNSIGNED NOT NULL COMMENT '公司ID',
|
||||||
|
`base_url` varchar(500) NOT NULL COMMENT 'OpenAI Compatible Base URL',
|
||||||
|
`api_key_encrypted` varchar(2000) NOT NULL COMMENT 'API Key 密文',
|
||||||
|
`api_key_suffix` varchar(16) NOT NULL DEFAULT '' COMMENT 'Key 末几位(展示掩码)',
|
||||||
|
`model` varchar(200) NOT NULL COMMENT '默认模型名',
|
||||||
|
`extra_headers_json` json NULL COMMENT '可选额外请求头',
|
||||||
|
`create_by` bigint UNSIGNED NULL COMMENT '创建人用户ID',
|
||||||
|
`update_by` bigint UNSIGNED NULL COMMENT '更新人用户ID',
|
||||||
|
`create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
`update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
|
||||||
|
PRIMARY KEY (`id`),
|
||||||
|
UNIQUE KEY `uk_agent_llm_company` (`company_id`),
|
||||||
|
CONSTRAINT `fk_agent_llm_company` FOREIGN KEY (`company_id`) REFERENCES `org_company` (`id`) ON DELETE CASCADE
|
||||||
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci COMMENT='公司 Agent 模型 API 配置';
|
||||||
+1
@@ -35,6 +35,7 @@ public class JwtAuthenticationFilter extends OncePerRequestFilter {
|
|||||||
return uri.startsWith("/api/open/")
|
return uri.startsWith("/api/open/")
|
||||||
|| uri.equals("/mcp")
|
|| uri.equals("/mcp")
|
||||||
|| uri.startsWith("/mcp/")
|
|| uri.startsWith("/mcp/")
|
||||||
|
|| uri.startsWith("/api/internal/agent/")
|
||||||
|| uri.startsWith("/api/channel/pdd/auth/callback")
|
|| uri.startsWith("/api/channel/pdd/auth/callback")
|
||||||
|| uri.startsWith("/channel/pdd/auth/callback");
|
|| uri.startsWith("/channel/pdd/auth/callback");
|
||||||
}
|
}
|
||||||
|
|||||||
+20
@@ -0,0 +1,20 @@
|
|||||||
|
package top.xyquan.ecomdmbbackend.modules.agent.llm.config;
|
||||||
|
|
||||||
|
import lombok.Data;
|
||||||
|
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 租户模型 API Key 加解密与 Redis 缓存。
|
||||||
|
*/
|
||||||
|
@Data
|
||||||
|
@Component
|
||||||
|
@ConfigurationProperties(prefix = "ecom.agent.llm")
|
||||||
|
public class AgentLlmProperties {
|
||||||
|
|
||||||
|
/** AES 密钥材料;空则回退 jwt.secret */
|
||||||
|
private String secret = "";
|
||||||
|
|
||||||
|
/** Redis 运行时缓存 TTL 秒 */
|
||||||
|
private long runtimeCacheTtlSeconds = 600;
|
||||||
|
}
|
||||||
+37
@@ -0,0 +1,37 @@
|
|||||||
|
package top.xyquan.ecomdmbbackend.modules.agent.llm.controller;
|
||||||
|
|
||||||
|
import jakarta.validation.Valid;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import org.springframework.web.bind.annotation.GetMapping;
|
||||||
|
import org.springframework.web.bind.annotation.PutMapping;
|
||||||
|
import org.springframework.web.bind.annotation.RequestBody;
|
||||||
|
import org.springframework.web.bind.annotation.RequestMapping;
|
||||||
|
import org.springframework.web.bind.annotation.RestController;
|
||||||
|
import top.xyquan.ecomdmbbackend.common.annotation.RequirePermission;
|
||||||
|
import top.xyquan.ecomdmbbackend.common.response.ApiResponse;
|
||||||
|
import top.xyquan.ecomdmbbackend.modules.agent.llm.model.dto.UpsertAgentLlmSettingsDTO;
|
||||||
|
import top.xyquan.ecomdmbbackend.modules.agent.llm.model.vo.AgentLlmSettingsVO;
|
||||||
|
import top.xyquan.ecomdmbbackend.modules.agent.llm.service.AgentCompanyLlmSettingsService;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 公司模型 API 配置(浏览器 JWT)。
|
||||||
|
*/
|
||||||
|
@RestController
|
||||||
|
@RequestMapping("/api/company/agent-llm-settings")
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class AgentCompanyLlmSettingsController {
|
||||||
|
|
||||||
|
private final AgentCompanyLlmSettingsService settingsService;
|
||||||
|
|
||||||
|
@GetMapping
|
||||||
|
@RequirePermission(value = "agent:llm-settings", description = "查看模型配置", allowSuper = true)
|
||||||
|
public ApiResponse<AgentLlmSettingsVO> get() {
|
||||||
|
return ApiResponse.success(settingsService.getForCurrentCompany());
|
||||||
|
}
|
||||||
|
|
||||||
|
@PutMapping
|
||||||
|
@RequirePermission(value = "agent:llm-settings", description = "更新模型配置", allowSuper = true)
|
||||||
|
public ApiResponse<AgentLlmSettingsVO> upsert(@Valid @RequestBody UpsertAgentLlmSettingsDTO dto) {
|
||||||
|
return ApiResponse.success("保存成功", settingsService.upsertForCurrentCompany(dto));
|
||||||
|
}
|
||||||
|
}
|
||||||
+57
@@ -0,0 +1,57 @@
|
|||||||
|
package top.xyquan.ecomdmbbackend.modules.agent.llm.controller;
|
||||||
|
|
||||||
|
import jakarta.servlet.http.HttpServletRequest;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import org.springframework.util.StringUtils;
|
||||||
|
import org.springframework.web.bind.annotation.GetMapping;
|
||||||
|
import org.springframework.web.bind.annotation.RequestMapping;
|
||||||
|
import org.springframework.web.bind.annotation.RequestParam;
|
||||||
|
import org.springframework.web.bind.annotation.RestController;
|
||||||
|
import top.xyquan.ecomdmbbackend.common.exception.BusinessException;
|
||||||
|
import top.xyquan.ecomdmbbackend.common.response.ApiResponse;
|
||||||
|
import top.xyquan.ecomdmbbackend.modules.agent.llm.model.vo.AgentLlmRuntimeVO;
|
||||||
|
import top.xyquan.ecomdmbbackend.modules.agent.llm.service.AgentCompanyLlmSettingsService;
|
||||||
|
import top.xyquan.ecomdmbbackend.modules.agent.mcp.config.AgentMcpProperties;
|
||||||
|
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.security.MessageDigest;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Agent 内部拉取运行时模型配置(服务 Bearer,不下发浏览器)。
|
||||||
|
*/
|
||||||
|
@RestController
|
||||||
|
@RequestMapping("/api/internal/agent")
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class AgentInternalLlmController {
|
||||||
|
|
||||||
|
private final AgentCompanyLlmSettingsService settingsService;
|
||||||
|
private final AgentMcpProperties mcpProperties;
|
||||||
|
|
||||||
|
@GetMapping("/llm-runtime")
|
||||||
|
public ApiResponse<AgentLlmRuntimeVO> runtime(
|
||||||
|
@RequestParam("companyId") Long companyId,
|
||||||
|
HttpServletRequest request) {
|
||||||
|
assertAgentBearer(request);
|
||||||
|
if (companyId == null) {
|
||||||
|
throw new BusinessException("companyId 不能为空");
|
||||||
|
}
|
||||||
|
return ApiResponse.success(settingsService.getRuntime(companyId));
|
||||||
|
}
|
||||||
|
|
||||||
|
private void assertAgentBearer(HttpServletRequest request) {
|
||||||
|
String configured = mcpProperties.getBearerToken();
|
||||||
|
if (!StringUtils.hasText(configured)) {
|
||||||
|
throw new BusinessException("Agent 内部凭证未配置");
|
||||||
|
}
|
||||||
|
String authorization = request.getHeader("Authorization");
|
||||||
|
if (!StringUtils.hasText(authorization) || !authorization.startsWith("Bearer ")) {
|
||||||
|
throw new BusinessException("缺少 Agent Bearer");
|
||||||
|
}
|
||||||
|
String provided = authorization.substring(7).trim();
|
||||||
|
byte[] a = configured.getBytes(StandardCharsets.UTF_8);
|
||||||
|
byte[] b = provided.getBytes(StandardCharsets.UTF_8);
|
||||||
|
if (!MessageDigest.isEqual(a, b)) {
|
||||||
|
throw new BusinessException("Agent Bearer 无效");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+12
@@ -0,0 +1,12 @@
|
|||||||
|
package top.xyquan.ecomdmbbackend.modules.agent.llm.mapper;
|
||||||
|
|
||||||
|
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||||
|
import org.apache.ibatis.annotations.Mapper;
|
||||||
|
import top.xyquan.ecomdmbbackend.modules.agent.llm.model.po.AgentCompanyLlmSettingsPO;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 公司模型 API 配置 Mapper。
|
||||||
|
*/
|
||||||
|
@Mapper
|
||||||
|
public interface AgentCompanyLlmSettingsMapper extends BaseMapper<AgentCompanyLlmSettingsPO> {
|
||||||
|
}
|
||||||
+20
@@ -0,0 +1,20 @@
|
|||||||
|
package top.xyquan.ecomdmbbackend.modules.agent.llm.model.dto;
|
||||||
|
|
||||||
|
import jakarta.validation.constraints.NotBlank;
|
||||||
|
import lombok.Data;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 更新公司模型 API 配置。
|
||||||
|
*/
|
||||||
|
@Data
|
||||||
|
public class UpsertAgentLlmSettingsDTO {
|
||||||
|
|
||||||
|
@NotBlank(message = "baseUrl 不能为空")
|
||||||
|
private String baseUrl;
|
||||||
|
|
||||||
|
@NotBlank(message = "model 不能为空")
|
||||||
|
private String model;
|
||||||
|
|
||||||
|
/** 首次必填;后续留空表示不改 Key */
|
||||||
|
private String apiKey;
|
||||||
|
}
|
||||||
+50
@@ -0,0 +1,50 @@
|
|||||||
|
package top.xyquan.ecomdmbbackend.modules.agent.llm.model.po;
|
||||||
|
|
||||||
|
import com.baomidou.mybatisplus.annotation.IdType;
|
||||||
|
import com.baomidou.mybatisplus.annotation.TableField;
|
||||||
|
import com.baomidou.mybatisplus.annotation.TableId;
|
||||||
|
import com.baomidou.mybatisplus.annotation.TableName;
|
||||||
|
import lombok.Data;
|
||||||
|
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 公司 Agent 模型 API 配置。
|
||||||
|
*/
|
||||||
|
@Data
|
||||||
|
@TableName("agent_company_llm_settings")
|
||||||
|
public class AgentCompanyLlmSettingsPO {
|
||||||
|
|
||||||
|
@TableId(value = "id", type = IdType.AUTO)
|
||||||
|
private Long id;
|
||||||
|
|
||||||
|
@TableField("company_id")
|
||||||
|
private Long companyId;
|
||||||
|
|
||||||
|
@TableField("base_url")
|
||||||
|
private String baseUrl;
|
||||||
|
|
||||||
|
@TableField("api_key_encrypted")
|
||||||
|
private String apiKeyEncrypted;
|
||||||
|
|
||||||
|
@TableField("api_key_suffix")
|
||||||
|
private String apiKeySuffix;
|
||||||
|
|
||||||
|
@TableField("model")
|
||||||
|
private String model;
|
||||||
|
|
||||||
|
@TableField("extra_headers_json")
|
||||||
|
private String extraHeadersJson;
|
||||||
|
|
||||||
|
@TableField("create_by")
|
||||||
|
private Long createBy;
|
||||||
|
|
||||||
|
@TableField("update_by")
|
||||||
|
private Long updateBy;
|
||||||
|
|
||||||
|
@TableField("create_time")
|
||||||
|
private LocalDateTime createTime;
|
||||||
|
|
||||||
|
@TableField("update_time")
|
||||||
|
private LocalDateTime updateTime;
|
||||||
|
}
|
||||||
+16
@@ -0,0 +1,16 @@
|
|||||||
|
package top.xyquan.ecomdmbbackend.modules.agent.llm.model.vo;
|
||||||
|
|
||||||
|
import lombok.Data;
|
||||||
|
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 仅供 Agent 内部拉取的运行时配置(含明文 apiKey)。
|
||||||
|
*/
|
||||||
|
@Data
|
||||||
|
public class AgentLlmRuntimeVO {
|
||||||
|
private String baseUrl;
|
||||||
|
private String apiKey;
|
||||||
|
private String model;
|
||||||
|
private Map<String, String> extraHeaders;
|
||||||
|
}
|
||||||
+15
@@ -0,0 +1,15 @@
|
|||||||
|
package top.xyquan.ecomdmbbackend.modules.agent.llm.model.vo;
|
||||||
|
|
||||||
|
import lombok.Data;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 对公司管理员可见的模型配置(Key 仅掩码)。
|
||||||
|
*/
|
||||||
|
@Data
|
||||||
|
public class AgentLlmSettingsVO {
|
||||||
|
private boolean configured;
|
||||||
|
private String baseUrl;
|
||||||
|
private String model;
|
||||||
|
private String apiKeyMasked;
|
||||||
|
private String updateTime;
|
||||||
|
}
|
||||||
+18
@@ -0,0 +1,18 @@
|
|||||||
|
package top.xyquan.ecomdmbbackend.modules.agent.llm.service;
|
||||||
|
|
||||||
|
import top.xyquan.ecomdmbbackend.modules.agent.llm.model.dto.UpsertAgentLlmSettingsDTO;
|
||||||
|
import top.xyquan.ecomdmbbackend.modules.agent.llm.model.vo.AgentLlmRuntimeVO;
|
||||||
|
import top.xyquan.ecomdmbbackend.modules.agent.llm.model.vo.AgentLlmSettingsVO;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 公司模型 API 配置。
|
||||||
|
*/
|
||||||
|
public interface AgentCompanyLlmSettingsService {
|
||||||
|
|
||||||
|
AgentLlmSettingsVO getForCurrentCompany();
|
||||||
|
|
||||||
|
AgentLlmSettingsVO upsertForCurrentCompany(UpsertAgentLlmSettingsDTO dto);
|
||||||
|
|
||||||
|
/** Agent 内部:按公司取运行时明文配置 */
|
||||||
|
AgentLlmRuntimeVO getRuntime(Long companyId);
|
||||||
|
}
|
||||||
+222
@@ -0,0 +1,222 @@
|
|||||||
|
package top.xyquan.ecomdmbbackend.modules.agent.llm.service.impl;
|
||||||
|
|
||||||
|
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||||
|
import com.fasterxml.jackson.core.type.TypeReference;
|
||||||
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
import org.springframework.data.redis.core.StringRedisTemplate;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
|
import org.springframework.util.StringUtils;
|
||||||
|
import top.xyquan.ecomdmbbackend.common.exception.BusinessException;
|
||||||
|
import top.xyquan.ecomdmbbackend.modules.agent.llm.config.AgentLlmProperties;
|
||||||
|
import top.xyquan.ecomdmbbackend.modules.agent.llm.mapper.AgentCompanyLlmSettingsMapper;
|
||||||
|
import top.xyquan.ecomdmbbackend.modules.agent.llm.model.dto.UpsertAgentLlmSettingsDTO;
|
||||||
|
import top.xyquan.ecomdmbbackend.modules.agent.llm.model.po.AgentCompanyLlmSettingsPO;
|
||||||
|
import top.xyquan.ecomdmbbackend.modules.agent.llm.model.vo.AgentLlmRuntimeVO;
|
||||||
|
import top.xyquan.ecomdmbbackend.modules.agent.llm.model.vo.AgentLlmSettingsVO;
|
||||||
|
import top.xyquan.ecomdmbbackend.modules.agent.llm.service.AgentCompanyLlmSettingsService;
|
||||||
|
import top.xyquan.ecomdmbbackend.modules.agent.llm.support.AgentLlmCrypto;
|
||||||
|
import top.xyquan.ecomdmbbackend.modules.org.company.member.service.CompanyMemberService;
|
||||||
|
import top.xyquan.ecomdmbbackend.utils.CurrentUserContext;
|
||||||
|
|
||||||
|
import java.time.Duration;
|
||||||
|
import java.time.format.DateTimeFormatter;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 公司模型 API:MySQL 存密文,Redis 缓存运行时明文供 Agent 注入。
|
||||||
|
*/
|
||||||
|
@Slf4j
|
||||||
|
@Service
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class AgentCompanyLlmSettingsServiceImpl implements AgentCompanyLlmSettingsService {
|
||||||
|
|
||||||
|
private static final DateTimeFormatter ISO = DateTimeFormatter.ISO_LOCAL_DATE_TIME;
|
||||||
|
|
||||||
|
private final AgentCompanyLlmSettingsMapper mapper;
|
||||||
|
private final AgentLlmCrypto crypto;
|
||||||
|
private final AgentLlmProperties llmProperties;
|
||||||
|
private final CurrentUserContext currentUserContext;
|
||||||
|
private final CompanyMemberService companyMemberService;
|
||||||
|
private final StringRedisTemplate stringRedisTemplate;
|
||||||
|
private final ObjectMapper objectMapper;
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public AgentLlmSettingsVO getForCurrentCompany() {
|
||||||
|
Long companyId = currentUserContext.getCurrentCompanyId();
|
||||||
|
AgentCompanyLlmSettingsPO po = findByCompany(companyId);
|
||||||
|
return toPublicVo(po);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
@Transactional(rollbackFor = Exception.class)
|
||||||
|
public AgentLlmSettingsVO upsertForCurrentCompany(UpsertAgentLlmSettingsDTO dto) {
|
||||||
|
Long companyId = currentUserContext.getCurrentCompanyId();
|
||||||
|
Long userId = currentUserContext.getCurrentUserId();
|
||||||
|
if (!currentUserContext.isCurrentUserSuper()
|
||||||
|
&& !companyMemberService.isOwner(userId, companyId)) {
|
||||||
|
throw new BusinessException("仅公司拥有者可配置模型 API");
|
||||||
|
}
|
||||||
|
|
||||||
|
String baseUrl = dto.getBaseUrl().trim().replaceAll("/+$", "");
|
||||||
|
String model = dto.getModel().trim();
|
||||||
|
AgentCompanyLlmSettingsPO existing = findByCompany(companyId);
|
||||||
|
|
||||||
|
String encrypted;
|
||||||
|
String suffix;
|
||||||
|
String apiKey = dto.getApiKey();
|
||||||
|
if (StringUtils.hasText(apiKey) && !apiKey.trim().startsWith("****")) {
|
||||||
|
String plain = apiKey.trim();
|
||||||
|
encrypted = crypto.encrypt(plain);
|
||||||
|
suffix = plain.length() >= 4 ? plain.substring(plain.length() - 4) : plain;
|
||||||
|
} else if (existing != null) {
|
||||||
|
encrypted = existing.getApiKeyEncrypted();
|
||||||
|
suffix = existing.getApiKeySuffix();
|
||||||
|
} else {
|
||||||
|
throw new BusinessException("首次配置必须提供 apiKey");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (existing == null) {
|
||||||
|
AgentCompanyLlmSettingsPO po = new AgentCompanyLlmSettingsPO();
|
||||||
|
po.setCompanyId(companyId);
|
||||||
|
po.setBaseUrl(baseUrl);
|
||||||
|
po.setApiKeyEncrypted(encrypted);
|
||||||
|
po.setApiKeySuffix(suffix);
|
||||||
|
po.setModel(model);
|
||||||
|
po.setCreateBy(userId);
|
||||||
|
po.setUpdateBy(userId);
|
||||||
|
mapper.insert(po);
|
||||||
|
existing = po;
|
||||||
|
} else {
|
||||||
|
existing.setBaseUrl(baseUrl);
|
||||||
|
existing.setApiKeyEncrypted(encrypted);
|
||||||
|
existing.setApiKeySuffix(suffix);
|
||||||
|
existing.setModel(model);
|
||||||
|
existing.setUpdateBy(userId);
|
||||||
|
mapper.updateById(existing);
|
||||||
|
}
|
||||||
|
|
||||||
|
evictRuntimeCache(companyId);
|
||||||
|
// 预热缓存,降低 Agent 首包延迟
|
||||||
|
try {
|
||||||
|
cacheRuntime(companyId, buildRuntime(existing));
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.warn("预热 LLM 运行时缓存失败 companyId={}", companyId, e);
|
||||||
|
}
|
||||||
|
return toPublicVo(existing);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public AgentLlmRuntimeVO getRuntime(Long companyId) {
|
||||||
|
if (companyId == null) {
|
||||||
|
throw new BusinessException("companyId 不能为空");
|
||||||
|
}
|
||||||
|
AgentLlmRuntimeVO cached = readRuntimeCache(companyId);
|
||||||
|
if (cached != null) {
|
||||||
|
return cached;
|
||||||
|
}
|
||||||
|
AgentCompanyLlmSettingsPO po = findByCompany(companyId);
|
||||||
|
if (po == null) {
|
||||||
|
throw new BusinessException("公司尚未配置模型 API");
|
||||||
|
}
|
||||||
|
AgentLlmRuntimeVO runtime = buildRuntime(po);
|
||||||
|
cacheRuntime(companyId, runtime);
|
||||||
|
return runtime;
|
||||||
|
}
|
||||||
|
|
||||||
|
private AgentLlmRuntimeVO buildRuntime(AgentCompanyLlmSettingsPO po) {
|
||||||
|
AgentLlmRuntimeVO vo = new AgentLlmRuntimeVO();
|
||||||
|
vo.setBaseUrl(po.getBaseUrl());
|
||||||
|
vo.setApiKey(crypto.decrypt(po.getApiKeyEncrypted()));
|
||||||
|
vo.setModel(po.getModel());
|
||||||
|
vo.setExtraHeaders(parseHeaders(po.getExtraHeadersJson()));
|
||||||
|
return vo;
|
||||||
|
}
|
||||||
|
|
||||||
|
private Map<String, String> parseHeaders(String json) {
|
||||||
|
if (!StringUtils.hasText(json)) {
|
||||||
|
return Map.of();
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
return objectMapper.readValue(json, new TypeReference<Map<String, String>>() {
|
||||||
|
});
|
||||||
|
} catch (Exception e) {
|
||||||
|
return Map.of();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private AgentCompanyLlmSettingsPO findByCompany(Long companyId) {
|
||||||
|
return mapper.selectOne(new LambdaQueryWrapper<AgentCompanyLlmSettingsPO>()
|
||||||
|
.eq(AgentCompanyLlmSettingsPO::getCompanyId, companyId)
|
||||||
|
.last("LIMIT 1"));
|
||||||
|
}
|
||||||
|
|
||||||
|
private AgentLlmSettingsVO toPublicVo(AgentCompanyLlmSettingsPO po) {
|
||||||
|
AgentLlmSettingsVO vo = new AgentLlmSettingsVO();
|
||||||
|
if (po == null) {
|
||||||
|
vo.setConfigured(false);
|
||||||
|
return vo;
|
||||||
|
}
|
||||||
|
vo.setConfigured(true);
|
||||||
|
vo.setBaseUrl(po.getBaseUrl());
|
||||||
|
vo.setModel(po.getModel());
|
||||||
|
vo.setApiKeyMasked("****" + (po.getApiKeySuffix() == null ? "" : po.getApiKeySuffix()));
|
||||||
|
if (po.getUpdateTime() != null) {
|
||||||
|
vo.setUpdateTime(po.getUpdateTime().format(ISO));
|
||||||
|
}
|
||||||
|
return vo;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String redisKey(Long companyId) {
|
||||||
|
return "agent:llm:rt:" + companyId;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void cacheRuntime(Long companyId, AgentLlmRuntimeVO runtime) {
|
||||||
|
try {
|
||||||
|
Map<String, Object> payload = new HashMap<>();
|
||||||
|
payload.put("base_url", runtime.getBaseUrl());
|
||||||
|
payload.put("api_key", runtime.getApiKey());
|
||||||
|
payload.put("model", runtime.getModel());
|
||||||
|
payload.put("extra_headers", runtime.getExtraHeaders() == null ? Map.of() : runtime.getExtraHeaders());
|
||||||
|
stringRedisTemplate.opsForValue().set(
|
||||||
|
redisKey(companyId),
|
||||||
|
objectMapper.writeValueAsString(payload),
|
||||||
|
Duration.ofSeconds(Math.max(60, llmProperties.getRuntimeCacheTtlSeconds())));
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.warn("写入 LLM Redis 缓存失败 companyId={}", companyId, e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private AgentLlmRuntimeVO readRuntimeCache(Long companyId) {
|
||||||
|
try {
|
||||||
|
String raw = stringRedisTemplate.opsForValue().get(redisKey(companyId));
|
||||||
|
if (!StringUtils.hasText(raw)) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
Map<String, Object> map = objectMapper.readValue(raw, new TypeReference<>() {
|
||||||
|
});
|
||||||
|
AgentLlmRuntimeVO vo = new AgentLlmRuntimeVO();
|
||||||
|
vo.setBaseUrl(String.valueOf(map.get("base_url")));
|
||||||
|
vo.setApiKey(String.valueOf(map.get("api_key")));
|
||||||
|
vo.setModel(String.valueOf(map.get("model")));
|
||||||
|
Object headers = map.get("extra_headers");
|
||||||
|
if (headers instanceof Map<?, ?> m) {
|
||||||
|
Map<String, String> h = new HashMap<>();
|
||||||
|
m.forEach((k, v) -> h.put(String.valueOf(k), String.valueOf(v)));
|
||||||
|
vo.setExtraHeaders(h);
|
||||||
|
} else {
|
||||||
|
vo.setExtraHeaders(Map.of());
|
||||||
|
}
|
||||||
|
return vo;
|
||||||
|
} catch (Exception e) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void evictRuntimeCache(Long companyId) {
|
||||||
|
stringRedisTemplate.delete(redisKey(companyId));
|
||||||
|
}
|
||||||
|
}
|
||||||
+78
@@ -0,0 +1,78 @@
|
|||||||
|
package top.xyquan.ecomdmbbackend.modules.agent.llm.support;
|
||||||
|
|
||||||
|
import org.springframework.beans.factory.annotation.Value;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
import org.springframework.util.StringUtils;
|
||||||
|
import top.xyquan.ecomdmbbackend.common.exception.BusinessException;
|
||||||
|
import top.xyquan.ecomdmbbackend.modules.agent.llm.config.AgentLlmProperties;
|
||||||
|
|
||||||
|
import javax.crypto.Cipher;
|
||||||
|
import javax.crypto.SecretKey;
|
||||||
|
import javax.crypto.spec.GCMParameterSpec;
|
||||||
|
import javax.crypto.spec.SecretKeySpec;
|
||||||
|
import java.nio.ByteBuffer;
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.security.MessageDigest;
|
||||||
|
import java.security.SecureRandom;
|
||||||
|
import java.util.Base64;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 租户 API Key AES-GCM 加解密(密钥由 ecom.agent.llm.secret 或 jwt.secret 派生)。
|
||||||
|
*/
|
||||||
|
@Component
|
||||||
|
public class AgentLlmCrypto {
|
||||||
|
|
||||||
|
private static final String TRANSFORMATION = "AES/GCM/NoPadding";
|
||||||
|
private static final int GCM_IV_LENGTH = 12;
|
||||||
|
private static final int GCM_TAG_LENGTH = 128;
|
||||||
|
|
||||||
|
private final AgentLlmProperties llmProperties;
|
||||||
|
private final String jwtSecret;
|
||||||
|
|
||||||
|
public AgentLlmCrypto(AgentLlmProperties llmProperties,
|
||||||
|
@Value("${jwt.secret}") String jwtSecret) {
|
||||||
|
this.llmProperties = llmProperties;
|
||||||
|
this.jwtSecret = jwtSecret;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String encrypt(String plain) {
|
||||||
|
try {
|
||||||
|
byte[] iv = new byte[GCM_IV_LENGTH];
|
||||||
|
new SecureRandom().nextBytes(iv);
|
||||||
|
Cipher cipher = Cipher.getInstance(TRANSFORMATION);
|
||||||
|
cipher.init(Cipher.ENCRYPT_MODE, secretKey(), new GCMParameterSpec(GCM_TAG_LENGTH, iv));
|
||||||
|
byte[] cipherBytes = cipher.doFinal(plain.getBytes(StandardCharsets.UTF_8));
|
||||||
|
ByteBuffer buffer = ByteBuffer.allocate(iv.length + cipherBytes.length);
|
||||||
|
buffer.put(iv);
|
||||||
|
buffer.put(cipherBytes);
|
||||||
|
return Base64.getEncoder().encodeToString(buffer.array());
|
||||||
|
} catch (Exception e) {
|
||||||
|
throw new BusinessException("加密 API Key 失败");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public String decrypt(String token) {
|
||||||
|
try {
|
||||||
|
byte[] all = Base64.getDecoder().decode(token);
|
||||||
|
ByteBuffer buffer = ByteBuffer.wrap(all);
|
||||||
|
byte[] iv = new byte[GCM_IV_LENGTH];
|
||||||
|
buffer.get(iv);
|
||||||
|
byte[] cipherBytes = new byte[buffer.remaining()];
|
||||||
|
buffer.get(cipherBytes);
|
||||||
|
Cipher cipher = Cipher.getInstance(TRANSFORMATION);
|
||||||
|
cipher.init(Cipher.DECRYPT_MODE, secretKey(), new GCMParameterSpec(GCM_TAG_LENGTH, iv));
|
||||||
|
return new String(cipher.doFinal(cipherBytes), StandardCharsets.UTF_8);
|
||||||
|
} catch (Exception e) {
|
||||||
|
throw new BusinessException("解密 API Key 失败,请检查 ecom.agent.llm.secret");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private SecretKey secretKey() throws Exception {
|
||||||
|
String material = StringUtils.hasText(llmProperties.getSecret())
|
||||||
|
? llmProperties.getSecret()
|
||||||
|
: jwtSecret;
|
||||||
|
byte[] digest = MessageDigest.getInstance("SHA-256")
|
||||||
|
.digest(material.getBytes(StandardCharsets.UTF_8));
|
||||||
|
return new SecretKeySpec(digest, "AES");
|
||||||
|
}
|
||||||
|
}
|
||||||
+1
-1
@@ -18,7 +18,7 @@ public class AgentMcpProperties {
|
|||||||
private String bearerToken = "";
|
private String bearerToken = "";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Agent 绑定的公司 ID(BI 等读模型按租户隔离);为空则业务 tool 会失败。
|
* 本地单租户 fallback;生产应由请求头 X-Agent-Company-Id 注入。
|
||||||
*/
|
*/
|
||||||
private Long companyId;
|
private Long companyId;
|
||||||
}
|
}
|
||||||
|
|||||||
+4
@@ -58,4 +58,8 @@ public class AgentMcpAuthentication implements Authentication {
|
|||||||
public Long getCompanyId() {
|
public Long getCompanyId() {
|
||||||
return principal.companyId();
|
return principal.companyId();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public String getUserId() {
|
||||||
|
return principal.userId();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+45
-6
@@ -19,13 +19,17 @@ import java.nio.charset.StandardCharsets;
|
|||||||
import java.security.MessageDigest;
|
import java.security.MessageDigest;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Agent MCP 鉴权:仅处理 /mcp,校验独立 Bearer,与 JWT / Open API Key 分离。
|
* Agent 鉴权:处理 /mcp 与 /api/internal/agent/**;Bearer 为服务凭证,租户来自请求头。
|
||||||
*/
|
*/
|
||||||
@Slf4j
|
@Slf4j
|
||||||
@Component
|
@Component
|
||||||
public class AgentMcpAuthenticationFilter extends OncePerRequestFilter {
|
public class AgentMcpAuthenticationFilter extends OncePerRequestFilter {
|
||||||
|
|
||||||
|
public static final String HEADER_COMPANY_ID = "X-Agent-Company-Id";
|
||||||
|
public static final String HEADER_USER_ID = "X-Agent-User-Id";
|
||||||
|
|
||||||
private static final String MCP_PATH = "/mcp";
|
private static final String MCP_PATH = "/mcp";
|
||||||
|
private static final String INTERNAL_PREFIX = "/api/internal/agent";
|
||||||
|
|
||||||
private final AgentMcpProperties properties;
|
private final AgentMcpProperties properties;
|
||||||
private final ObjectMapper objectMapper;
|
private final ObjectMapper objectMapper;
|
||||||
@@ -41,7 +45,9 @@ public class AgentMcpAuthenticationFilter extends OncePerRequestFilter {
|
|||||||
if (uri == null) {
|
if (uri == null) {
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
return !(uri.equals(MCP_PATH) || uri.startsWith(MCP_PATH + "/"));
|
return !(uri.equals(MCP_PATH)
|
||||||
|
|| uri.startsWith(MCP_PATH + "/")
|
||||||
|
|| uri.startsWith(INTERNAL_PREFIX));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
@@ -53,17 +59,26 @@ public class AgentMcpAuthenticationFilter extends OncePerRequestFilter {
|
|||||||
try {
|
try {
|
||||||
String configured = properties.getBearerToken();
|
String configured = properties.getBearerToken();
|
||||||
if (!StringUtils.hasText(configured)) {
|
if (!StringUtils.hasText(configured)) {
|
||||||
writeUnauthorized(response, "MCP 凭证未配置");
|
writeUnauthorized(response, "Agent 凭证未配置");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
String provided = extractBearer(request);
|
String provided = extractBearer(request);
|
||||||
if (!StringUtils.hasText(provided) || !tokenEquals(configured, provided)) {
|
if (!StringUtils.hasText(provided) || !tokenEquals(configured, provided)) {
|
||||||
writeUnauthorized(response, "MCP 凭证无效或缺失");
|
writeUnauthorized(response, "Agent 凭证无效或缺失");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
AgentMcpPrincipal principal = new AgentMcpPrincipal("agent-mcp", properties.getCompanyId());
|
Long companyId = resolveCompanyId(request);
|
||||||
|
String userId = resolveUserId(request);
|
||||||
|
// /mcp 业务 tool 必须有 company;内部 llm-runtime 可用 query companyId,头可空
|
||||||
|
boolean mcpCall = isMcpPath(request.getRequestURI());
|
||||||
|
if (mcpCall && companyId == null) {
|
||||||
|
writeUnauthorized(response, "缺少租户头 " + HEADER_COMPANY_ID);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
AgentMcpPrincipal principal = new AgentMcpPrincipal("agent-mcp", companyId, userId);
|
||||||
SecurityContextHolder.getContext().setAuthentication(new AgentMcpAuthentication(principal));
|
SecurityContextHolder.getContext().setAuthentication(new AgentMcpAuthentication(principal));
|
||||||
filterChain.doFilter(request, response);
|
filterChain.doFilter(request, response);
|
||||||
} finally {
|
} finally {
|
||||||
@@ -71,6 +86,31 @@ public class AgentMcpAuthenticationFilter extends OncePerRequestFilter {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private Long resolveCompanyId(HttpServletRequest request) {
|
||||||
|
String header = request.getHeader(HEADER_COMPANY_ID);
|
||||||
|
if (StringUtils.hasText(header)) {
|
||||||
|
try {
|
||||||
|
return Long.parseLong(header.trim());
|
||||||
|
} catch (NumberFormatException e) {
|
||||||
|
log.warn("非法 {}={}", HEADER_COMPANY_ID, header);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// 兼容旧配置:无头时回退静态 company-id(仅建议本地单租户)
|
||||||
|
return properties.getCompanyId();
|
||||||
|
}
|
||||||
|
|
||||||
|
private String resolveUserId(HttpServletRequest request) {
|
||||||
|
String header = request.getHeader(HEADER_USER_ID);
|
||||||
|
if (StringUtils.hasText(header)) {
|
||||||
|
return header.trim();
|
||||||
|
}
|
||||||
|
return "0";
|
||||||
|
}
|
||||||
|
|
||||||
|
private static boolean isMcpPath(String uri) {
|
||||||
|
return uri != null && (uri.equals(MCP_PATH) || uri.startsWith(MCP_PATH + "/"));
|
||||||
|
}
|
||||||
|
|
||||||
private String extractBearer(HttpServletRequest request) {
|
private String extractBearer(HttpServletRequest request) {
|
||||||
String authorization = request.getHeader("Authorization");
|
String authorization = request.getHeader("Authorization");
|
||||||
if (StringUtils.hasText(authorization) && authorization.startsWith("Bearer ")) {
|
if (StringUtils.hasText(authorization) && authorization.startsWith("Bearer ")) {
|
||||||
@@ -79,7 +119,6 @@ public class AgentMcpAuthenticationFilter extends OncePerRequestFilter {
|
|||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 常量时间比较,降低侧信道风险。 */
|
|
||||||
private static boolean tokenEquals(String expected, String actual) {
|
private static boolean tokenEquals(String expected, String actual) {
|
||||||
byte[] a = expected.getBytes(StandardCharsets.UTF_8);
|
byte[] a = expected.getBytes(StandardCharsets.UTF_8);
|
||||||
byte[] b = actual.getBytes(StandardCharsets.UTF_8);
|
byte[] b = actual.getBytes(StandardCharsets.UTF_8);
|
||||||
|
|||||||
+6
-2
@@ -1,7 +1,11 @@
|
|||||||
package top.xyquan.ecomdmbbackend.modules.agent.mcp.security;
|
package top.xyquan.ecomdmbbackend.modules.agent.mcp.security;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* MCP Agent 认证主体(m2m);companyId 绑定租户数据范围。
|
* MCP / Agent 内部调用主体;companyId、userId 来自请求头(多租户)。
|
||||||
*/
|
*/
|
||||||
public record AgentMcpPrincipal(String clientName, Long companyId) {
|
public record AgentMcpPrincipal(String clientName, Long companyId, String userId) {
|
||||||
|
|
||||||
|
public AgentMcpPrincipal(String clientName, Long companyId) {
|
||||||
|
this(clientName, companyId, "0");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import org.springframework.context.annotation.Lazy;
|
|||||||
import org.springframework.security.core.Authentication;
|
import org.springframework.security.core.Authentication;
|
||||||
import org.springframework.security.core.context.SecurityContextHolder;
|
import org.springframework.security.core.context.SecurityContextHolder;
|
||||||
import org.springframework.stereotype.Component;
|
import org.springframework.stereotype.Component;
|
||||||
|
import org.springframework.util.StringUtils;
|
||||||
import top.xyquan.ecomdmbbackend.common.exception.BusinessException;
|
import top.xyquan.ecomdmbbackend.common.exception.BusinessException;
|
||||||
import top.xyquan.ecomdmbbackend.modules.agent.mcp.security.AgentMcpAuthentication;
|
import top.xyquan.ecomdmbbackend.modules.agent.mcp.security.AgentMcpAuthentication;
|
||||||
import top.xyquan.ecomdmbbackend.modules.open.common.context.OpenApiContextHolder;
|
import top.xyquan.ecomdmbbackend.modules.open.common.context.OpenApiContextHolder;
|
||||||
@@ -61,10 +62,11 @@ public class CurrentUserContext {
|
|||||||
if (authentication instanceof AgentMcpAuthentication agentMcpAuthentication) {
|
if (authentication instanceof AgentMcpAuthentication agentMcpAuthentication) {
|
||||||
Long companyId = agentMcpAuthentication.getCompanyId();
|
Long companyId = agentMcpAuthentication.getCompanyId();
|
||||||
if (companyId == null) {
|
if (companyId == null) {
|
||||||
throw new BusinessException("MCP 未绑定公司,请配置 ecom.agent.mcp.company-id");
|
throw new BusinessException("MCP 未绑定公司,请传请求头 X-Agent-Company-Id");
|
||||||
}
|
}
|
||||||
|
String userId = agentMcpAuthentication.getUserId();
|
||||||
return TokenPayload.builder()
|
return TokenPayload.builder()
|
||||||
.userId("0")
|
.userId(StringUtils.hasText(userId) ? userId : "0")
|
||||||
.companyId(companyId)
|
.companyId(companyId)
|
||||||
.isSuper(false)
|
.isSuper(false)
|
||||||
.companyRole("owner")
|
.companyRole("owner")
|
||||||
|
|||||||
@@ -92,13 +92,17 @@ ecom:
|
|||||||
admin-real-name: 超级管理员
|
admin-real-name: 超级管理员
|
||||||
admin-phone: 13800000001
|
admin-phone: 13800000001
|
||||||
admin-password: admin123
|
admin-password: admin123
|
||||||
# Agent → MCP 独立凭证(与浏览器 JWT、开放 API Key 分离)
|
# Agent → MCP / 内部接口凭证(与浏览器 JWT、开放 API Key 分离)
|
||||||
agent:
|
agent:
|
||||||
mcp:
|
mcp:
|
||||||
# 为空则拒绝所有 MCP 请求;生产务必用环境变量覆盖
|
# 为空则拒绝所有 MCP / 内部 Agent 请求;生产务必用环境变量覆盖
|
||||||
bearer-token: ${AGENT_MCP_TOKEN:}
|
bearer-token: ${AGENT_MCP_TOKEN:}
|
||||||
# Agent 数据租户;BI tool 依赖此值
|
# 仅本地单租户 fallback;多租户以请求头 X-Agent-Company-Id 为准
|
||||||
company-id: ${AGENT_MCP_COMPANY_ID:}
|
company-id: ${AGENT_MCP_COMPANY_ID:}
|
||||||
|
llm:
|
||||||
|
# API Key 加解密材料;空则派生自 jwt.secret
|
||||||
|
secret: ${AGENT_LLM_SECRET:}
|
||||||
|
runtime-cache-ttl-seconds: 600
|
||||||
|
|
||||||
# JWT 令牌有效期(密钥见各环境配置)
|
# JWT 令牌有效期(密钥见各环境配置)
|
||||||
jwt:
|
jwt:
|
||||||
|
|||||||
@@ -933,3 +933,22 @@ SELECT m.id, p.id FROM `sys_menu` m JOIN `sys_permission` p ON (p.code LIKE 'ec:
|
|||||||
INSERT IGNORE INTO `sys_menu_permission` (`menu_id`, `permission_id`)
|
INSERT IGNORE INTO `sys_menu_permission` (`menu_id`, `permission_id`)
|
||||||
SELECT m.id, p.id FROM `sys_menu` m JOIN `sys_permission` p ON p.code = 'bi:workbench:read' WHERE m.name = '工作台';
|
SELECT m.id, p.id FROM `sys_menu` m JOIN `sys_permission` p ON p.code = 'bi:workbench:read' WHERE m.name = '工作台';
|
||||||
|
|
||||||
|
INSERT INTO `sys_menu` (`id`, `parent_id`, `super`, `route_name`, `title`, `path`, `component`, `redirect`, `icon`, `type`, `visible`, `status`, `keep_alive`, `order`)
|
||||||
|
SELECT 14080, NULL, 0, 'AgentAssistant', '智能助手', '/agent/chat', '/agent/chat/index', '', 'lucide:bot', 'menu', 1, 1, 0, 14
|
||||||
|
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_menu` WHERE `id` = 14080 OR `route_name` = 'AgentAssistant');
|
||||||
|
|
||||||
|
INSERT INTO `sys_permission` (`id`, `parent_id`, `code`, `name`, `type`, `status`, `remark`, `sort_order`)
|
||||||
|
SELECT 4800, (SELECT id FROM `sys_permission` WHERE `code` = 'data' LIMIT 1), 'agent', '智能助手', 'module', 1, '', 50
|
||||||
|
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `id` = 4800 OR `code` = 'agent');
|
||||||
|
|
||||||
|
INSERT INTO `sys_permission` (`id`, `parent_id`, `code`, `name`, `type`, `status`, `remark`, `sort_order`)
|
||||||
|
SELECT 4801, (SELECT id FROM `sys_permission` WHERE `code` = 'agent' LIMIT 1), 'agent:chat', '对话', 'api', 1, '', 1
|
||||||
|
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `id` = 4801 OR `code` = 'agent:chat');
|
||||||
|
|
||||||
|
INSERT INTO `sys_permission` (`id`, `parent_id`, `code`, `name`, `type`, `status`, `remark`, `sort_order`)
|
||||||
|
SELECT 4802, (SELECT id FROM `sys_permission` WHERE `code` = 'agent' LIMIT 1), 'agent:llm-settings', '模型配置', 'api', 1, '', 2
|
||||||
|
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `id` = 4802 OR `code` = 'agent:llm-settings');
|
||||||
|
|
||||||
|
INSERT IGNORE INTO `sys_menu_permission` (`menu_id`, `permission_id`)
|
||||||
|
SELECT m.id, p.id FROM `sys_menu` m JOIN `sys_permission` p ON p.code IN ('agent:chat', 'agent:llm-settings') WHERE m.route_name = 'AgentAssistant';
|
||||||
|
|
||||||
|
|||||||
@@ -43,6 +43,8 @@
|
|||||||
"@vueuse/core": "catalog:",
|
"@vueuse/core": "catalog:",
|
||||||
"ant-design-vue": "catalog:",
|
"ant-design-vue": "catalog:",
|
||||||
"dayjs": "catalog:",
|
"dayjs": "catalog:",
|
||||||
|
"dompurify": "^3.4.15",
|
||||||
|
"marked": "^18.0.13",
|
||||||
"papaparse": "^5.4.1",
|
"papaparse": "^5.4.1",
|
||||||
"pinia": "catalog:",
|
"pinia": "catalog:",
|
||||||
"spark-md5": "^3.0.2",
|
"spark-md5": "^3.0.2",
|
||||||
@@ -51,6 +53,8 @@
|
|||||||
"vue-waterfall-plugin-next": "^3.0.0"
|
"vue-waterfall-plugin-next": "^3.0.0"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
|
"@types/dompurify": "^3.2.0",
|
||||||
|
"@types/marked": "^6.0.0",
|
||||||
"@types/papaparse": "^5.3.14",
|
"@types/papaparse": "^5.3.14",
|
||||||
"@types/spark-md5": "^3.0.5"
|
"@types/spark-md5": "^3.0.5"
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,172 @@
|
|||||||
|
import { useAccessStore } from '@vben/stores';
|
||||||
|
|
||||||
|
import { requestClient } from '#/api/request';
|
||||||
|
|
||||||
|
/** Agent 服务走 /api/agent,开发态由 Vite 代理到 :8200 */
|
||||||
|
|
||||||
|
export namespace AgentVO {
|
||||||
|
export interface Session {
|
||||||
|
threadId: string;
|
||||||
|
title: string;
|
||||||
|
status: string;
|
||||||
|
createdAt?: string;
|
||||||
|
updatedAt?: string;
|
||||||
|
lastMessageAt?: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface Message {
|
||||||
|
id?: string;
|
||||||
|
seq: number;
|
||||||
|
role: 'user' | 'assistant' | 'system' | 'tool';
|
||||||
|
content: string;
|
||||||
|
createdAt?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface LlmSettings {
|
||||||
|
configured: boolean;
|
||||||
|
baseUrl?: string | null;
|
||||||
|
model?: string | null;
|
||||||
|
apiKeyMasked?: string | null;
|
||||||
|
/** Server 字段;兼容旧 updatedAt */
|
||||||
|
updateTime?: string;
|
||||||
|
updatedAt?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface Memory {
|
||||||
|
id: string;
|
||||||
|
kind: string;
|
||||||
|
key?: string | null;
|
||||||
|
text: string;
|
||||||
|
updatedAt?: string;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
export async function listAgentSessionsApi() {
|
||||||
|
return requestClient.get<{ items: AgentVO.Session[] }>('/agent/sessions');
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function createAgentSessionApi(title?: string) {
|
||||||
|
return requestClient.post<AgentVO.Session>('/agent/sessions', { title });
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function listAgentMessagesApi(threadId: string) {
|
||||||
|
return requestClient.get<{ items: AgentVO.Message[] }>(
|
||||||
|
`/agent/sessions/${threadId}/messages`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function listAgentMemoriesApi() {
|
||||||
|
return requestClient.get<{ items: AgentVO.Memory[] }>('/agent/memories');
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function deleteAgentMemoryApi(memoryId: string) {
|
||||||
|
return requestClient.delete<{ ok: boolean }>(`/agent/memories/${memoryId}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getAgentLlmSettingsApi() {
|
||||||
|
return requestClient.get<AgentVO.LlmSettings>(
|
||||||
|
'/company/agent-llm-settings',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function updateAgentLlmSettingsApi(body: {
|
||||||
|
baseUrl: string;
|
||||||
|
model: string;
|
||||||
|
apiKey?: string;
|
||||||
|
}) {
|
||||||
|
return requestClient.put<AgentVO.LlmSettings>(
|
||||||
|
'/company/agent-llm-settings',
|
||||||
|
body,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** SSE 流式发消息 */
|
||||||
|
export function streamAgentChat(options: {
|
||||||
|
threadId: string;
|
||||||
|
content: string;
|
||||||
|
onToken: (text: string) => void;
|
||||||
|
onDone?: () => void;
|
||||||
|
onError?: (message: string) => void;
|
||||||
|
}): AbortController {
|
||||||
|
const controller = new AbortController();
|
||||||
|
const accessStore = useAccessStore();
|
||||||
|
const token = accessStore.accessToken;
|
||||||
|
const url = `/api/agent/sessions/${options.threadId}/chat`;
|
||||||
|
|
||||||
|
void (async () => {
|
||||||
|
try {
|
||||||
|
const res = await fetch(url, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
Accept: 'text/event-stream',
|
||||||
|
...(token ? { Authorization: `Bearer ${token}` } : {}),
|
||||||
|
},
|
||||||
|
body: JSON.stringify({ content: options.content }),
|
||||||
|
signal: controller.signal,
|
||||||
|
});
|
||||||
|
if (!res.ok || !res.body) {
|
||||||
|
options.onError?.(`请求失败 HTTP ${res.status}`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const reader = res.body.getReader();
|
||||||
|
const decoder = new TextDecoder();
|
||||||
|
let buffer = '';
|
||||||
|
let finished = false;
|
||||||
|
|
||||||
|
const consumeBlock = (part: string) => {
|
||||||
|
const lines = part.split('\n');
|
||||||
|
let event = 'message';
|
||||||
|
const dataLines: string[] = [];
|
||||||
|
for (const rawLine of lines) {
|
||||||
|
const line = rawLine.replace(/\r$/, '');
|
||||||
|
if (!line || line.startsWith(':')) continue;
|
||||||
|
if (line.startsWith('event:')) {
|
||||||
|
event = line.slice(6).trim();
|
||||||
|
} else if (line.startsWith('data:')) {
|
||||||
|
dataLines.push(line.slice(5).replace(/^ /, ''));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const data = dataLines.join('\n');
|
||||||
|
if (!data && event !== 'done') return;
|
||||||
|
if (event === 'token') {
|
||||||
|
try {
|
||||||
|
const parsed = JSON.parse(data) as { text?: string };
|
||||||
|
if (parsed.text) options.onToken(parsed.text);
|
||||||
|
} catch {
|
||||||
|
options.onToken(data);
|
||||||
|
}
|
||||||
|
} else if (event === 'error') {
|
||||||
|
try {
|
||||||
|
const parsed = JSON.parse(data) as { message?: string };
|
||||||
|
options.onError?.(parsed.message || data);
|
||||||
|
} catch {
|
||||||
|
options.onError?.(data);
|
||||||
|
}
|
||||||
|
} else if (event === 'done') {
|
||||||
|
finished = true;
|
||||||
|
options.onDone?.();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
while (true) {
|
||||||
|
const { done, value } = await reader.read();
|
||||||
|
if (done) break;
|
||||||
|
buffer += decoder.decode(value, { stream: true });
|
||||||
|
// 统一换行,按 SSE 事件块拆分
|
||||||
|
buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n');
|
||||||
|
const parts = buffer.split('\n\n');
|
||||||
|
buffer = parts.pop() || '';
|
||||||
|
for (const part of parts) {
|
||||||
|
if (part.trim()) consumeBlock(part);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (buffer.trim()) consumeBlock(buffer);
|
||||||
|
if (!finished) options.onDone?.();
|
||||||
|
} catch (e: any) {
|
||||||
|
if (e?.name === 'AbortError') return;
|
||||||
|
options.onError?.(e?.message || '流式连接失败');
|
||||||
|
}
|
||||||
|
})();
|
||||||
|
|
||||||
|
return controller;
|
||||||
|
}
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
export type { AgentVO } from './apis';
|
||||||
|
export {
|
||||||
|
createAgentSessionApi,
|
||||||
|
deleteAgentMemoryApi,
|
||||||
|
getAgentLlmSettingsApi,
|
||||||
|
listAgentMemoriesApi,
|
||||||
|
listAgentMessagesApi,
|
||||||
|
listAgentSessionsApi,
|
||||||
|
streamAgentChat,
|
||||||
|
updateAgentLlmSettingsApi,
|
||||||
|
} from './apis';
|
||||||
@@ -0,0 +1,489 @@
|
|||||||
|
<script lang="ts" setup>
|
||||||
|
import { computed, nextTick, onBeforeUnmount, ref, watch } from 'vue';
|
||||||
|
|
||||||
|
import { Page } from '@vben/common-ui';
|
||||||
|
|
||||||
|
import {
|
||||||
|
Button,
|
||||||
|
Empty,
|
||||||
|
Form,
|
||||||
|
FormItem,
|
||||||
|
Input,
|
||||||
|
InputPassword,
|
||||||
|
Modal,
|
||||||
|
Textarea,
|
||||||
|
message,
|
||||||
|
} from 'ant-design-vue';
|
||||||
|
|
||||||
|
import {
|
||||||
|
createAgentSessionApi,
|
||||||
|
deleteAgentMemoryApi,
|
||||||
|
getAgentLlmSettingsApi,
|
||||||
|
listAgentMemoriesApi,
|
||||||
|
listAgentMessagesApi,
|
||||||
|
listAgentSessionsApi,
|
||||||
|
streamAgentChat,
|
||||||
|
updateAgentLlmSettingsApi,
|
||||||
|
type AgentVO,
|
||||||
|
} from '#/api/agent';
|
||||||
|
|
||||||
|
import { renderAgentMarkdown } from './markdown';
|
||||||
|
|
||||||
|
defineOptions({ name: 'AgentChat' });
|
||||||
|
|
||||||
|
const loadingSessions = ref(false);
|
||||||
|
const loadingMessages = ref(false);
|
||||||
|
const sending = ref(false);
|
||||||
|
const sessions = ref<AgentVO.Session[]>([]);
|
||||||
|
const activeThreadId = ref<string | null>(null);
|
||||||
|
const messages = ref<AgentVO.Message[]>([]);
|
||||||
|
/** 当前流式助手正文(与 messages 末条同步,避免列表被 loading 遮挡时丢更新) */
|
||||||
|
const streamingText = ref('');
|
||||||
|
const draft = ref('');
|
||||||
|
const settingsOpen = ref(false);
|
||||||
|
const savingSettings = ref(false);
|
||||||
|
const memories = ref<AgentVO.Memory[]>([]);
|
||||||
|
const llmForm = ref({
|
||||||
|
baseUrl: '',
|
||||||
|
model: '',
|
||||||
|
apiKey: '',
|
||||||
|
apiKeyMasked: '' as string | null,
|
||||||
|
configured: false,
|
||||||
|
});
|
||||||
|
const messagePaneRef = ref<HTMLElement | null>(null);
|
||||||
|
let abort: AbortController | null = null;
|
||||||
|
/** 丢弃过期的 loadMessages */
|
||||||
|
let messagesLoadSeq = 0;
|
||||||
|
|
||||||
|
const activeSession = computed(() =>
|
||||||
|
sessions.value.find((s) => s.threadId === activeThreadId.value),
|
||||||
|
);
|
||||||
|
|
||||||
|
const showMessageLoading = computed(
|
||||||
|
() => loadingMessages.value && !sending.value && messages.value.length === 0,
|
||||||
|
);
|
||||||
|
|
||||||
|
function bubbleHtml(m: AgentVO.Message, idx: number): string {
|
||||||
|
const isStreamingAssistant =
|
||||||
|
sending.value &&
|
||||||
|
idx === messages.value.length - 1 &&
|
||||||
|
m.role === 'assistant';
|
||||||
|
const text = isStreamingAssistant ? streamingText.value : m.content || '';
|
||||||
|
if (!text) {
|
||||||
|
return isStreamingAssistant ? '…' : '';
|
||||||
|
}
|
||||||
|
if (m.role === 'user') {
|
||||||
|
return text
|
||||||
|
.replace(/&/g, '&')
|
||||||
|
.replace(/</g, '<')
|
||||||
|
.replace(/>/g, '>')
|
||||||
|
.replace(/\n/g, '<br>');
|
||||||
|
}
|
||||||
|
return renderAgentMarkdown(text);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function refreshSessions() {
|
||||||
|
loadingSessions.value = true;
|
||||||
|
try {
|
||||||
|
const res = await listAgentSessionsApi();
|
||||||
|
sessions.value = res.items || [];
|
||||||
|
if (!activeThreadId.value && sessions.value[0]) {
|
||||||
|
activeThreadId.value = sessions.value[0].threadId;
|
||||||
|
}
|
||||||
|
} catch (e: any) {
|
||||||
|
message.error(e?.message || '加载会话失败');
|
||||||
|
} finally {
|
||||||
|
loadingSessions.value = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function loadMessages(threadId: string) {
|
||||||
|
const seq = ++messagesLoadSeq;
|
||||||
|
loadingMessages.value = true;
|
||||||
|
try {
|
||||||
|
const res = await listAgentMessagesApi(threadId);
|
||||||
|
if (seq !== messagesLoadSeq || sending.value || threadId !== activeThreadId.value) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
messages.value = res.items || [];
|
||||||
|
streamingText.value = '';
|
||||||
|
await nextTick();
|
||||||
|
scrollToBottom();
|
||||||
|
} catch (e: any) {
|
||||||
|
if (seq === messagesLoadSeq && !sending.value) {
|
||||||
|
message.error(e?.message || '加载消息失败');
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
if (seq === messagesLoadSeq) {
|
||||||
|
loadingMessages.value = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function scrollToBottom() {
|
||||||
|
const el = messagePaneRef.value;
|
||||||
|
if (el) el.scrollTop = el.scrollHeight;
|
||||||
|
}
|
||||||
|
|
||||||
|
watch(activeThreadId, (id) => {
|
||||||
|
if (sending.value) return;
|
||||||
|
if (id) void loadMessages(id);
|
||||||
|
else {
|
||||||
|
messages.value = [];
|
||||||
|
streamingText.value = '';
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
async function createSession() {
|
||||||
|
try {
|
||||||
|
const s = await createAgentSessionApi();
|
||||||
|
sessions.value = [s, ...sessions.value];
|
||||||
|
messagesLoadSeq += 1;
|
||||||
|
loadingMessages.value = false;
|
||||||
|
messages.value = [];
|
||||||
|
streamingText.value = '';
|
||||||
|
activeThreadId.value = s.threadId;
|
||||||
|
} catch (e: any) {
|
||||||
|
message.error(e?.message || '新建会话失败');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function openSettings() {
|
||||||
|
settingsOpen.value = true;
|
||||||
|
try {
|
||||||
|
const [s, mem] = await Promise.all([
|
||||||
|
getAgentLlmSettingsApi(),
|
||||||
|
listAgentMemoriesApi().catch(() => ({ items: [] as AgentVO.Memory[] })),
|
||||||
|
]);
|
||||||
|
llmForm.value = {
|
||||||
|
baseUrl: s.baseUrl || '',
|
||||||
|
model: s.model || '',
|
||||||
|
apiKey: '',
|
||||||
|
apiKeyMasked: s.apiKeyMasked || null,
|
||||||
|
configured: !!s.configured,
|
||||||
|
};
|
||||||
|
memories.value = mem.items || [];
|
||||||
|
} catch (e: any) {
|
||||||
|
message.error(e?.message || '加载模型配置失败');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function removeMemory(id: string) {
|
||||||
|
try {
|
||||||
|
await deleteAgentMemoryApi(id);
|
||||||
|
memories.value = memories.value.filter((m) => m.id !== id);
|
||||||
|
message.success('已删除记忆');
|
||||||
|
} catch (e: any) {
|
||||||
|
message.error(e?.message || '删除失败');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function saveSettings() {
|
||||||
|
if (!llmForm.value.baseUrl.trim() || !llmForm.value.model.trim()) {
|
||||||
|
message.warning('请填写 Base URL 与模型名');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
savingSettings.value = true;
|
||||||
|
try {
|
||||||
|
const s = await updateAgentLlmSettingsApi({
|
||||||
|
baseUrl: llmForm.value.baseUrl.trim(),
|
||||||
|
model: llmForm.value.model.trim(),
|
||||||
|
apiKey: llmForm.value.apiKey.trim() || undefined,
|
||||||
|
});
|
||||||
|
llmForm.value.configured = s.configured;
|
||||||
|
llmForm.value.apiKeyMasked = s.apiKeyMasked || null;
|
||||||
|
llmForm.value.apiKey = '';
|
||||||
|
message.success('模型配置已保存');
|
||||||
|
settingsOpen.value = false;
|
||||||
|
} catch (e: any) {
|
||||||
|
message.error(e?.message || '保存失败');
|
||||||
|
} finally {
|
||||||
|
savingSettings.value = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function appendStreamToken(t: string) {
|
||||||
|
streamingText.value += t;
|
||||||
|
const idx = messages.value.length - 1;
|
||||||
|
const last = messages.value[idx];
|
||||||
|
if (last?.role === 'assistant') {
|
||||||
|
messages.value[idx] = { ...last, content: streamingText.value };
|
||||||
|
}
|
||||||
|
void nextTick().then(scrollToBottom);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function send() {
|
||||||
|
const text = draft.value.trim();
|
||||||
|
if (!text || sending.value) return;
|
||||||
|
if (!activeThreadId.value) {
|
||||||
|
await createSession();
|
||||||
|
}
|
||||||
|
const threadId = activeThreadId.value;
|
||||||
|
if (!threadId) return;
|
||||||
|
|
||||||
|
messagesLoadSeq += 1;
|
||||||
|
loadingMessages.value = false;
|
||||||
|
sending.value = true;
|
||||||
|
streamingText.value = '';
|
||||||
|
draft.value = '';
|
||||||
|
messages.value.push({
|
||||||
|
seq: (messages.value.at(-1)?.seq || 0) + 1,
|
||||||
|
role: 'user',
|
||||||
|
content: text,
|
||||||
|
});
|
||||||
|
messages.value.push({
|
||||||
|
seq: (messages.value.at(-1)?.seq || 0) + 1,
|
||||||
|
role: 'assistant',
|
||||||
|
content: '',
|
||||||
|
});
|
||||||
|
await nextTick();
|
||||||
|
scrollToBottom();
|
||||||
|
|
||||||
|
abort?.abort();
|
||||||
|
abort = streamAgentChat({
|
||||||
|
threadId,
|
||||||
|
content: text,
|
||||||
|
onToken: appendStreamToken,
|
||||||
|
onDone: () => {
|
||||||
|
const finalText = streamingText.value;
|
||||||
|
const idx = messages.value.length - 1;
|
||||||
|
const last = messages.value[idx];
|
||||||
|
if (last?.role === 'assistant') {
|
||||||
|
messages.value[idx] = { ...last, content: finalText || last.content };
|
||||||
|
}
|
||||||
|
sending.value = false;
|
||||||
|
streamingText.value = '';
|
||||||
|
void refreshSessions();
|
||||||
|
},
|
||||||
|
onError: (msg) => {
|
||||||
|
sending.value = false;
|
||||||
|
const idx = messages.value.length - 1;
|
||||||
|
const last = messages.value[idx];
|
||||||
|
if (last?.role === 'assistant' && !last.content && !streamingText.value) {
|
||||||
|
messages.value[idx] = { ...last, content: `错误:${msg}` };
|
||||||
|
}
|
||||||
|
streamingText.value = '';
|
||||||
|
message.error(msg);
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
onBeforeUnmount(() => abort?.abort());
|
||||||
|
|
||||||
|
void refreshSessions();
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<Page auto-content-height content-class="!p-0">
|
||||||
|
<div class="flex h-full min-h-0 w-full overflow-hidden">
|
||||||
|
<aside
|
||||||
|
class="flex w-64 shrink-0 flex-col border-r border-border bg-card"
|
||||||
|
>
|
||||||
|
<div class="flex items-center gap-2 border-b border-border p-3">
|
||||||
|
<Button type="primary" block @click="createSession">新对话</Button>
|
||||||
|
</div>
|
||||||
|
<div class="min-h-0 flex-1 overflow-y-auto p-2">
|
||||||
|
<div
|
||||||
|
v-if="loadingSessions"
|
||||||
|
class="text-muted-foreground py-6 text-center text-sm"
|
||||||
|
>
|
||||||
|
加载中…
|
||||||
|
</div>
|
||||||
|
<template v-else>
|
||||||
|
<button
|
||||||
|
v-for="s in sessions"
|
||||||
|
:key="s.threadId"
|
||||||
|
type="button"
|
||||||
|
class="mb-1 w-full rounded-md px-3 py-2 text-left text-sm transition-colors"
|
||||||
|
:class="
|
||||||
|
s.threadId === activeThreadId
|
||||||
|
? 'bg-primary/10 text-primary'
|
||||||
|
: 'hover:bg-muted'
|
||||||
|
"
|
||||||
|
@click="activeThreadId = s.threadId"
|
||||||
|
>
|
||||||
|
<div class="truncate font-medium">{{ s.title }}</div>
|
||||||
|
<div class="text-muted-foreground mt-0.5 truncate text-xs">
|
||||||
|
{{ s.updatedAt || '' }}
|
||||||
|
</div>
|
||||||
|
</button>
|
||||||
|
<Empty
|
||||||
|
v-if="sessions.length === 0"
|
||||||
|
class="mt-8"
|
||||||
|
description="暂无会话"
|
||||||
|
/>
|
||||||
|
</template>
|
||||||
|
</div>
|
||||||
|
<div class="border-t border-border p-3">
|
||||||
|
<Button block @click="openSettings">模型 API 设置</Button>
|
||||||
|
</div>
|
||||||
|
</aside>
|
||||||
|
|
||||||
|
<section class="flex min-h-0 min-w-0 flex-1 flex-col">
|
||||||
|
<header
|
||||||
|
class="flex h-12 shrink-0 items-center border-b border-border px-4"
|
||||||
|
>
|
||||||
|
<span class="truncate font-medium">
|
||||||
|
{{ activeSession?.title || '智能助手' }}
|
||||||
|
</span>
|
||||||
|
</header>
|
||||||
|
<div
|
||||||
|
ref="messagePaneRef"
|
||||||
|
class="relative min-h-0 flex-1 space-y-3 overflow-y-auto px-4 py-4"
|
||||||
|
>
|
||||||
|
<div
|
||||||
|
v-if="showMessageLoading"
|
||||||
|
class="text-muted-foreground py-6 text-center text-sm"
|
||||||
|
>
|
||||||
|
加载消息…
|
||||||
|
</div>
|
||||||
|
<Empty
|
||||||
|
v-else-if="messages.length === 0"
|
||||||
|
description="开始提问吧(需先配置公司模型 API)"
|
||||||
|
/>
|
||||||
|
<div
|
||||||
|
v-for="(m, idx) in messages"
|
||||||
|
:key="`${m.seq}-${idx}`"
|
||||||
|
class="flex"
|
||||||
|
:class="m.role === 'user' ? 'justify-end' : 'justify-start'"
|
||||||
|
>
|
||||||
|
<div
|
||||||
|
class="agent-md max-w-[75%] rounded-2xl px-3 py-2 text-sm leading-relaxed"
|
||||||
|
:class="
|
||||||
|
m.role === 'user'
|
||||||
|
? 'bg-primary text-primary-foreground whitespace-pre-wrap'
|
||||||
|
: 'bg-muted text-foreground'
|
||||||
|
"
|
||||||
|
v-html="bubbleHtml(m, idx)"
|
||||||
|
></div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<footer class="shrink-0 border-t border-border p-3">
|
||||||
|
<div class="flex gap-2">
|
||||||
|
<Textarea
|
||||||
|
v-model:value="draft"
|
||||||
|
:rows="2"
|
||||||
|
:disabled="sending"
|
||||||
|
placeholder="输入问题,Enter 发送(Shift+Enter 换行)"
|
||||||
|
class="flex-1"
|
||||||
|
@keydown.enter.exact.prevent="send"
|
||||||
|
/>
|
||||||
|
<Button type="primary" :loading="sending" @click="send">
|
||||||
|
发送
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</footer>
|
||||||
|
</section>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<Modal
|
||||||
|
v-model:open="settingsOpen"
|
||||||
|
title="公司模型 API(OpenAI Compatible)"
|
||||||
|
:confirm-loading="savingSettings"
|
||||||
|
ok-text="保存"
|
||||||
|
destroy-on-close
|
||||||
|
@ok="saveSettings"
|
||||||
|
>
|
||||||
|
<p class="text-muted-foreground mb-3 text-sm">
|
||||||
|
各租户自行填写 Base URL、API Key 与模型名。Key
|
||||||
|
加密落库(MySQL),Agent 经内部接口/Redis 注入;界面仅显示掩码。
|
||||||
|
</p>
|
||||||
|
<Form layout="vertical">
|
||||||
|
<FormItem label="Base URL" required>
|
||||||
|
<Input
|
||||||
|
v-model:value="llmForm.baseUrl"
|
||||||
|
placeholder="https://api.deepseek.com/v1"
|
||||||
|
/>
|
||||||
|
</FormItem>
|
||||||
|
<FormItem label="Model" required>
|
||||||
|
<Input v-model:value="llmForm.model" placeholder="deepseek-chat" />
|
||||||
|
</FormItem>
|
||||||
|
<FormItem
|
||||||
|
:label="
|
||||||
|
llmForm.configured
|
||||||
|
? `API Key(已配置 ${llmForm.apiKeyMasked || '****'},留空则不修改)`
|
||||||
|
: 'API Key'
|
||||||
|
"
|
||||||
|
:required="!llmForm.configured"
|
||||||
|
>
|
||||||
|
<InputPassword
|
||||||
|
v-model:value="llmForm.apiKey"
|
||||||
|
placeholder="sk-..."
|
||||||
|
/>
|
||||||
|
</FormItem>
|
||||||
|
</Form>
|
||||||
|
<div class="mt-4 border-t border-border pt-3">
|
||||||
|
<div class="mb-2 text-sm font-medium">我的记忆</div>
|
||||||
|
<p class="text-muted-foreground mb-2 text-xs">
|
||||||
|
对话中发送「记住:…」可写入;助手会注入最近条目。
|
||||||
|
</p>
|
||||||
|
<div v-if="memories.length === 0" class="text-muted-foreground text-xs">
|
||||||
|
暂无记忆
|
||||||
|
</div>
|
||||||
|
<div
|
||||||
|
v-for="m in memories"
|
||||||
|
:key="m.id"
|
||||||
|
class="mb-1 flex items-start gap-2 rounded-md bg-muted/50 px-2 py-1.5 text-xs"
|
||||||
|
>
|
||||||
|
<span class="min-w-0 flex-1 break-words">{{ m.text }}</span>
|
||||||
|
<Button type="link" size="small" danger @click="removeMemory(m.id)">
|
||||||
|
删
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</Modal>
|
||||||
|
</Page>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.agent-md :deep(p) {
|
||||||
|
margin: 0.35em 0;
|
||||||
|
}
|
||||||
|
.agent-md :deep(p:first-child) {
|
||||||
|
margin-top: 0;
|
||||||
|
}
|
||||||
|
.agent-md :deep(p:last-child) {
|
||||||
|
margin-bottom: 0;
|
||||||
|
}
|
||||||
|
.agent-md :deep(ul),
|
||||||
|
.agent-md :deep(ol) {
|
||||||
|
margin: 0.35em 0;
|
||||||
|
padding-left: 1.25em;
|
||||||
|
}
|
||||||
|
.agent-md :deep(pre) {
|
||||||
|
margin: 0.5em 0;
|
||||||
|
overflow-x: auto;
|
||||||
|
border-radius: 0.5rem;
|
||||||
|
background: rgba(0, 0, 0, 0.06);
|
||||||
|
padding: 0.6em 0.75em;
|
||||||
|
font-size: 0.85em;
|
||||||
|
}
|
||||||
|
.agent-md :deep(code) {
|
||||||
|
font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
|
||||||
|
font-size: 0.9em;
|
||||||
|
}
|
||||||
|
.agent-md :deep(:not(pre) > code) {
|
||||||
|
border-radius: 0.25rem;
|
||||||
|
background: rgba(0, 0, 0, 0.06);
|
||||||
|
padding: 0.1em 0.35em;
|
||||||
|
}
|
||||||
|
.agent-md :deep(a) {
|
||||||
|
text-decoration: underline;
|
||||||
|
}
|
||||||
|
.agent-md :deep(blockquote) {
|
||||||
|
margin: 0.4em 0;
|
||||||
|
border-left: 3px solid rgba(0, 0, 0, 0.2);
|
||||||
|
padding-left: 0.75em;
|
||||||
|
opacity: 0.9;
|
||||||
|
}
|
||||||
|
.agent-md :deep(table) {
|
||||||
|
margin: 0.5em 0;
|
||||||
|
border-collapse: collapse;
|
||||||
|
font-size: 0.9em;
|
||||||
|
}
|
||||||
|
.agent-md :deep(th),
|
||||||
|
.agent-md :deep(td) {
|
||||||
|
border: 1px solid rgba(0, 0, 0, 0.12);
|
||||||
|
padding: 0.25em 0.5em;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
/** 轻量 Markdown → 安全 HTML(流式场景下未闭合围栏也能尽量渲染)。 */
|
||||||
|
import DOMPurify from 'dompurify';
|
||||||
|
import { marked } from 'marked';
|
||||||
|
|
||||||
|
marked.setOptions({
|
||||||
|
gfm: true,
|
||||||
|
breaks: true,
|
||||||
|
});
|
||||||
|
|
||||||
|
export function renderAgentMarkdown(source: string): string {
|
||||||
|
const raw = source || '';
|
||||||
|
if (!raw.trim()) return '';
|
||||||
|
try {
|
||||||
|
const html = marked.parse(raw, { async: false }) as string;
|
||||||
|
return DOMPurify.sanitize(html, {
|
||||||
|
USE_PROFILES: { html: true },
|
||||||
|
});
|
||||||
|
} catch {
|
||||||
|
return DOMPurify.sanitize(raw.replace(/</g, '<').replace(/>/g, '>'));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
import { defineConfig } from '@vben/vite-config';
|
import { defineConfig } from '@vben/vite-config';
|
||||||
|
|
||||||
/** 开发环境 SSE 经 Vite 代理时禁止缓冲,否则只有首包 message+ping 后续心跳到不了浏览器 */
|
/** 开发环境 SSE 经 Vite 代理时禁止缓冲 */
|
||||||
function configureSseFriendlyProxy(proxyServer: {
|
function configureSseFriendlyProxy(proxyServer: {
|
||||||
on: (
|
on: (
|
||||||
event: 'proxyReq' | 'proxyRes',
|
event: 'proxyReq' | 'proxyRes',
|
||||||
@@ -8,15 +8,18 @@ function configureSseFriendlyProxy(proxyServer: {
|
|||||||
) => void;
|
) => void;
|
||||||
}) {
|
}) {
|
||||||
proxyServer.on('proxyReq', (proxyReq, req) => {
|
proxyServer.on('proxyReq', (proxyReq, req) => {
|
||||||
if (req.url?.includes('/notify/sse/')) {
|
const url = req.url || '';
|
||||||
|
if (url.includes('/notify/sse/') || url.includes('/agent/sessions/')) {
|
||||||
proxyReq.setHeader('Accept', 'text/event-stream');
|
proxyReq.setHeader('Accept', 'text/event-stream');
|
||||||
proxyReq.setHeader('Cache-Control', 'no-cache');
|
proxyReq.setHeader('Cache-Control', 'no-cache');
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
proxyServer.on('proxyRes', (proxyRes, req, res) => {
|
proxyServer.on('proxyRes', (proxyRes, req, res) => {
|
||||||
const contentType = proxyRes.headers['content-type'];
|
const contentType = proxyRes.headers['content-type'];
|
||||||
|
const url = req.url || '';
|
||||||
if (
|
if (
|
||||||
req.url?.includes('/notify/sse/') ||
|
url.includes('/notify/sse/') ||
|
||||||
|
url.includes('/chat') ||
|
||||||
(typeof contentType === 'string' &&
|
(typeof contentType === 'string' &&
|
||||||
contentType.includes('text/event-stream'))
|
contentType.includes('text/event-stream'))
|
||||||
) {
|
) {
|
||||||
@@ -38,6 +41,14 @@ export default defineConfig(async () => {
|
|||||||
vite: {
|
vite: {
|
||||||
server: {
|
server: {
|
||||||
proxy: {
|
proxy: {
|
||||||
|
// Agent 服务(须写在通用 /api 之前)
|
||||||
|
'/api/agent': {
|
||||||
|
changeOrigin: true,
|
||||||
|
target: 'http://localhost:8200',
|
||||||
|
timeout: 0,
|
||||||
|
proxyTimeout: 0,
|
||||||
|
configure: configureSseFriendlyProxy,
|
||||||
|
},
|
||||||
'/api': {
|
'/api': {
|
||||||
changeOrigin: true,
|
changeOrigin: true,
|
||||||
// 后端服务地址
|
// 后端服务地址
|
||||||
|
|||||||
Generated
+42
@@ -656,6 +656,12 @@ importers:
|
|||||||
dayjs:
|
dayjs:
|
||||||
specifier: 'catalog:'
|
specifier: 'catalog:'
|
||||||
version: 1.11.13
|
version: 1.11.13
|
||||||
|
dompurify:
|
||||||
|
specifier: ^3.4.15
|
||||||
|
version: 3.4.15
|
||||||
|
marked:
|
||||||
|
specifier: ^18.0.13
|
||||||
|
version: 18.0.13
|
||||||
papaparse:
|
papaparse:
|
||||||
specifier: ^5.4.1
|
specifier: ^5.4.1
|
||||||
version: 5.5.3
|
version: 5.5.3
|
||||||
@@ -675,6 +681,12 @@ importers:
|
|||||||
specifier: ^3.0.0
|
specifier: ^3.0.0
|
||||||
version: 3.0.0
|
version: 3.0.0
|
||||||
devDependencies:
|
devDependencies:
|
||||||
|
'@types/dompurify':
|
||||||
|
specifier: ^3.2.0
|
||||||
|
version: 3.2.0
|
||||||
|
'@types/marked':
|
||||||
|
specifier: ^6.0.0
|
||||||
|
version: 6.0.0
|
||||||
'@types/papaparse':
|
'@types/papaparse':
|
||||||
specifier: ^5.3.14
|
specifier: ^5.3.14
|
||||||
version: 5.3.16
|
version: 5.3.16
|
||||||
@@ -3988,6 +4000,10 @@ packages:
|
|||||||
'@types/deep-eql@4.0.2':
|
'@types/deep-eql@4.0.2':
|
||||||
resolution: {integrity: sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==}
|
resolution: {integrity: sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==}
|
||||||
|
|
||||||
|
'@types/dompurify@3.2.0':
|
||||||
|
resolution: {integrity: sha512-Fgg31wv9QbLDA0SpTOXO3MaxySc4DKGLi8sna4/Utjo4r3ZRPdCt4UQee8BWr+Q5z21yifghREPJGYaEOEIACg==}
|
||||||
|
deprecated: This is a stub types definition. dompurify provides its own type definitions, so you do not need this installed.
|
||||||
|
|
||||||
'@types/eslint@9.6.1':
|
'@types/eslint@9.6.1':
|
||||||
resolution: {integrity: sha512-FXx2pKgId/WyYo2jXw63kk7/+TY7u7AziEJxJAnSFzHlqTAS3Ync6SvgYAN/k4/PQpnnVuzoMuVnByKK2qp0ag==}
|
resolution: {integrity: sha512-FXx2pKgId/WyYo2jXw63kk7/+TY7u7AziEJxJAnSFzHlqTAS3Ync6SvgYAN/k4/PQpnnVuzoMuVnByKK2qp0ag==}
|
||||||
|
|
||||||
@@ -4021,6 +4037,10 @@ packages:
|
|||||||
'@types/lodash@4.17.16':
|
'@types/lodash@4.17.16':
|
||||||
resolution: {integrity: sha512-HX7Em5NYQAXKW+1T+FiuG27NGwzJfCX3s1GjOa7ujxZa52kjJLOr4FUxT+giF6Tgxv1e+/czV/iTtBw27WTU9g==}
|
resolution: {integrity: sha512-HX7Em5NYQAXKW+1T+FiuG27NGwzJfCX3s1GjOa7ujxZa52kjJLOr4FUxT+giF6Tgxv1e+/czV/iTtBw27WTU9g==}
|
||||||
|
|
||||||
|
'@types/marked@6.0.0':
|
||||||
|
resolution: {integrity: sha512-jmjpa4BwUsmhxcfsgUit/7A9KbrC48Q0q8KvnY107ogcjGgTFDlIL3RpihNpx2Mu1hM4mdFQjoVc4O6JoGKHsA==}
|
||||||
|
deprecated: This is a stub types definition. marked provides its own type definitions, so you do not need this installed.
|
||||||
|
|
||||||
'@types/minimatch@3.0.5':
|
'@types/minimatch@3.0.5':
|
||||||
resolution: {integrity: sha512-Klz949h02Gz2uZCMGwDUSDS1YBlTdDDgbWHi+81l29tQALUtvz4rAYi5uoVhE5Lagoq6DeqAUlbrHvW/mXDgdQ==}
|
resolution: {integrity: sha512-Klz949h02Gz2uZCMGwDUSDS1YBlTdDDgbWHi+81l29tQALUtvz4rAYi5uoVhE5Lagoq6DeqAUlbrHvW/mXDgdQ==}
|
||||||
|
|
||||||
@@ -5638,6 +5658,9 @@ packages:
|
|||||||
resolution: {integrity: sha512-cgwlv/1iFQiFnU96XXgROh8xTeetsnJiDsTc7TYCLFd9+/WNkIqPTxiM/8pSd8VIrhXGTf1Ny1q1hquVqDJB5w==}
|
resolution: {integrity: sha512-cgwlv/1iFQiFnU96XXgROh8xTeetsnJiDsTc7TYCLFd9+/WNkIqPTxiM/8pSd8VIrhXGTf1Ny1q1hquVqDJB5w==}
|
||||||
engines: {node: '>= 4'}
|
engines: {node: '>= 4'}
|
||||||
|
|
||||||
|
dompurify@3.4.15:
|
||||||
|
resolution: {integrity: sha512-EUBjM+B+lkDE41iE82DDSCfkoPGfXx8IxFxPMjNzm/Uk4xDet77rTN9wqlxlVg71kK7XGuUMv6wUxJUwwv+Xyw==}
|
||||||
|
|
||||||
domutils@2.8.0:
|
domutils@2.8.0:
|
||||||
resolution: {integrity: sha512-w96Cjofp72M5IIhpjgobBimYEfoPjx1Vx0BSX9P30WBdZW2WIKU0T1Bd0kz2eNZ9ikjKgHbEyKx8BB6H1L3h3A==}
|
resolution: {integrity: sha512-w96Cjofp72M5IIhpjgobBimYEfoPjx1Vx0BSX9P30WBdZW2WIKU0T1Bd0kz2eNZ9ikjKgHbEyKx8BB6H1L3h3A==}
|
||||||
|
|
||||||
@@ -7365,6 +7388,11 @@ packages:
|
|||||||
resolution: {integrity: sha512-EsS89h6l4vbfJEtBZnENTOFk8mCRpY5ru36Xe5bcX1KYIli2mkSHqoFsp5O1wMDvTJJzxe/4THpCTtygjeeGWQ==}
|
resolution: {integrity: sha512-EsS89h6l4vbfJEtBZnENTOFk8mCRpY5ru36Xe5bcX1KYIli2mkSHqoFsp5O1wMDvTJJzxe/4THpCTtygjeeGWQ==}
|
||||||
engines: {node: '>= 10'}
|
engines: {node: '>= 10'}
|
||||||
|
|
||||||
|
marked@18.0.13:
|
||||||
|
resolution: {integrity: sha512-xTxVzZsBFwunP6HDmtBkabUQEYArnP7/rMDGmPj9SlrKlQ4i8MdYVow+nJL0eOqwpUqhzBoTBRADGN6uYwPyOw==}
|
||||||
|
engines: {node: '>= 20'}
|
||||||
|
hasBin: true
|
||||||
|
|
||||||
math-intrinsics@1.1.0:
|
math-intrinsics@1.1.0:
|
||||||
resolution: {integrity: sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==}
|
resolution: {integrity: sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==}
|
||||||
engines: {node: '>= 0.4'}
|
engines: {node: '>= 0.4'}
|
||||||
@@ -12946,6 +12974,10 @@ snapshots:
|
|||||||
|
|
||||||
'@types/deep-eql@4.0.2': {}
|
'@types/deep-eql@4.0.2': {}
|
||||||
|
|
||||||
|
'@types/dompurify@3.2.0':
|
||||||
|
dependencies:
|
||||||
|
dompurify: 3.4.15
|
||||||
|
|
||||||
'@types/eslint@9.6.1':
|
'@types/eslint@9.6.1':
|
||||||
dependencies:
|
dependencies:
|
||||||
'@types/estree': 1.0.8
|
'@types/estree': 1.0.8
|
||||||
@@ -12979,6 +13011,10 @@ snapshots:
|
|||||||
|
|
||||||
'@types/lodash@4.17.16': {}
|
'@types/lodash@4.17.16': {}
|
||||||
|
|
||||||
|
'@types/marked@6.0.0':
|
||||||
|
dependencies:
|
||||||
|
marked: 18.0.13
|
||||||
|
|
||||||
'@types/minimatch@3.0.5': {}
|
'@types/minimatch@3.0.5': {}
|
||||||
|
|
||||||
'@types/node@12.20.55': {}
|
'@types/node@12.20.55': {}
|
||||||
@@ -14806,6 +14842,10 @@ snapshots:
|
|||||||
dependencies:
|
dependencies:
|
||||||
domelementtype: 2.3.0
|
domelementtype: 2.3.0
|
||||||
|
|
||||||
|
dompurify@3.4.15:
|
||||||
|
optionalDependencies:
|
||||||
|
'@types/trusted-types': 2.0.7
|
||||||
|
|
||||||
domutils@2.8.0:
|
domutils@2.8.0:
|
||||||
dependencies:
|
dependencies:
|
||||||
dom-serializer: 1.4.1
|
dom-serializer: 1.4.1
|
||||||
@@ -16662,6 +16702,8 @@ snapshots:
|
|||||||
- bluebird
|
- bluebird
|
||||||
- supports-color
|
- supports-color
|
||||||
|
|
||||||
|
marked@18.0.13: {}
|
||||||
|
|
||||||
math-intrinsics@1.1.0: {}
|
math-intrinsics@1.1.0: {}
|
||||||
|
|
||||||
mathml-tag-names@2.1.3: {}
|
mathml-tag-names@2.1.3: {}
|
||||||
|
|||||||
Reference in New Issue
Block a user