AgentSkillsCN

backend-architecture

前端组件设计规范与最佳实践。当您编写任何前端代码(React/Next.js 组件、页面、hooks)时,此技能会自动触发。它确保代码的复用性、封装性以及单一职责原则。触发场景包括创建新的前端组件或页面、重构现有前端代码、为前端新增功能,或对 frontend 目录下的任何代码修改进行处理。此技能始终生效。

SKILL.md
--- frontmatter
name: backend-architecture
description: |
  后端代码架构上下文。此技能在每次对话开始时自动触发,提供项目后端的模块化架构概览。
  包含:核心模块、业务服务、数据模型、API路由、调度器等组件的介绍。
  触发条件:alwaysApply: true(始终应用)
alwaysApply: true

EmbedEase AI 后端架构

基于 FastAPI + LangChain v1.2 + LangGraph 的多智能体商品推荐系统。

目录结构

code
backend/
├── app/
│   ├── core/           # 核心模块(配置、数据库、LLM、日志、Chat Models)
│   ├── models/         # SQLAlchemy 数据模型
│   ├── prompts/        # 提示词管理系统
│   ├── repositories/   # 数据访问层
│   ├── routers/        # FastAPI 路由
│   ├── schemas/        # Pydantic Schema
│   ├── services/       # 业务逻辑层
│   ├── scheduler/      # 定时任务调度
│   ├── utils/          # 工具函数
│   └── main.py         # 应用入口
├── tests/              # 测试用例
└── data/               # 静态数据

核心模块 (app/core/)

模块文件职责
配置config.pyPydantic Settings,环境变量管理
数据库database.pySQLAlchemy 异步引擎、会话管理
爬虫数据库crawler_database.py爬虫专用数据库连接
Chat Modelschat_models/多态架构 Chat 模型(推理内容提取)
LLMllm.pyChatOpenAI/Embeddings 初始化
Embeddingembedding.py向量嵌入模型
Rerankrerank.py重排序模型
日志logging.pyLoguru 结构化日志
健康检查health.py, health_checks.py依赖健康状态
错误处理errors.py, error_reporter.py统一异常类和错误报告
依赖注入dependencies.pyFastAPI 依赖(DB Session 等)
路径管理paths.py文件路径常量

Chat Models 多态架构 (core/chat_models/)

code
chat_models/
├── base.py             # ReasoningChunk 结构 + BaseReasoningChatModel 抽象基类
├── registry.py         # 模型创建工厂,按 provider 选择实现
└── providers/
    └── reasoning_content.py  # SiliconFlow 推理内容实现

提示词系统 (app/prompts/)

统一管理所有提示词,支持默认值 + 数据库覆盖:

code
prompts/
├── registry.py         # PromptRegistry - 提示词注册表
├── schemas.py          # Pydantic Schema
└── defaults/           # 默认提示词
    ├── agent.py        # Agent 提示词
    ├── crawler.py      # 爬虫提示词
    ├── memory.py       # 记忆提示词
    └── skill.py        # 技能提示词
职责
PromptRegistry提示词 CRUD、优先级(数据库 > 默认)、reset

数据模型 (app/models/)

模型文件说明
Agentagent.py智能体配置、FAQEntry、KnowledgeConfig
Conversationconversation.py会话、HandoffState
Messagemessage.py消息
Useruser.py用户
Productproduct.py商品
CrawlSite/CrawlPage/CrawlTaskcrawler.py爬虫站点、页面、任务
Promptprompt.py提示词模板
ToolCalltool_call.py工具调用记录
AppMetadataapp_metadata.py键值存储(系统配置)
Skill/AgentSkillskill.py技能定义、Agent-技能关联

业务服务 (app/services/)

Agent 服务 (services/agent/)

多智能体系统核心:

