diff --git a/(红头)项目核心文档汇总.md b/(红头)项目核心文档汇总.md index a9123bd..f67ff89 100644 --- a/(红头)项目核心文档汇总.md +++ b/(红头)项目核心文档汇总.md @@ -185,6 +185,21 @@ - **route** — Router Agent 分析问题,分发到最匹配的 Specialist Agent - **sequential** — Agent 流水线执行,前者输出作为后者输入 - **debate** — 多个 Agent 独立回答,Aggregator 汇总为最终答案 +- **自主学习**:Agent 从历史执行中自动优化工具选择策略,基于 AgentLearningPattern 模型记录和累计工具使用模式,执行前注入历史模式到 system prompt + +### 11. Agent 定时任务系统 +- **cron 调度**:支持标准 cron 表达式,按周期自动触发 Agent 执行 +- **Celery Beat 集成**:每分钟检查到期任务,到期自动触发 +- **执行管理**:支持手动触发、暂停/恢复、执行状态跟踪 +- **飞书推送**:定时任务执行结果自动推送到飞书(Webhook + 应用消息) + +### 12. 飞书集成和通知系统 +- **通知系统**:统一的通知管理(notifications 表、通知服务、API) +- **飞书定时任务推送**:定时任务执行结果自动推送飞书 +- **飞书应用消息**:通过飞书应用 API 发送消息通知 +- **飞书账号绑定**:用户可绑定飞书账号,接收个性化通知 +- **橙子飞书机器人**:独立 WebSocket 连接的飞书机器人,固定路由到橙子助手 Agent +- **飞书事件监听**:WebSocket 长连接监听飞书 IM 事件 ## 项目结构 @@ -209,18 +224,37 @@ aiagent/ │ │ │ ├── context.py # 会话上下文(消息历史、迭代追踪) │ │ │ ├── memory.py # 分层记忆管理器 + LLM 自动压缩总结 │ │ │ ├── tool_manager.py# 工具管理器(包装 ToolRegistry) -│ │ │ ├── core.py # AgentRuntime 主循环(ReAct 核心) -│ │ │ ├── orchestrator.py# 多 Agent 编排引擎(route/sequential/debate) +│ │ │ ├── core.py # AgentRuntime 主循环(ReAct 核心)+ 自主学习集成 +│ │ │ ├── orchestrator.py# 多 Agent 编排引擎(route/sequential/debate/pipeline) │ │ │ └── workflow_integration.py # 工作流桥接 │ │ ├── api/ # API路由 -│ │ │ ├── agent_chat.py # Agent 聊天 + 多 Agent 编排 + LLM 调用日志(新增) -│ │ │ └── agent_monitoring.py # Agent 监控 API 5 个端点(新增) +│ │ │ ├── agent_chat.py # Agent 聊天 + 多 Agent 编排 + LLM 调用日志 + SSE 流式 +│ │ │ ├── agent_monitoring.py # Agent 监控 API 5 个端点 +│ │ │ ├── agent_schedules.py # Agent 定时任务 CRUD API + 手动触发 +│ │ │ ├── feishu_bind.py # 飞书账号绑定/解绑 API +│ │ │ └── notifications.py # 通知系统 API │ │ ├── core/ # 核心模块 │ │ ├── models/ # 数据库模型 -│ │ │ └── agent_llm_log.py # Agent LLM 调用日志模型(新增) +│ │ │ ├── agent_llm_log.py # Agent LLM 调用日志模型 +│ │ │ ├── agent_learning_pattern.py # Agent 学习模式模型(自主学习) +│ │ │ ├── agent_schedule.py # Agent 定时任务调度模型 +│ │ │ ├── notification.py # 通知模型 +│ │ │ └── agent_vector_memory.py # Agent 向量记忆表模型 │ │ ├── schemas/ # Pydantic模式 │ │ ├── services/ # 业务逻辑 -│ │ │ └── agent_monitoring_service.py # Agent 监控服务(新增) +│ │ │ ├── agent_monitoring_service.py # Agent 监控服务 +│ │ │ ├── agent_learning_service.py # 自主学习服务(工具选择优化) +│ │ │ ├── agent_schedule_service.py # 定时任务调度服务 +│ │ │ ├── notification_service.py # 通知服务 +│ │ │ ├── feishu_app_service.py # 飞书应用消息发送 +│ │ │ ├── feishu_notifier.py # 飞书通知器 +│ │ │ ├── feishu_ws_handler.py # 飞书 WebSocket 事件处理 +│ │ │ ├── orange_app_service.py # 橙子飞书机器人服务 +│ │ │ ├── orange_ws_handler.py # 橙子机器人 WS 处理 +│ │ │ ├── knowledge_service.py # 知识库 RAG 服务 +│ │ │ ├── embedding_service.py # Embedding 生成服务 +│ │ │ ├── document_parser.py # 文档解析器 +│ │ │ └── text_chunker.py # 文本分块器 │ │ └── main.py # 应用入口 │ ├── alembic/ # 数据库迁移 │ ├── tests/ # 测试 @@ -464,7 +498,14 @@ alembic downgrade -1 - **自主 Agent Runtime**: 100% ✅(2026-04 新增) - **多 Agent 编排**: 100% ✅(2026-05 新增) - **Agent 监控 Dashboard**: 100% ✅(2026-05 新增) -- **整体项目**: 约 97-98% +- **SSE 流式输出**: 100% ✅(2026-05 新增) +- **向量记忆 + 知识库 RAG**: 100% ✅(2026-05 新增) +- **工具市场**: 100% ✅(2026-05 新增) +- **工作流预算接入**: 100% ✅(2026-05 新增) +- **Agent 自主学习**: 100% ✅(2026-05 新增) +- **Agent 定时任务系统**: 100% ✅(2026-05 新增) +- **飞书通知与机器人对话**: 100% ✅(2026-05 新增) +- **整体项目**: 约 99.9% ### 已完成核心功能 1. **完整的用户认证系统** - 注册、登录、JWT认证 @@ -485,23 +526,20 @@ alembic downgrade -1 16. **Agent 配置页面** - AgentConfig.vue 可视化编辑 System Prompt / 模型 / Temperature / 工具 17. **多 Agent 编排** - AgentOrchestrator 三种模式(route/sequential/debate),前端编排 UI 支持模式切换和动态 Agent 编辑 18. **Agent 监控 Dashboard** - 实时 LLM 调用埋点(AgentLLMLog 表)、Agent 用量排行、Token 统计、工具调用频次、日趋势图 +19. **SSE 流式输出** - Agent 思考过程实时推送到前端 +20. **向量记忆** - Embedding API + 余弦相似度 Top-K 语义检索 +21. **知识库 RAG** - 文件上传 → 5 种格式解析 → 分块 → 向量化 → 检索增强 +22. **工具市场** - HTTP/Code 工具 CRUD + 沙箱测试 + 分类浏览 +23. **工作流预算接入** - Agent LLM/工具调用计入 WorkflowEngine 全局预算 +24. **Agent 自主学习** - 从历史执行中自动优化工具选择策略(AgentLearningPattern) +25. **Agent 定时任务系统** - cron 表达式定时触发 Agent 执行,集成 Celery Beat +26. **飞书通知与机器人对话** - 通知系统、飞书定时任务推送、橙子飞书机器人 -### 近期开发重点(高优先级) -1. **预算接入** - Agent 内部 LLM 调用计入工作流执行预算 -2. **用户体验优化** - 工作流编辑器优化、Agent使用体验优化 -3. **流式输出** - Agent 思考过程实时推送到前端 - -### 中期规划 -1. **向量记忆** - 集成 Embedding API + 向量检索(语义记忆) -2. **流式输出** - Agent 思考过程实时推送到前端 -3. **知识库 RAG** - 文件上传 → 切片 → 向量化 → 检索增强生成 -4. **工具市场** - 用户可上传自定义工具定义 - -### 长期规划 -1. **自主学习** - Agent 从历史执行中自动优化工具选择策略 -2. **多租户支持** - 租户模型、数据隔离、资源配额管理 -3. **插件系统** - 插件注册机制、自定义节点插件开发框架 -4. **性能优化** - 工作流执行性能优化、前端性能优化 +### 近期规划 +1. **多租户支持** - 租户模型、数据隔离、资源配额管理 +2. **插件系统** - 插件注册机制、自定义节点插件开发框架 +3. **性能优化** - 工作流执行性能优化、前端性能优化 +4. **用户体验优化** - 工作流编辑器优化、Agent使用体验优化 详细开发进度请参考:[开发进度.md](./开发进度.md) @@ -556,7 +594,7 @@ alembic downgrade -1 --- -**最后更新**: 2026-05-01 -**文档版本**: 1.6 +**最后更新**: 2026-05-02 +**文档版本**: 1.7 *本文档基于项目现有文档整理生成,涵盖项目核心信息。详细技术方案请参考[方案-优化版.md](./方案-优化版.md)。DeepSeek 模型名与 Base URL 以官方文档为准,变更时请同步修订本节。* \ No newline at end of file diff --git a/install_autostart.ps1 b/install_autostart.ps1 new file mode 100644 index 0000000..5f9a905 --- /dev/null +++ b/install_autostart.ps1 @@ -0,0 +1,74 @@ +# Install / uninstall AIAgent auto-start scheduled task +# Usage: +# powershell -ExecutionPolicy Bypass -File .\install_autostart.ps1 +# powershell -ExecutionPolicy Bypass -File .\install_autostart.ps1 -Uninstall + +param( + [switch]$Uninstall +) + +$ErrorActionPreference = "Stop" +$RepoRoot = Split-Path -Parent $MyInvocation.MyCommand.Path +$TaskName = "AIAgent-Startup" +$ScriptPath = Join-Path $RepoRoot "start_aiagent_background.ps1" + +if (-not (Test-Path $ScriptPath)) { + Write-Host "ERROR: $ScriptPath not found" -ForegroundColor Red + exit 1 +} + +if ($Uninstall) { + Write-Host "Uninstalling scheduled task: $TaskName ..." -ForegroundColor Yellow + Unregister-ScheduledTask -TaskName $TaskName -Confirm:$false -ErrorAction SilentlyContinue + Write-Host "[OK] Task '$TaskName' removed" -ForegroundColor Green + exit 0 +} + +# Remove old task if exists +Unregister-ScheduledTask -TaskName $TaskName -Confirm:$false -ErrorAction SilentlyContinue + +# Build action: run background start script +$argString = "-NoProfile -ExecutionPolicy Bypass -WindowStyle Hidden -File `"$ScriptPath`"" +$action = New-ScheduledTaskAction -Execute "powershell.exe" -Argument $argString + +# Build trigger: 30 seconds after system boot +$trigger = New-ScheduledTaskTrigger -AtStartup -RandomDelay (New-TimeSpan -Seconds 30) + +# Build settings +$settings = New-ScheduledTaskSettingsSet ` + -AllowStartIfOnBatteries ` + -DontStopIfGoingOnBatteries ` + -StartWhenAvailable ` + -RestartCount 3 ` + -RestartInterval (New-TimeSpan -Minutes 1) ` + -ExecutionTimeLimit (New-TimeSpan -Minutes 10) + +# Run as SYSTEM (no login required) +$principal = New-ScheduledTaskPrincipal -UserId "SYSTEM" -LogonType ServiceAccount -RunLevel Highest + +Register-ScheduledTask -TaskName $TaskName ` + -Trigger $trigger ` + -Action $action ` + -Settings $settings ` + -Principal $principal ` + -Description "AIAgent platform auto-start (Redis + API + Celery + Frontend)" ` + -Force + +Write-Host "" +Write-Host "==================================================" -ForegroundColor Green +Write-Host "[OK] Auto-start task installed" -ForegroundColor Green +Write-Host "==================================================" -ForegroundColor Green +Write-Host "" +Write-Host "Task name : $TaskName" +Write-Host "Trigger : At system startup (30s delay)" +Write-Host "Run as : SYSTEM (no login required)" +Write-Host "Logs : $RepoRoot\logs\" +Write-Host "" +Write-Host "Manual test (run now):" +Write-Host " Start-ScheduledTask -TaskName '$TaskName'" +Write-Host "" +Write-Host "Uninstall:" +Write-Host " powershell -ExecutionPolicy Bypass -File `"$($MyInvocation.MyCommand.Path)`" -Uninstall" +Write-Host "" +Write-Host "Verify in GUI:" +Write-Host " taskschd.msc -> 任务计划程序库 -> $TaskName" diff --git a/start_aiagent_background.ps1 b/start_aiagent_background.ps1 new file mode 100644 index 0000000..9976b59 --- /dev/null +++ b/start_aiagent_background.ps1 @@ -0,0 +1,99 @@ +# 静默后台启动脚本(无弹窗,日志写文件) +# 用于 Windows 任务计划程序开机自启 + +$ErrorActionPreference = "Continue" +$RepoRoot = Split-Path -Parent $MyInvocation.MyCommand.Path +$Backend = Join-Path $RepoRoot "backend" +$Frontend = Join-Path $RepoRoot "frontend" +$RedisDir = Join-Path $Backend "redis" +$RedisExe = Join-Path $RedisDir "redis-server.exe" +$RedisCli = Join-Path $RedisDir "redis-cli.exe" +$LogDir = Join-Path $RepoRoot "logs" +$LogFile = Join-Path $LogDir "autostart_$(Get-Date -Format 'yyyyMMdd_HHmmss').log" + +if (-not (Test-Path $LogDir)) { + New-Item -ItemType Directory -Path $LogDir -Force | Out-Null +} + +function Write-Log($msg) { + $ts = Get-Date -Format "yyyy-MM-dd HH:mm:ss" + "$ts $msg" | Out-File -Append -FilePath $LogFile -Encoding UTF8 +} + +Write-Log "========== AIAgent background start ==========" +Write-Log "Repo: $RepoRoot" + +# ── 1) Redis ────────────────────────────────── +$redisPort = 6379 +$redisListening = netstat -ano | Select-String ":$redisPort\s+.*LISTENING" +if ($redisListening) { + Write-Log "Redis already listening on $redisPort" +} else { + if (-not (Test-Path $RedisExe)) { + Write-Log "ERROR: Redis not found at $RedisExe" + } else { + Write-Log "Starting Redis on $redisPort ..." + $redisProc = Start-Process -FilePath $RedisExe ` + -ArgumentList "--port $redisPort" ` + -WorkingDirectory $RedisDir ` + -WindowStyle Hidden ` + -PassThru + Start-Sleep -Seconds 2 + if (Test-Path $RedisCli) { + & $RedisCli -p $redisPort ping 2>&1 | Out-File -Append $LogFile -Encoding UTF8 + } + Write-Log "Redis PID=$($redisProc.Id) started" + } +} + +# ── 2) Backend API ──────────────────────────── +$apiPort = 8037 +$apiListening = netstat -ano | Select-String ":$apiPort\s+.*LISTENING" +if ($apiListening) { + Write-Log "Backend API already listening on $apiPort" +} else { + Write-Log "Starting backend API on $apiPort ..." + $apiLog = Join-Path $LogDir "api.log" + Start-Process powershell ` + -WindowStyle Hidden ` + -ArgumentList @( + "-NoProfile", "-ExecutionPolicy", "Bypass", + "-Command", + "Set-Location '$Backend'; .\venv\Scripts\Activate.ps1; python -m uvicorn app.main:app --host 0.0.0.0 --port $apiPort 2>&1 | Out-File -Append '$apiLog' -Encoding UTF8" + ) + Write-Log "Backend API starting (log: $apiLog)" +} + +# ── 3) Celery Worker ────────────────────────── +Write-Log "Starting Celery worker ..." +$celeryLog = Join-Path $LogDir "celery.log" +Start-Process powershell ` + -WindowStyle Hidden ` + -ArgumentList @( + "-NoProfile", "-ExecutionPolicy", "Bypass", + "-Command", + "Set-Location '$Backend'; .\venv\Scripts\Activate.ps1; python -m celery -A app.core.celery_app worker --loglevel=info --pool=threads --concurrency=8 2>&1 | Out-File -Append '$celeryLog' -Encoding UTF8" + ) +Write-Log "Celery worker starting (log: $celeryLog)" + +# ── 4) Frontend (pnpm dev) ──────────────────── +$frontendPort = 3001 +$frontendListening = netstat -ano | Select-String ":$frontendPort\s+.*LISTENING" +if ($frontendListening) { + Write-Log "Frontend already listening on $frontendPort" +} else { + Write-Log "Starting frontend on $frontendPort ..." + $frontendLog = Join-Path $LogDir "frontend.log" + Start-Process powershell ` + -WindowStyle Hidden ` + -ArgumentList @( + "-NoProfile", "-ExecutionPolicy", "Bypass", + "-Command", + "`$env:AIAGENT_API_PROXY='http://127.0.0.1:$apiPort'; Set-Location '$Frontend'; pnpm dev --port $frontendPort 2>&1 | Out-File -Append '$frontendLog' -Encoding UTF8" + ) + Write-Log "Frontend starting (log: $frontendLog)" +} + +Write-Log "========== All services issued ==========" +Write-Log "Frontend: http://localhost:$frontendPort" +Write-Log "API docs: http://127.0.0.1:$apiPort/docs" diff --git a/stop_aiagent.ps1 b/stop_aiagent.ps1 index e96daad..792419d 100644 --- a/stop_aiagent.ps1 +++ b/stop_aiagent.ps1 @@ -2,35 +2,51 @@ $ErrorActionPreference = "SilentlyContinue" Write-Host "== AIAgent stop ==" -ForegroundColor Cyan -function Stop-ByCommandLine($pattern, $name) { - $targets = Get-CimInstance Win32_Process | Where-Object { - $_.CommandLine -and $_.CommandLine -match $pattern +function Get-PidsListeningOnPort([int]$Port) { + $pids = New-Object System.Collections.Generic.HashSet[int] + try { + netstat -ano | ForEach-Object { + $ln = $_.Trim() + if ($ln -notmatch "LISTENING") { return } + # 匹配 :8037 或 :3001 等端口后的 LISTENING 行末 PID + if ($ln -match ":$Port\s+.*LISTENING\s+(\d+)\s*$") { + [void]$pids.Add([int]$Matches[1]) + } + } + } catch { } + return @($pids) +} + +function Stop-OnPorts([int[]]$ports, [string]$name) { + $all = New-Object System.Collections.Generic.HashSet[int] + foreach ($p in $ports) { + foreach ($pid in (Get-PidsListeningOnPort $p)) { + [void]$all.Add($pid) + } } - if (-not $targets) { - Write-Host "[SKIP] ${name}: no matching process" -ForegroundColor DarkGray + if ($all.Count -eq 0) { + Write-Host "[SKIP] ${name}: no listener on ports $($ports -join ',')" -ForegroundColor DarkGray return } - foreach ($p in $targets) { + foreach ($pid in $all) { + if ($pid -le 4) { continue } try { - Stop-Process -Id $p.ProcessId -Force - Write-Host "[OK] stopped ${name} PID=$($p.ProcessId)" -ForegroundColor Green + Stop-Process -Id $pid -Force -ErrorAction SilentlyContinue + Write-Host "[OK] stopped ${name} PID=$pid" -ForegroundColor Green } catch { - Write-Host "[WARN] failed to stop ${name} PID=$($p.ProcessId)" -ForegroundColor Yellow + Write-Host "[WARN] failed to stop ${name} PID=$pid" -ForegroundColor Yellow } } } -# 1) 停后端 API(uvicorn app.main:app) -Stop-ByCommandLine "uvicorn\s+app\.main:app" "backend-api" +# 后端 API(8037 / 8041 备用) +Stop-OnPorts @(8037, 8041) "backend-api" -# 2) 停 Celery Worker -Stop-ByCommandLine "celery\s+-A\s+app\.core\.celery_app\s+worker" "celery-worker" +# 前端 Vite(3001) +Stop-OnPorts @(3001) "frontend-dev" -# 3) 停前端 dev(vite / pnpm dev / npm run dev) -Stop-ByCommandLine "vite(\.js)?\s|pnpm\s+dev|npm\s+run\s+dev" "frontend-dev" - -# 4) 停 Redis(优先匹配本项目 redis-server) -Stop-ByCommandLine "redis-server(\.exe)?(\s|$)" "redis" +# Redis(6379,仅当监听在本地开发端口时结束;若与其它项目共用请谨慎) +Stop-OnPorts @(6379) "redis" Start-Sleep -Milliseconds 600 diff --git a/自主AI Agent改造完成情况.md b/自主AI Agent改造完成情况.md index 1d21ad1..4b86b6e 100644 --- a/自主AI Agent改造完成情况.md +++ b/自主AI Agent改造完成情况.md @@ -10,7 +10,7 @@ ## 已完成改造 -### 新增文件(22 个) +### 新增文件 — 第一轮(22 个) | 文件 | 行数 | 用途 | |------|------|------| @@ -40,7 +40,27 @@ | `scripts/seed_agents.py` | 270 | 批量 Agent 种子脚本(创建 4 个常用自主 Agent) | | `scripts/test_coding_agent.py` | 150 | 编程助手自动化测试脚本(4 场景 × 2 端点 = 8 用例) | -### 修改文件(14 个) +### 新增文件 — 第二轮(2026-05-02 自主学习 + 定时任务 + 飞书集成) + +| 文件 | 行数 | 用途 | +|------|------|------| +| `backend/app/services/agent_learning_service.py` | 340 | **自主学习服务** — 任务分类、工具序列提取/合并、有效性评分、学习模式注入 | +| `backend/app/models/agent_learning_pattern.py` | 25 | Agent 学习模式模型(11 类任务 × 工具序列 × 频率/评分) | +| `backend/app/services/agent_schedule_service.py` | 140 | **Agent 定时任务调度服务** — cron 解析、到期触发、执行跟踪 | +| `backend/app/models/agent_schedule.py` | 28 | Agent 定时任务调度模型(cron 表达式、启用/禁用、执行记录) | +| `backend/app/api/agent_schedules.py` | 200 | Agent 定时任务 CRUD API + 手动触发端点 | +| `backend/app/tasks/scheduler_tasks.py` | 27 | Celery Beat 定时检查任务(每分钟扫描到期调度) | +| `backend/app/services/notification_service.py` | 128 | 通知系统服务(通知创建、查询、已读标记) | +| `backend/app/models/notification.py` | 24 | 通知模型 | +| `backend/app/api/notifications.py` | 115 | 通知系统 API | +| `backend/app/api/feishu_bind.py` | 243 | 飞书账号绑定/解绑 API(二维码 + 验证码) | +| `backend/app/services/feishu_app_service.py` | 199 | 飞书应用消息发送服务 | +| `backend/app/services/feishu_notifier.py` | 96 | 飞书通知器(Webhook + 应用消息推送) | +| `backend/app/services/feishu_ws_handler.py` | 351 | 飞书 WebSocket 长连接事件监听 | +| `backend/app/services/orange_app_service.py` | 137 | 橙子飞书机器人服务 | +| `backend/app/services/orange_ws_handler.py` | 298 | 橙子机器人 WebSocket 处理 + +### 修改文件 — 第二轮(14 个原文件 + 新增 8 个修改) | 文件 | 改动 | |------|------| @@ -140,21 +160,33 @@ AgentRuntime (新增) ### 新增代码行数统计 ``` -agent_runtime/ → 约 1250 行 Python(含 pipeline 模式约 100 行新增) -api/ → 约 660 行 Python -services → 约 880 行 Python -models → 约 140 行 Python -frontend → 约 640 行 Vue/TypeScript(含 pipeline 前端选项) -修改(非新增) → 约 250 行 Python/TS -───────────────────────────────────────── -总计新增 → 约 3570 行 +第一轮(Agent Runtime 核心): + agent_runtime/ → 约 1250 行 Python + api/ → 约 660 行 Python + services → 约 880 行 Python + models → 约 140 行 Python + frontend → 约 640 行 Vue/TypeScript + 修改(非新增) → 约 250 行 + ───────────────────────────────── + 小计 → 约 3820 行 + +第二轮(自主学习 + 定时任务 + 飞书集成): + services → 约 1550 行 Python(学习/调度/通知/飞书/橙子) + api → 约 560 行 Python + models → 约 80 行 Python + tasks → 约 30 行 Python + 修改(非新增) → 约 40 行 + ───────────────────────────────── + 小计 → 约 2260 行 + +总计新增 → 约 6080 行 ``` --- ## 整体完成度 -从最初 DAG 工作流引擎 → Agent Runtime → 多 Agent 编排 → Agent 监控,平台自主 AI Agent 能力已从 **0 → 核心闭环 + 可观测**: +从最初 DAG 工作流引擎 → Agent Runtime → 多 Agent 编排 → Agent 监控 → 自主学习 → 定时任务 → 飞书集成,平台自主 AI Agent 能力已从 **0 → 完整闭环**: - 单 Agent ReAct 循环:✅ 完成 - 工具调用与记忆管理:✅ 完成 - 执行追踪与记忆压缩:✅ 完成 @@ -168,6 +200,9 @@ frontend → 约 640 行 Vue/TypeScript(含 pipeline 前端选 - 知识库 RAG:✅ 完成(上传 → 解析 5 种格式 → 切片 → 向量化 → 检索) - 工作流预算接入:✅ 完成(Agent LLM/工具调用计入 WorkflowEngine 全局预算) - 工具市场:✅ 完成(HTTP/Code 工具 CRUD + 沙箱测试 + 市场浏览) +- **Agent 自主学习**:✅ 完成(任务分类 → 工具序列提取 → 学习模式注入) +- **Agent 定时任务系统**:✅ 完成(cron 表达式 → Celery Beat 到期触发) +- **飞书通知与机器人对话**:✅ 完成(通知系统 + 飞书推送 + 橙子机器人) **新增工具**: - 种子脚本批量创建 Agent + 开发者工具(代码编程助手 + 4 个自主 Agent + 5 个开发者工具) @@ -181,9 +216,12 @@ frontend → 约 640 行 Vue/TypeScript(含 pipeline 前端选 - Reviewer 审查所有步骤输出,生产最终答案 - 测试通过(Python/JS 对比分析:Planner 生成 5 步计划 → Executor 执行 5 步 → Reviewer 输出 7541 字审查报告) -**未完成项**:自主学习。 +**第二轮新增功能**: +- **Agent 自主学习**:11 类任务分类 × 工具序列提取/合并 × 有效性评分 × 学习模式注入 system prompt +- **Agent 定时任务系统**:cron 表达式 + Celery Beat 每分钟扫描 + 到期自动触发执行 +- **飞书通知与机器人对话**:通知系统 + 飞书定时推送 + 橙子飞书机器人(独立 WS 连接) -整体完成度:**99% → 99.7%**(核心功能闭环 + Pipeline 流水线新模式,仅剩自主学习一项长期规划) +整体完成度:**100%**(自主 AI Agent 全部能力完整闭环,无未完成核心项目) --- @@ -284,9 +322,9 @@ POST /api/v1/agent-chat/orchestrate --- -## 后续计划 +## 后续计划 — 全部已完成 -### 短期(1-2 周)— 全部完成 +### 第一阶段(短期 1-2 周)— 全部完成 | 项目 | 状态 | 说明 | |------|------|------| @@ -295,24 +333,26 @@ POST /api/v1/agent-chat/orchestrate | 执行追踪 | ✅ 完成 | 后端返回 steps,前端 AgentChat.vue 可展开显示思考链 | | 多 Agent 编排 | ✅ 完成 | 四种模式:route(路由分发)、sequential(流水线)、debate(独立回答+汇总)、pipeline(规划→执行→审查) | | 编排前端 UI | ✅ 完成 | AgentChat.vue 新增模式切换、Agent 编辑弹窗、步骤展开 | -| 预算接入 | ✅ 完成 | Agent 内部 LLM 调用也计入工作流执行预算——通过 `AgentBudgetConfig` 内控 + `on_llm_invocation` 外调双向保障 | -| SSE 流式输出 | ✅ 完成 | 新增 `POST /api/v1/agent-chat/bare/stream` 端点,SSE 实时推送思考步骤和最终答案 | +| 预算接入 | ✅ 完成 | Agent 内部 LLM 调用也计入工作流执行预算 | +| SSE 流式输出 | ✅ 完成 | 新增 `POST /api/v1/agent-chat/bare/stream` 端点 | -### 中期(1-2 月)— 全部完成 +### 第二阶段(中期 1-2 月)— 全部完成 | 项目 | 状态 | 说明 | |------|------|------| -| 向量记忆 | ✅ 完成 | SiliconFlow Embedding API(bce-embedding-base_v1, 768维)+ 余弦相似度 Top-K 检索,无 API Key 时自动降级 | -| Agent Dashboard | ✅ 完成 | Agent 专属监控面板:LLM 调用追踪、Token 统计、Agent 用量排行、工具调用频次、日趋势图 | -| 工具市场 | ✅ 完成 | HTTP/Code 工具 CRUD + 沙箱测试(httpx / 沙箱 exec)+ 市场浏览(分类/搜索/scope 筛选)+ 使用计数 | -| 知识库 | ✅ 完成 | 文件上传 → 解析 5 种格式(txt/pdf/docx/csv/md)→ 分块(段落/句子)→ 嵌入 → 语义检索 → RAG 上下文注入 | +| 向量记忆 | ✅ 完成 | SiliconFlow Embedding API + 余弦相似度 Top-K 检索 | +| Agent Dashboard | ✅ 完成 | LLM 调用追踪、Token 统计、Agent 用量排行、工具调用频次、日趋势图 | +| 工具市场 | ✅ 完成 | HTTP/Code 工具 CRUD + 沙箱测试 + 分类浏览 | +| 知识库 RAG | ✅ 完成 | 5 种格式解析 → 分块 → 嵌入 → 语义检索 → 上下文注入 | -### 长期(3-6 月) +### 第三阶段(长期 3-6 月)— 全部完成 -| 项目 | 说明 | -|------|------| -| 自主学习 | Agent 从历史执行中自动优化工具选择策略 | -| 监控与告警 | Agent 执行异常检测与告警 | +| 项目 | 状态 | 说明 | +|------|------|------| +| 自主学习 | ✅ 完成 | 11 类任务分类 × 工具序列提取/合并 × 有效性评分 × 学习模式注入 | +| 定时任务系统 | ✅ 完成 | cron 表达式 + Celery Beat 每分钟扫描 + 到期自动触发执行 | +| 飞书通知与机器人 | ✅ 完成 | 通知系统 + 飞书推送 + 橙子飞书机器人 | +| 监控与告警 | ✅ 完成 | Agent 异常检测、通知推送 | --- @@ -391,3 +431,28 @@ POST /api/v1/agent-chat/orchestrate - [x] `POST /api/v1/tools/test/code` — 代码沙箱测试(文本统计 0ms) - [x] `POST /api/v1/tools/{id}/use` — 使用计数自增 - [x] `DELETE /api/v1/tools/{id}` — 删除自定义工具 +- [x] **Agent 自主学习**(2026-05-02 新增) + - [x] `AgentLearningPattern` 模型(task_type / tool_sequence / frequency / score / keywords) + - [x] `agent_learning_service.py` — `extract_pattern()` 从执行中提取工具序列 + - [x] `agent_learning_service.py` — `merge_pattern()` 合并相似模式(频率自增、评分加权) + - [x] `agent_learning_service.py` — `get_relevant_patterns()` 按任务分类检索 Top-K 模式 + - [x] `agent_learning_service.py` — `inject_learning_hints()` 注入历史模式到 system prompt + - [x] 集成到 `AgentRuntime.run()` 和 `run_stream()` —— 执行前注入、执行后保存 + - [x] 支持 bare chat 和 Agent 模式(通过 `enable_learning` / `learning_mode` 参数控制) +- [x] **Agent 定时任务系统**(2026-05-02 新增) + - [x] `AgentSchedule` 模型(agent_id / cron_expression / enabled / last_run_at / next_run_at) + - [x] `agent_schedule_service.py` — `check_due_schedules()` 扫描到期任务 + - [x] `agent_schedules.py` API — CRUD + 手动触发 + 启用/禁用 + - [x] `scheduler_tasks.py` — Celery Beat 每分钟调度任务 + - [x] 集成到 `celery_app.py`(`app.conf.beat_schedule` 注册 `check-agent-schedules`) + - [x] 依赖:`croniter`(cron 表达式解析) +- [x] **飞书通知与机器人对话**(2026-05-02 新增) + - [x] `Notification` 模型 + `notification_service.py` 通知服务 + - [x] `notifications.py` API — 通知查询、已读标记 + - [x] `feishu_bind.py` API — 飞书账号绑定/解绑 + - [x] `feishu_app_service.py` — 飞书应用消息发送(文本/富文本) + - [x] `feishu_notifier.py` — 定时任务结果自动推送飞书 + - [x] `feishu_ws_handler.py` — 飞书 WebSocket 长连接事件监听(消息/进群/退群) + - [x] `orange_app_service.py` — 橙子飞书机器人消息处理 + - [x] `orange_ws_handler.py` — 橙子机器人独立 WS 连接 + 固定路由到橙子助手 Agent + - [x] 执行记录添加 `schedule_id` 字段,用户添加飞书绑定字段 diff --git a/项目初始文档.md b/项目初始文档.md new file mode 100644 index 0000000..668383e --- /dev/null +++ b/项目初始文档.md @@ -0,0 +1,468 @@ +# AIAgent 项目初始文档 + +> 大模型重启后,读此文档即可快速了解项目全貌。最后更新: 2026-05-02。 + +--- + +## 1. 一句话概括 + +**低代码智能体搭建与工作流编排平台** — 可视化拖拽配置 30+ 种节点类型,集成多种 AI 模型,支持复杂业务流程自动化执行。 + +--- + +## 2. 速查卡片 + +| 项目 | 值 | +|---|---| +| 代码路径 | `D:\aaa\aiagent` | +| Git 分支 | `main` | +| 数据库 | MySQL 腾讯云 `gz-cynosdbmysql-grp-d26pzce5.sql.tencentcdb.com:24936` / `agent_db` | +| Redis | 本地 `localhost:6379` | +| 前端端口 | `3001` (Vite dev) | +| 后端端口 | `8037` (uvicorn) | +| 外部地址 | `http://101.43.95.130:8038` | +| 健康检查 | `GET http://127.0.0.1:8037/health` | +| API 文档 | `http://127.0.0.1:8037/docs` | +| 启动脚本 | `start_aiagent.ps1` (弹窗) / `start_aiagent_background.ps1` (静默) | +| 停止脚本 | `stop_aiagent.ps1` | +| 重启后端 | `restart_backend_celery.ps1` | +| 开机自启 | `install_autostart.ps1` (需管理员) | + +--- + +## 3. 架构总览 + +``` +┌──────────────────────────────────────────────────────────┐ +│ 用户浏览器 │ +│ http://localhost:3001 │ +└─────────────┬────────────────────────────────────────────┘ + │ + ┌─────────┴──────────┐ + │ Frontend (Vite) │ Vue 3 + Pinia + Element Plus + Vue Flow + │ :3001 │ + └─────────┬──────────┘ + │ /api/v1/* (Vite proxy → :8037) + │ /api/v1/ws (WebSocket) + ┌─────────┴──────────┐ + │ Backend (FastAPI) │ Python + SQLAlchemy + Celery + │ :8037 │ + │ ├─ 26 API 路由 │ + │ ├─ 33 服务模块 │ + │ └─ 启动时: 注册内置工具 + 飞书 WS 长连接 + └──┬───────┬─────────┘ + │ │ + ▼ ▼ + ┌──────┐ ┌──────┐ ┌──────────────┐ + │MySQL │ │Redis │────▶│Celery Worker │ 异步执行工作流/Agent + │(云) │ │:6379 │ │(threads×8) │ + └──────┘ └──────┘ └──────┬───────┘ + │ Redis Pub/Sub + ▼ + WebSocket → 前端实时状态推送 +``` + +**关键设计**: +- 用户请求 → FastAPI 创建执行记录 → Celery 任务入 Redis 队列 → Worker 消费执行 → WebSocket 推送进度 +- 工作流在 Celery Worker 中异步运行,支持暂停/恢复/取消 +- API 和 Worker 共用同一个 venv 和工具注册逻辑 + +--- + +## 4. 启动 / 停止 + +### 4.1 标准启动(弹窗模式) + +```powershell +cd D:\aaa\aiagent +powershell -ExecutionPolicy Bypass -File .\start_aiagent.ps1 +``` + +会打开 4 个 PowerShell 窗口:Redis、API、Celery、前端。 + +### 4.2 停止 + +```powershell +powershell -ExecutionPolicy Bypass -File .\stop_aiagent.ps1 +``` + +### 4.3 仅重启后端+Celery(最常用,改 .env / 依赖 / 工具后) + +```powershell +powershell -ExecutionPolicy Bypass -File .\restart_backend_celery.ps1 +``` + +### 4.4 手动应急启动(脚本不可用时) + +4 个终端分别执行: + +```powershell +# 1) Redis +cd D:\aaa\aiagent\backend\redis +.\redis-server.exe --port 6379 + +# 2) API +cd D:\aaa\aiagent\backend +.\venv\Scripts\Activate.ps1 +python -m uvicorn app.main:app --host 0.0.0.0 --port 8037 + +# 3) Celery +cd D:\aaa\aiagent\backend +.\venv\Scripts\Activate.ps1 +python -m celery -A app.core.celery_app worker --loglevel=info --pool=threads --concurrency=8 + +# 4) 前端 +cd D:\aaa\aiagent\frontend +$env:AIAGENT_API_PROXY='http://127.0.0.1:8037' +pnpm dev --port 3001 +``` + +### 4.5 验证 + +```powershell +netstat -ano | findstr :6379 +netstat -ano | findstr :8037 +netstat -ano | findstr :3001 +curl.exe http://127.0.0.1:8037/health +``` + +--- + +## 5. 项目目录结构(关键路径) + +``` +D:\aaa\aiagent\ +├── backend/ +│ ├── .env # ★ 环境变量 (DB/Redis/API Keys/CORS) +│ ├── requirements.txt # Python 依赖 +│ ├── venv/ # Python 虚拟环境 +│ ├── redis/ # Windows Redis 可执行文件 +│ ├── alembic/ # 数据库迁移 +│ ├── alembic.ini +│ ├── app/ +│ │ ├── main.py # ★ FastAPI 入口 (startup 事件 + 路由注册) +│ │ ├── core/ +│ │ │ ├── config.py # Pydantic Settings (环境变量读取) +│ │ │ ├── database.py # SQLAlchemy 引擎 + 会话 +│ │ │ ├── celery_app.py # Celery 应用实例 +│ │ │ ├── security.py # JWT 工具 +│ │ │ ├── redis_client.py # Redis 客户端 +│ │ │ ├── tools_bootstrap.py # 内置工具注册逻辑 +│ │ │ ├── exceptions.py # 自定义异常类 +│ │ │ └── error_handler.py # 全局异常处理器 +│ │ ├── models/ # SQLAlchemy 数据模型 (14个) +│ │ ├── api/ # REST 路由 (26个文件) +│ │ ├── services/ # 业务逻辑 (33个文件) +│ │ │ ├── workflow_engine.py # ★ 工作流执行引擎 (~5700行) +│ │ │ ├── workflow_validator.py # 工作流校验 +│ │ │ ├── llm_service.py # LLM 调用 (OpenAI/DeepSeek 兼容) +│ │ │ ├── tool_registry.py # 工具注册表 +│ │ │ ├── builtin_tools.py # 内置工具实现 +│ │ │ └── ... # 其他服务 +│ │ ├── tasks/ # Celery 异步任务 +│ │ ├── websocket/ # WebSocket 管理 +│ │ └── utils/ # 工具函数 +│ ├── scripts/ # 运维脚本 +│ │ └── check_ocr_env.py +│ └── tests/ +│ +├── frontend/ +│ ├── package.json +│ ├── vite.config.ts # Vite 配置 (proxy → :8037) +│ ├── src/ +│ │ ├── main.ts # Vue 入口 +│ │ ├── api/index.ts # Axios 封装 + 拦截器 +│ │ ├── router/index.ts # 路由 (20条) +│ │ ├── stores/ # Pinia 状态管理 (5个) +│ │ ├── views/ # 页面视图 (18个) +│ │ ├── components/ # 组件 +│ │ │ └── WorkflowEditor/ # 工作流编辑器核心 +│ │ └── types/index.ts # TS 类型定义 +│ └── node_modules/ +│ +├── scripts/ # 种子数据脚本 +│ ├── seed_tools.py +│ ├── seed_agents.py +│ ├── seed_coding_agent.py +│ ├── seed_scenario_agents.py +│ └── seed_extra_agents.py +│ +├── start_aiagent.ps1 # 一键启动 (弹窗) +├── stop_aiagent.ps1 # 一键停止 +├── restart_backend_celery.ps1 # 仅重启后端+Celery +├── start_aiagent_background.ps1 # 后台静默启动 (开机自启用) +├── install_autostart.ps1 # 安装/卸载开机自启任务 +├── agent_workspaces/ # 文件工具沙箱目录 +├── uploads/ # 上传文件存储 +├── tessdata/ # Tesseract OCR 语言包 +├── (红头)Windows服务器启动与重启唯一指南.md # ★ 运维权威文档 +└── aiagent项目架构文档.md # 架构详解 +``` + +--- + +## 6. 技术栈 + +| 层 | 技术 | +|---|---| +| 前端框架 | Vue 3 (Composition API) + TypeScript | +| 构建 | Vite 5 | +| UI 库 | Element Plus | +| 流程图 | Vue Flow (基于 React Flow) | +| 状态管理 | Pinia | +| HTTP | Axios | +| 后端框架 | FastAPI (Python) | +| ORM | SQLAlchemy 2.0 + PyMySQL | +| 异步任务 | Celery 5.3 (Redis Broker) | +| 迁移 | Alembic | +| AI SDK | OpenAI Python SDK (兼容 DeepSeek/SiliconFlow 等) | +| 加密 | cryptography (Fernet) | +| 实时推送 | WebSocket + Redis Pub/Sub | + +--- + +## 7. 数据库模型 (14 个表) + +| 表 | 模型 | 用途 | +|---|---|---| +| `users` | User | 用户 (含 role 字段) | +| `workflows` | Workflow | 工作流定义 (nodes+edges JSON) | +| `workflow_versions` | WorkflowVersion | 版本历史 + 回滚 | +| `workflow_templates` | WorkflowTemplate | 预制模板 | +| `agents` | Agent | 智能体 (workflow_config JSON) | +| `executions` | Execution | 执行记录 (pending/running/completed/failed/paused) | +| `execution_logs` | ExecutionLog | 节点级执行日志 | +| `model_configs` | ModelConfig | AI 模型配置 (API Key Fernet 加密) | +| `tools` | Tool | 工具定义 | +| `data_sources` | DataSource | 外部数据源连接 | +| `permissions` | Permission | RBAC 权限 | +| `alert_rules` | AlertRule | 监控告警规则 | +| `node_templates` | NodeTemplate | 节点配置模板 | +| `persistent_user_memories` | PersistentUserMemory | 跨会话持久化记忆 | + +--- + +## 8. API 路由清单 (26 个模块, `/api/v1/*`) + +| 路由模块 | 文件 | 功能 | +|---|---|---| +| auth | `auth.py` | 注册/登录/JWT | +| workflows | `workflows.py` | 工作流 CRUD + 执行 + 版本 | +| executions | `executions.py` | 执行记录 + 暂停/恢复/取消 | +| execution_logs | `execution_logs.py` | 执行日志查询 | +| agents | `agents.py` | Agent CRUD + 场景模板 | +| agent_chat | `agent_chat.py` | Agent 对话 API (SSE 流式) | +| agent_monitoring | `agent_monitoring.py` | Agent 监控统计 | +| agent_schedules | `agent_schedules.py` | Agent 定时任务 (cron) | +| tools | `tools.py` | 工具市场 CRUD | +| model_configs | `model_configs.py` | 模型配置管理 | +| data_sources | `data_sources.py` | 数据源管理 | +| uploads | `uploads.py` | 文件上传 | +| websocket | `websocket.py` | WebSocket 实时推送 | +| webhooks | `webhooks.py` | 外部 Webhook 接收 | +| template_market | `template_market.py` | 模板市场 | +| platform_templates | `platform_templates.py` | 平台预置模板 | +| node_templates | `node_templates.py` | 节点模板 | +| node_test | `node_test.py` | 单节点测试 | +| batch_operations | `batch_operations.py` | 批量操作 | +| collaboration | `collaboration.py` | 多用户协作 | +| permissions | `permissions.py` | RBAC 权限管理 | +| monitoring | `monitoring.py` | 系统监控 | +| alert_rules | `alert_rules.py` | 告警规则 | +| notifications | `notifications.py` | 通知推送 | +| knowledge_base | `knowledge_base.py` | 知识库 (RAG) | +| feishu_bind | `feishu_bind.py` | 飞书用户绑定 | + +--- + +## 9. 前端路由清单 (20 条) + +| 路径 | 视图 | 说明 | +|---|---|---| +| `/login` | Login.vue | 登录 | +| `/` | Home.vue | 首页仪表盘 | +| `/console` | MainConsole.vue | 主控制台 | +| `/workflow/:id?` | WorkflowDesigner.vue | 工作流编辑器 | +| `/agents` | Agents.vue | Agent 管理 | +| `/agents/:id/design` | WorkflowDesigner.vue | Agent 工作流设计 | +| `/agents/:id/config` | AgentConfig.vue | Agent 配置 | +| `/executions` | Executions.vue | 执行记录 | +| `/executions/:id` | ExecutionDetail.vue | 执行详情 | +| `/execution-board` | ExecutionBoard.vue | 执行看板 | +| `/data-sources` | DataSources.vue | 数据源管理 | +| `/model-configs` | ModelConfigs.vue | 模型配置 | +| `/template-market` | TemplateMarket.vue | 模板市场 | +| `/permissions` | PermissionManagement.vue | 权限管理 (admin) | +| `/monitoring` | Monitoring.vue | 监控面板 | +| `/agent-monitoring` | AgentDashboard.vue | Agent 仪表盘 | +| `/alert-rules` | AlertRules.vue | 告警规则 | +| `/node-templates` | NodeTemplates.vue | 节点模板 | +| `/tools` | Tools.vue | 工具市场 | +| `/agent-chat` | AgentChat.vue | Agent 对话 | +| `/agent-chat/:id` | AgentChat.vue | 指定 Agent 对话 | + +**路由守卫**: 除 `/login` 外均需 JWT;`/permissions` 额外要求 admin 角色。 + +--- + +## 10. 节点类型 (30+ 种) + +### 控制流 +`start` `end/output` `condition` `switch` `merge` `loop/foreach` `wait` + +### AI 能力 +`llm` `template` `code` + +### 数据 +`data/transform` `json` `text` `csv` `excel` `cache` `vector_db` + +### 存储 +`database/db` `file/file_operation` `object_storage` `pdf` `image` + +### 网络 +`http/request` `webhook` `oauth` + +### 消息 +`email/mail` `message_queue/mq/rabbitmq/kafka` `sms` + +### 办公协同 +`slack` `dingtalk/dingding` `wechat_work/wecom` + +### 高级 +`subworkflow/invoke_agent` `batch` `validator` `approval` `error_handler` `log` `schedule/delay/timer` + +核心执行逻辑在 `backend/app/services/workflow_engine.py` 的 `execute_node` 方法中。 + +--- + +## 11. 核心服务模块 (33 个) + +| 服务 | 文件 | 职责 | +|---|---|---| +| 工作流引擎 | `workflow_engine.py` | 拓扑排序 + 节点执行 + 预算熔断 + 断点恢复 | +| 工作流校验 | `workflow_validator.py` | 结构/连接/配置合法性检查 | +| 工作流模板 | `workflow_templates.py` | 预置模板生成 | +| LLM 服务 | `llm_service.py` | OpenAI 兼容 SDK 调用 + 流式 + 工具调用 | +| 工具注册表 | `tool_registry.py` | 内置/HTTP/工作流工具管理 | +| 内置工具 | `builtin_tools.py` | file_read/write/system_info/datetime 等 | +| 条件解析 | `condition_parser.py` | 条件表达式求值 + 分支裁剪 | +| 数据转换 | `data_transformer.py` | 数据格式转换 | +| 执行日志 | `execution_logger.py` | 节点级日志记录 | +| 执行预算 | `execution_budget.py` | 步数/LLM/工具三重熔断 | +| 加密服务 | `encryption_service.py` | Fernet 加密/解密 | +| 持久记忆 | `persistent_memory_service.py` | 跨会话用户记忆 | +| 权限服务 | `permission_service.py` | RBAC 检查 | +| 监控服务 | `monitoring_service.py` | 系统指标采集 | +| 告警服务 | `alert_service.py` | 告警规则评估 + 通知 | +| 数据源连接器 | `data_source_connector.py` | 外部数据源连接 | +| 场景模板 | `scene_templates.py` | 场景化模板 | +| 场景 DSL | `scenario_dsl.py` | DSL 解析/校验 | +| Agent 学习 | `agent_learning_service.py` | 从历史执行中优化工具选择 | +| Agent 监控 | `agent_monitoring_service.py` | Agent 运行指标 | +| Agent 调度 | `agent_schedule_service.py` | 定时任务 cron 调度 | +| 知识库 | `knowledge_service.py` | 向量检索 RAG | +| 嵌入服务 | `embedding_service.py` | Embedding 向量化 | +| 文档解析 | `document_parser.py` | PDF/Word/Excel 解析 | +| 文本分块 | `text_chunker.py` | 长文本分块 | +| 飞书通知 | `feishu_notifier.py` | 飞书消息推送 | +| 飞书 WebSocket | `feishu_ws_handler.py` | 飞书机器人长连接 | +| 飞书应用 | `feishu_app_service.py` | 飞书应用逻辑 | +| 橙子 WebSocket | `orange_ws_handler.py` | 第二个飞书机器人 | +| 橙子应用 | `orange_app_service.py` | 第二个飞书应用 | +| 通知服务 | `notification_service.py` | 统一通知推送 | +| Agent 工作区日志 | `agent_workspace_chat_log.py` | 对话日志落盘 | + +--- + +## 12. 关键配置项 (`.env`) + +``` +DATABASE_URL=mysql+pymysql://root:***@gz-cynosdbmysql-grp-d26pzce5.sql.tencentcdb.com:24936/agent_db +REDIS_URL=redis://localhost:6379/0 +CORS_ORIGINS=http://localhost:3001,... (多地址逗号分隔) +DEEPSEEK_API_KEY=sk-fdf7cc1c73504e628ec0119b7e11b8cc +SILICONFLOW_API_KEY=sk-xpptixobqxshkmikjvjeoltekytqmmresfndhoivezomuobn +FEISHU_APP_ID=cli_a97f3e2ecaf81cba # 飞书机器人 +ORANGE_APP_ID=cli_a97f1271ec345cc6 # 橙子飞书机器人 +EXTERNAL_URL=http://101.43.95.130:8038 +TESSERACT_CMD=C:/Program Files/Tesseract-OCR/tesseract.exe +``` + +**重要**: 修改 `.env` 后至少需要 `restart_backend_celery.ps1`。 + +--- + +## 13. 安全机制 + +- **JWT 认证** — 所有 API Bearer Token(`/login` 除外),`app.core.security` +- **模型密钥加密** — API Key Fernet 加密存储,仅创建者可调用 +- **RBAC** — 角色级权限 (`admin` / `user`) +- **执行预算** — 步数上限(2000)、LLM 调用上限(200)、工具调用上限(500) +- **代码沙箱** — `code` 节点禁用 `open`/`eval`/`__import__` +- **文件沙箱** — 操作限制在 `LOCAL_FILE_TOOLS_ROOT` 目录内 + +--- + +## 14. 外部集成 + +| 集成 | 说明 | +|---|---| +| 飞书 | 2 个机器人 — 应用通知 + 对话交互 (WebSocket 长连接) | +| DeepSeek | AI 模型 (DSML 协议支持, reasoning_content) | +| SiliconFlow | Embedding 模型 (bce-embedding-base_v1) | +| 腾讯云 MySQL | 生产数据库 | +| Tesseract OCR | 图片文字识别 (Windows 安装路径) | + +--- + +## 15. Git 历史摘要 (最近 20 次提交) + +``` +7ee80c7 feat: 集成飞书通知和机器人对话系统 +0bbf68d feat: 实现 Agent 定时任务系统 — cron 表达式周期执行 +e3802ef feat: 实现 Agent 自主学习 — 从历史执行中优化工具选择 +c28cf40 feat: 添加更多场景专用 Agent 种子脚本 +5a52dac feat: 添加 5 个场景专用 Agent 种子脚本 +5423aca feat: 新增 Pipeline 流水线编排模式 (Planner→Executor→Reviewer) +7aba0f9 fix: 修复 Agent 流式对话无响应和工具 schema 兼容性问题 +342f3fc chore: 添加工具市场种子脚本 +4c1b5b2 fix: 工具市场 categories 路由被 /{tool_id} 拦截 +30dad00 fix: 工具市场页面缺少 MainLayout 导入 +9400cf9 refactor: 优化工具市场 UI — 卡片视图、统计概览、分步表单 +cd83090 feat: 添加工具市场前端页面 +7b9e082 feat: 向量记忆 RAG、工具市场、SSE 流式响应、前端集成与测试覆盖 +036f533 feat: Agent 监控与编排、仪表盘/配置页及文档更新 +0946756 feat: Agent 运行时、对话 API、作业助手与引擎修复 +4366312 feat: DeepSeek v4 模型对齐、作业助手脚本与 Agent 对比测试 +cadeb2d fix: 修复热点摘要超长上下文并统一 Windows 启动文档 +63b5411 图片上传识别功能 +df4fab1 feat: Agent 批量测试、作业助手与上传预览 +0608161 feat: 完善企业场景多线路由与执行稳定性 +``` + +--- + +## 16. 常见问题速查 + +| 症状 | 根因 | 解决 | +|---|---|---| +| `timeout of 30000ms exceeded` | Redis 端口不匹配或 Celery 未运行 | 检查 `.env` 中 `REDIS_URL` 端口与 `netstat` 一致 | +| Celery 任务卡住 | Windows prefork 池问题 | 使用 `--pool=threads` (脚本已配置) | +| 前端 401 | Token 过期或未登录 | 重新登录获取 Token | +| OCR 不工作 | Tesseract 未安装或路径不对 | 检查 `TESSERACT_CMD` 路径 | +| 内置工具未注册 | Worker 与 API 使用不同启动逻辑 | 确认 Worker 日志中有"内置工具就绪" | +| 工作流执行超时 | 循环节点未终止或 LLM 调用过多 | 检查执行日志,调整预算上限 | +| `.env` 改完不生效 | 仅重启了 API,Celery 未重启 | 执行 `restart_backend_celery.ps1` | + +--- + +## 17. 开发工作流 + +``` +改前端代码 → Vite HMR 自动生效 +改后端 API 代码 → uvicorn --reload 自动重启 +改 .env / 依赖 → restart_backend_celery.ps1 +改工具实现 → restart_backend_celery.ps1 +改工作流引擎 → restart_backend_celery.ps1 +加新节点类型 → 修改 workflow_engine.py + 前端 NodeTypes.ts + restart +```