code
agent/
├── core/               # 核心服务
│   ├── service.py      # AgentService 主入口
│   ├── factory.py      # Agent 工厂
│   ├── config.py       # Agent 配置管理
│   ├── intent.py       # 意图识别
│   └── policy.py       # 路由策略
├── middleware/         # 中间件(声明式注册,按 order 执行)
│   ├── registry.py           # 中间件注册表
│   ├── sliding_window.py     # 滑动窗口裁剪
│   ├── summarization_broadcast.py # 上下文压缩摘要
│   ├── todo_broadcast.py     # TODO 规划广播
│   ├── sequential_tools.py   # 工具串行执行
│   ├── noise_filter.py       # 工具输出噪音过滤
│   ├── response_sanitization.py # 响应内容安全过滤
│   ├── llm_call_sse.py       # LLM 调用事件推送
│   └── logging.py            # 日志记录
├── retrieval/          # 检索服务(已迁移到 knowledge/)
├── streams/            # 流式响应
├── tools/              # 工具定义(声明式注册)
│   ├── registry.py     # 工具注册表
│   ├── product/        # 商品工具(12+)
│   ├── knowledge/      # 知识库工具
│   └── common/         # 通用工具
└── bootstrap.py        # 默认 Agent 初始化

中间件执行顺序

Order名称说明可配置
10MemoryOrchestration记忆注入 + 异步写入✅ Agent 级
15PIIDetectionPII 敏感信息检测(多规则)✅ Agent 级
20ResponseSanitization响应内容安全过滤🔒 系统级
25ModelRetry模型调用重试(指数退避)✅ Agent 级
26ModelFallback模型降级(备选模型列表)✅ Agent 级
27ModelCallLimit模型调用限制(防死循环)✅ Agent 级
30SSELLM 调用事件推送🔒 系统级
40TodoBroadcast任务规划广播✅ Agent 级
50SequentialToolExecution工具串行执行🔒 系统级
55NoiseFilter工具输出噪音过滤✅ Agent 级
60Logging日志记录🔒 系统级
70ToolRetry工具重试✅ Agent 级
80ToolCallLimit工具调用限制✅ Agent 级
84ContextEditing上下文编辑(工具结果清理)✅ Agent 级
85SlidingWindow滑动窗口裁剪✅ Agent 级
90Summarization上下文压缩摘要✅ Agent 级

🔒 系统级:硬编码启用,不可在后台配置 ✅ Agent 级:可在后台管理页面配置开关和参数

商品工具列表

工具说明
search_products搜索商品
get_product_details获取商品详情
compare_products对比商品
filter_by_price价格筛选
list_all_categories列出所有类目
get_category_overview类目概览
list_products_by_category按类目列商品
find_similar_products查找相似商品
list_featured_products精选商品
list_products_by_attribute按属性筛选
suggest_related_categories推荐相关类目
get_product_purchase_links获取购买链接
guide_user引导用户

记忆系统 (services/memory/)

长期记忆 + 用户画像:

code
memory/
├── store.py            # UserProfileStore - LangGraph Store 基座
├── profile_service.py  # ProfileService - 用户画像服务
├── fact_memory.py      # FactMemoryService - 事实型长期记忆
├── graph_memory.py     # KnowledgeGraphManager - 图谱记忆
├── vector_store.py     # Qdrant 向量存储
├── models.py           # Entity, Fact, Relation, UserProfile
├── prompts.py          # 记忆提示词
└── middleware/         # 记忆编排中间件
职责
UserProfileStoreLangGraph Store,跨会话画像存储
ProfileService从事实/图谱自动提取画像信息
FactMemoryServiceLLM 抽取 + Qdrant 向量检索
KnowledgeGraphManager实体/关系结构化存储

技能服务 (services/skill/)

Agent 可扩展技能系统:

code
skill/
├── service.py      # SkillService - CRUD、Agent 关联、技能匹配
├── generator.py    # SkillGenerator - AI 智能生成技能
├── registry.py     # SkillRegistry - 运行时缓存
├── injector.py     # SkillInjector - 技能注入到 Agent
└── system_skills.py # 系统内置技能定义

知识库服务 (services/knowledge/)

code
knowledge/
├── factory.py          # 检索器工厂
├── kb_retriever.py     # 知识库检索
├── faq_retriever.py    # FAQ 检索
└── faq_service.py      # FAQ CRUD

客服支持 (services/support/)

code
support/
├── gateway.py          # 客服网关
├── handoff.py          # 人工客服转接
├── heat_score.py       # 热度评分
└── notification/       # 通知渠道
    ├── base.py         # 通知基类
    ├── dispatcher.py   # 通知分发器
    └── channels/       # 具体渠道实现

其他服务

服务目录/文件职责
会话conversation.py会话 CRUD、消息管理
聊天流chat_stream.pySSE 流式响应
流式响应streaming/SSE 上下文、事件发射器
爬虫crawler/网站爬取、页面解析、站点初始化
OCRocr/多引擎支持(RapidOCR、PaddleX、MinerU)
存储storage/MinIO 对象存储
WebSocketwebsocket/实时通信、心跳、消息路由
快速配置quick_setup/配置向导、状态管理、检查清单
商品画像catalog_profile.py商品分类画像
系统配置system_config.pyLLM/Embedding/Rerank 动态配置

数据访问层 (app/repositories/)

仓库文件职责
ConversationRepositoryconversation.py会话 CRUD
MessageRepositorymessage.py消息 CRUD
ProductRepositoryproduct.py商品 CRUD
CrawlerRepositorycrawler.py爬虫站点/页面 CRUD
ToolCallRepositorytool_call.py工具调用记录
UserRepositoryuser.py用户 CRUD

API 路由 (app/routers/)

路由前缀说明
admin.py/api/v1/admin后台管理
system_config.py/api/v1/admin/system-config系统配置
skills.py/api/v1/admin/skills技能管理、AI 生成
prompts.py/api/v1/admin/prompts提示词管理
chat.py/api/v1/chat聊天 API
conversations.py/api/v1/conversations会话管理
agents.py/api/v1/agentsAgent CRUD
crawler.py/api/v1/crawler爬虫管理
ocr.py/api/v1/ocrOCR 服务
support.py/api/v1/support客服支持
users.py/api/v1/users用户管理
upload.py/api/v1/upload文件上传
quick_setup.py/api/v1/quick-setup快速配置向导
health.py/api/v1/health健康检查
system.py/api/v1/system系统信息
ws.py/wsWebSocket

调度器 (app/scheduler/)

APScheduler 定时任务:

code
scheduler/
├── scheduler.py        # 任务调度器
├── registry.py         # 任务注册
├── runner.py           # 任务执行器
├── state/              # 任务状态管理
├── tasks/              # 任务定义
│   ├── base.py         # 任务基类
│   └── crawl_site.py   # 爬虫定时任务
└── routers/            # 调度器 API

事件类型 (app/schemas/events.py)

细粒度事件分类:

类别事件说明
流级别meta.start流开始
assistant.final最终态
error错误事件
LLM 边界llm.call.startLLM 调用开始
llm.call.endLLM 调用结束
LLM 内部assistant.reasoning.delta推理内容增量
assistant.delta文本增量
工具调用tool.start工具开始
tool.end工具结束
数据事件assistant.products商品数据
assistant.todosTODO 规划更新
context.summarized上下文压缩完成
context.trimmed滑动窗口裁剪
后处理memory.extraction.start记忆抽取开始
memory.extraction.complete记忆抽取完成
memory.profile.updated用户画像更新
客服support.handoff_started客服介入开始
support.handoff_ended客服介入结束
support.human_message人工客服消息
技能skill.activated技能被激活
skill.loaded技能被加载
多 Agentagent.routedAgent 路由决策
agent.handoffAgent 切换
中间件model.retry.start模型重试开始
model.retry.failed模型重试失败
model.fallback模型降级
model.call_limit.exceeded模型调用限制超限
context.edited上下文编辑(工具结果清理)

数据流

code
用户请求 → FastAPI Router → Service → Repository → Database
                ↓
           Agent 服务 → 中间件链 → LangGraph → LLM
                ↓
           工具调用 → 检索服务 → Qdrant/知识库
                ↓
           SSE 流式响应 → 事件推送
                ↓
           记忆抽取 → 用户画像更新

配置优先级

  • 系统配置(LLM_API_KEY 等):数据库 > 环境变量
  • 提示词数据库 > 默认值

通过 SystemConfigServicePromptRegistry 管理动态配置。

测试

bash
# 运行所有测试
uv run pytest

# 运行特定模块测试
uv run pytest tests/services/test_system_config.py -v

# 运行技能系统测试
uv run pytest tests/schemas/test_skill.py tests/services/test_skill.py tests/routers/test_skills.py -v