# AI内容生成引擎

<cite>
**本文档引用的文件**
- [index.ts](file://server/src/modules/book-generator/index.ts)
- [graph.ts](file://server/src/modules/book-generator/graph.ts)
- [book-generator.service.ts](file://server/src/modules/book-generator/book-generator.service.ts)
- [book-generator.controller.ts](file://server/src/modules/book-generator/book-generator.controller.ts)
- [langgraph-controller.ts](file://server/src/modules/book-generator/langgraph-controller.ts)
- [selector.ts](file://server/src/modules/book-generator/strategies/selector.ts)
- [types.ts](file://server/src/modules/book-generator/strategies/types.ts)
- [per-chapter.strategy.ts](file://server/src/modules/book-generator/strategies/per-chapter.strategy.ts)
- [full-outline.node.ts](file://server/src/modules/book-generator/nodes/full-outline.node.ts)
- [content.node.ts](file://server/src/modules/book-generator/nodes/content.node.ts)
- [builder.ts](file://server/src/modules/book-generator/prompts/builder.ts)
- [book-generator.store.ts](file://server/src/modules/book-generator/book-generator.store.ts)
- [fault-tolerance.ts](file://server/src/modules/book-generator/fault-tolerance.ts)
- [book-tools.ts](file://server/src/services/llm/book-tools.ts)
- [stage-manager.ts](file://server/src/modules/book-generator/stage-manager.ts)
</cite>

## 目录
1. [简介](#简介)
2. [项目结构](#项目结构)
3. [核心组件](#核心组件)
4. [架构概览](#架构概览)
5. [详细组件分析](#详细组件分析)
6. [依赖分析](#依赖分析)
7. [性能考虑](#性能考虑)
8. [故障排查指南](#故障排查指南)
9. [结论](#结论)
10. [附录](#附录)

## 简介
本项目是一个基于LangGraph的AI内容生成引擎，专注于自动化生成结构化的书籍内容，涵盖从大纲规划、章节创作到音频/视频生成的完整工作流。系统采用策略模式灵活切换生成路径，结合容错机制、配额控制与状态机管理，确保在复杂场景下的稳定性与可扩展性。

## 项目结构
项目主要位于 `server/src/modules/book-generator` 目录下，围绕“策略-节点-状态”的三层架构组织：

- 策略层：通过 `strategies/` 管理不同的生成策略（串行、一步大纲+并行内容、逐章内聚）
- 节点层：通过 `nodes/` 实现具体的工作节点（大纲生成、章节内容生成等）
- 状态层：通过 `graph.ts` 定义LangGraph状态与进度管理
- 控制层：通过控制器暴露REST API，协调生成流程与批量任务
- 存储层：通过 `book-generator.store.ts` 封装数据库访问与状态推进
- 容错层：通过 `fault-tolerance.ts` 提供重试、超时与自动恢复能力

```mermaid
graph TB
subgraph "策略层"
S1["selector.ts<br/>策略选择器"]
S2["per-chapter.strategy.ts<br/>逐章内聚策略"]
S3["types.ts<br/>策略接口定义"]
end
subgraph "节点层"
N1["full-outline.node.ts<br/>一步大纲节点"]
N2["content.node.ts<br/>内容生成节点"]
end
subgraph "状态层"
G["graph.ts<br/>LangGraph状态定义"]
end
subgraph "控制层"
C1["book-generator.controller.ts<br/>批量生成API"]
C2["langgraph-controller.ts<br/>LangGraph主流程API"]
end
subgraph "存储层"
D["book-generator.store.ts<br/>数据库访问与树形结构构建"]
end
subgraph "容错层"
F["fault-tolerance.ts<br/>重试/超时/恢复"]
end
S1 --> S2
S2 --> N1
S2 --> N2
N1 --> G
N2 --> G
C1 --> D
C2 --> D
D --> F
```

**图表来源**
- [selector.ts:1-78](file://server/src/modules/book-generator/strategies/selector.ts#L1-L78)
- [per-chapter.strategy.ts:1-56](file://server/src/modules/book-generator/strategies/per-chapter.strategy.ts#L1-L56)
- [full-outline.node.ts:1-243](file://server/src/modules/book-generator/nodes/full-outline.node.ts#L1-L243)
- [content.node.ts:1-547](file://server/src/modules/book-generator/nodes/content.node.ts#L1-L547)
- [graph.ts:1-83](file://server/src/modules/book-generator/graph.ts#L1-L83)
- [book-generator.controller.ts:1-199](file://server/src/modules/book-generator/book-generator.controller.ts#L1-L199)
- [langgraph-controller.ts:1-800](file://server/src/modules/book-generator/langgraph-controller.ts#L1-L800)
- [book-generator.store.ts:1-800](file://server/src/modules/book-generator/book-generator.store.ts#L1-L800)
- [fault-tolerance.ts:1-379](file://server/src/modules/book-generator/fault-tolerance.ts#L1-L379)

**章节来源**
- [index.ts:1-104](file://server/src/modules/book-generator/index.ts#L1-L104)
- [graph.ts:1-83](file://server/src/modules/book-generator/graph.ts#L1-L83)

## 核心组件
- LangGraphBookGenerator：对外暴露的主入口，负责根据书籍规模与类型解析生成层级，并委派给当前策略执行
- BatchGenerationOrchestrator：批量生成编排器，串联内容生成、音频生成、音频合并、视频生成与视频合并五个阶段，并提供进度推送与取消机制
- 策略选择器：支持串行、一步大纲+并行内容、逐章内聚三种策略，可通过运行时切换
- LangGraph节点：包括一步大纲生成、内容生成等节点，负责具体的AI调用与状态推进
- 容错层：提供AI调用重试、节点超时控制、进度监控与自动恢复
- 存储层：封装数据库访问、树形大纲构建、章节状态推进与发布管理

**章节来源**
- [index.ts:60-104](file://server/src/modules/book-generator/index.ts#L60-L104)
- [book-generator.service.ts:45-143](file://server/src/modules/book-generator/book-generator.service.ts#L45-L143)
- [selector.ts:13-78](file://server/src/modules/book-generator/strategies/selector.ts#L13-L78)
- [per-chapter.strategy.ts:21-56](file://server/src/modules/book-generator/strategies/per-chapter.strategy.ts#L21-L56)
- [fault-tolerance.ts:17-47](file://server/src/modules/book-generator/fault-tolerance.ts#L17-L47)
- [book-generator.store.ts:163-332](file://server/src/modules/book-generator/book-generator.store.ts#L163-L332)

## 架构概览
系统采用“策略-节点-状态”三层架构，结合LangGraph实现多步骤工作流。策略层通过选择器动态切换；节点层负责具体步骤的执行；状态层通过Annotation定义状态与reducer，确保进度与状态的正确收敛。

```mermaid
classDiagram
class LangGraphBookGenerator {
+generate(bookId, topic, bookScale, genLevel) Promise~void~
}
class GenerationStrategy {
<<interface>>
+name StrategyName
+description string
+generate(bookId, topic, bookScale, genLevel) Promise~void~
}
class PerChapterStrategy {
+name "per-chapter"
+description "逐章内聚：先生成章大纲，然后每章独立并行生成结构+内容"
+generate(bookId, topic, bookScale, genLevel) Promise~void~
}
class GraphState {
+bookId string
+topic string
+bookScale string
+genLevel number
+progress number
+finished boolean
+error string
+completedChapters number[]
+failedChapters number[]
}
class FullOutlineNode {
+generateFullOutlineNode(state) Promise~Partial~State~~
}
class ContentNode {
+writeChaptersNode(state) Promise~Partial~State~~
+writeChaptersParallelNode(state) Promise~Partial~State~~
}
class BatchGenerationOrchestrator {
+execute() Promise~Result~
+setCancellationFlag(taskId) void
+clearCancellationFlag(taskId) void
+isTaskCancelled(taskId) boolean
}
class BookStore {
+create(data) Promise~Book~
+getById(id, filterPublic, userId) Promise~Book|null~
+update(id, data) Promise~Book|null~
+getChapterTree(bookId) Promise~any[]~
+updateChapterById(id, data) Promise~Chapter|null~
+generateChapterAudioById(chapterId, userId) Promise~Result~
}
class FaultTolerance {
+callLLMWithRetry(messages, modelId, context) Promise~string~
+executeNodeWithTimeout(fn, timeoutMs) Promise~T~
+startProgressMonitor(bookId) void
+attemptAutoRecovery(bookId) Promise~void~
}
LangGraphBookGenerator --> GenerationStrategy : "委派"
GenerationStrategy <|.. PerChapterStrategy : "实现"
PerChapterStrategy --> GraphState : "使用"
PerChapterStrategy --> FullOutlineNode : "调用"
PerChapterStrategy --> ContentNode : "调用"
BatchGenerationOrchestrator --> BookStore : "读写"
BatchGenerationOrchestrator --> FaultTolerance : "容错"
BookStore --> FaultTolerance : "配合"
```

**图表来源**
- [index.ts:60-104](file://server/src/modules/book-generator/index.ts#L60-L104)
- [types.ts:8-22](file://server/src/modules/book-generator/strategies/types.ts#L8-L22)
- [per-chapter.strategy.ts:21-56](file://server/src/modules/book-generator/strategies/per-chapter.strategy.ts#L21-L56)
- [graph.ts:23-82](file://server/src/modules/book-generator/graph.ts#L23-L82)
- [full-outline.node.ts:135-218](file://server/src/modules/book-generator/nodes/full-outline.node.ts#L135-L218)
- [content.node.ts:102-332](file://server/src/modules/book-generator/nodes/content.node.ts#L102-L332)
- [book-generator.service.ts:45-143](file://server/src/modules/book-generator/book-generator.service.ts#L45-L143)
- [book-generator.store.ts:163-332](file://server/src/modules/book-generator/book-generator.store.ts#L163-L332)
- [fault-tolerance.ts:64-176](file://server/src/modules/book-generator/fault-tolerance.ts#L64-L176)

## 详细组件分析

### LangGraphBookGenerator 与策略选择
- 作用：根据书籍规模与类型解析生成层级，委派给当前策略执行
- 关键点：
  - 书籍类型到生成层级映射
  - 规模配置与层级解析
  - 独立大纲生成函数（不依赖策略）

```mermaid
sequenceDiagram
participant Client as "客户端"
participant API as "LangGraph API"
participant Gen as "LangGraphBookGenerator"
participant Sel as "策略选择器"
participant Strat as "PerChapterStrategy"
participant Graph as "LangGraph工作流"
Client->>API : POST /api/book-generator/langgraph/books
API->>Gen : generate(bookId, topic, bookScale, genLevel)
Gen->>Sel : getCurrentStrategy()
Sel-->>Gen : PerChapterStrategy
Gen->>Strat : generate(...)
Strat->>Graph : 初始化状态与节点
Graph-->>Strat : 执行工作流
Strat-->>Gen : 完成
Gen-->>API : 返回结果
API-->>Client : 生成完成
```

**图表来源**
- [index.ts:60-104](file://server/src/modules/book-generator/index.ts#L60-L104)
- [selector.ts:58-60](file://server/src/modules/book-generator/strategies/selector.ts#L58-L60)
- [per-chapter.strategy.ts:33-54](file://server/src/modules/book-generator/strategies/per-chapter.strategy.ts#L33-L54)

**章节来源**
- [index.ts:24-51](file://server/src/modules/book-generator/index.ts#L24-L51)
- [index.ts:84-104](file://server/src/modules/book-generator/index.ts#L84-L104)

### LangGraph 状态与进度管理
- 状态定义：通过Annotation定义bookId、topic、bookScale、genLevel、progress、finished、error、completedChapters、failedChapters等字段
- Reducer策略：
  - 进度与章节数只增不减，防止回退导致状态丢失
  - 失败章节列表合并而非覆盖
- 用途：作为LangGraph工作流的共享状态，贯穿整个生成过程

```mermaid
flowchart TD
Start(["初始化状态"]) --> SetFields["设置基础字段<br/>bookId/topic/bookScale/genLevel"]
SetFields --> InitProgress["初始化进度与完成状态"]
InitProgress --> RunNodes["执行节点<br/>逐步更新状态"]
RunNodes --> ProgressUpdate{"进度是否增加？"}
ProgressUpdate --> |是| UpdateMax["使用maxReducer<br/>只增不减"]
ProgressUpdate --> |否| KeepPrev["保持原值"]
UpdateMax --> NextNode["下一个节点"]
KeepPrev --> NextNode
NextNode --> Finished{"finished为true？"}
Finished --> |是| End(["结束"])
Finished --> |否| RunNodes
```

**图表来源**
- [graph.ts:12-21](file://server/src/modules/book-generator/graph.ts#L12-L21)
- [graph.ts:23-82](file://server/src/modules/book-generator/graph.ts#L23-L82)

**章节来源**
- [graph.ts:9-82](file://server/src/modules/book-generator/graph.ts#L9-L82)

### 一步大纲生成节点（fullOutlineNode）
- 目标：一次AI调用生成完整树形大纲（章→节→小节）
- 关键流程：
  - 构建提示词（包含层级约束、字数预算、规划参考）
  - 调用LLM并解析JSON
  - 将大纲持久化到数据库，同时创建各级章节记录
- 容错：带超时与重试包装，失败时标记失败阶段

```mermaid
sequenceDiagram
participant Node as "fullOutlineNode"
participant LLM as "LLM调用"
participant Store as "BookStore"
participant FT as "容错层"
Node->>FT : executeNodeWithTimeout(...)
FT->>LLM : callLLMWithRetry(buildFullOutlinePrompt,...)
LLM-->>FT : JSON大纲
FT-->>Node : 大纲数据
Node->>Store : update(bookId, outlineJson, progress)
Node->>Store : createChapters/Items(各级章节)
Node-->>Node : 返回进度完成
```

**图表来源**
- [full-outline.node.ts:135-218](file://server/src/modules/book-generator/nodes/full-outline.node.ts#L135-L218)
- [fault-tolerance.ts:127-176](file://server/src/modules/book-generator/fault-tolerance.ts#L127-L176)

**章节来源**
- [full-outline.node.ts:18-108](file://server/src/modules/book-generator/nodes/full-outline.node.ts#L18-L108)
- [full-outline.node.ts:135-218](file://server/src/modules/book-generator/nodes/full-outline.node.ts#L135-L218)

### 内容生成节点（content.node）
- 目标：为所有叶节点生成正文内容
- 并行策略：使用AsyncPool并发生成，提升吞吐
- 安全机制：
  - 配额检查与消耗
  - 字数预算与上限保护
  - 智能截断与内容清洗
- 状态推进：通过advanceChapter/regenerateChapter安全推进/回退状态

```mermaid
flowchart TD
Start(["开始内容生成"]) --> FindLeaves["查找叶节点"]
FindLeaves --> FilterTargets["过滤未完成目标"]
FilterTargets --> Loop{"遍历目标"}
Loop --> |检查配额| QuotaCheck["checkQuotaForWords"]
QuotaCheck --> |不足| Interrupt["中断生成并标记"]
QuotaCheck --> |充足| BuildMsg["构建消息短文/长篇"]
BuildMsg --> CallLLM["LLM调用工具/非工具"]
CallLLM --> Clean["内容清洗与截断"]
Clean --> Consume["消耗音频分钟配额"]
Consume --> Save["保存内容并推进状态"]
Save --> Loop
Loop --> |完成| Done(["完成"])
```

**图表来源**
- [content.node.ts:102-332](file://server/src/modules/book-generator/nodes/content.node.ts#L102-L332)
- [content.node.ts:445-547](file://server/src/modules/book-generator/nodes/content.node.ts#L445-L547)

**章节来源**
- [content.node.ts:19-55](file://server/src/modules/book-generator/nodes/content.node.ts#L19-L55)
- [content.node.ts:102-332](file://server/src/modules/book-generator/nodes/content.node.ts#L102-L332)
- [content.node.ts:445-547](file://server/src/modules/book-generator/nodes/content.node.ts#L445-L547)

### 批量生成编排器（BatchGenerationOrchestrator）
- 职责：串行执行内容生成、音频生成、音频合并、视频生成、视频合并五个阶段
- 进度：每个阶段推进进度并推送WebSocket消息
- 取消：支持任务取消标志，及时终止执行
- 超时：各阶段内置轮询检查与超时控制

```mermaid
sequenceDiagram
participant Orchestrator as "编排器"
participant Store as "BookStore"
participant LLM as "LangGraph生成"
participant TTS as "TTS服务"
participant Merge as "合并服务"
participant WS as "WebSocket"
Orchestrator->>WS : 推送阶段开始
Orchestrator->>Store : 获取书籍与章节树
Orchestrator->>LLM : 异步启动LangGraph生成
Orchestrator->>Store : 轮询检查内容完成
Orchestrator->>TTS : 生成音频并行
Orchestrator->>Merge : 合并音频/视频
Orchestrator->>WS : 推送阶段完成
Orchestrator-->>Orchestrator : 返回结果
```

**图表来源**
- [book-generator.service.ts:45-143](file://server/src/modules/book-generator/book-generator.service.ts#L45-L143)
- [book-generator.service.ts:149-217](file://server/src/modules/book-generator/book-generator.service.ts#L149-L217)
- [book-generator.service.ts:222-285](file://server/src/modules/book-generator/book-generator.service.ts#L222-L285)
- [book-generator.service.ts:289-359](file://server/src/modules/book-generator/book-generator.service.ts#L289-L359)
- [book-generator.service.ts:363-453](file://server/src/modules/book-generator/book-generator.service.ts#L363-L453)
- [book-generator.service.ts:458-528](file://server/src/modules/book-generator/book-generator.service.ts#L458-L528)

**章节来源**
- [book-generator.service.ts:45-143](file://server/src/modules/book-generator/book-generator.service.ts#L45-L143)

### API 接口文档
- LangGraph主流程API
  - POST /api/book-generator/langgraph/books：创建并生成书籍（异步/同步）
  - GET /api/book-generator/langgraph/books/{id}/progress：获取生成进度
  - POST /api/book-generator/langgraph/books/{id}/generate：对已有书籍再次生成
  - GET /api/book-generator/langgraph/estimate：书籍规模预估
  - POST /api/book-generator/langgraph/detect-book-type：AI自动检测书籍类型
  - POST /api/book-generator/langgraph/smart-recommend：智能推荐难度/人群/风格/领域
- 批量生成API
  - POST /api/book-generator/books/{id}/batch-generate：一键完整生成（内容、音频、合并、生成视频、合并视频）
  - POST /api/book-generator/books/{id}/batch-generate/cancel：取消批量生成任务
  - GET /api/book-generator/books/{id}/batch-generate/status：查询批量生成任务状态

**章节来源**
- [langgraph-controller.ts:378-530](file://server/src/modules/book-generator/langgraph-controller.ts#L378-L530)
- [langgraph-controller.ts:657-698](file://server/src/modules/book-generator/langgraph-controller.ts#L657-L698)
- [book-generator.controller.ts:24-119](file://server/src/modules/book-generator/book-generator.controller.ts#L24-L119)
- [book-generator.controller.ts:125-197](file://server/src/modules/book-generator/book-generator.controller.ts#L125-L197)

## 依赖分析
- 组件耦合
  - 策略层与节点层松耦合：策略通过StateGraph组合节点，便于替换与扩展
  - 存储层与状态层强耦合：状态推进依赖存储层的乐观锁与清理规则
  - 容错层横切关注：为LLM调用与节点执行提供统一的重试与超时机制
- 外部依赖
  - LangGraph：工作流与状态管理
  - Prisma：数据库ORM与事务
  - WebSocket：进度推送
  - TTS/视频生成服务：内容产物生成

```mermaid
graph TB
Strat["策略层"] --> Nodes["节点层"]
Nodes --> State["状态层"]
Orchestrator["编排器"] --> Store["存储层"]
Orchestrator --> FT["容错层"]
Store --> DB["数据库"]
Orchestrator --> WS["WebSocket"]
```

**图表来源**
- [selector.ts:13-17](file://server/src/modules/book-generator/strategies/selector.ts#L13-L17)
- [per-chapter.strategy.ts:33-40](file://server/src/modules/book-generator/strategies/per-chapter.strategy.ts#L33-L40)
- [book-generator.service.ts:45-143](file://server/src/modules/book-generator/book-generator.service.ts#L45-L143)
- [fault-tolerance.ts:17-47](file://server/src/modules/book-generator/fault-tolerance.ts#L17-L47)

**章节来源**
- [selector.ts:13-78](file://server/src/modules/book-generator/strategies/selector.ts#L13-L78)
- [per-chapter.strategy.ts:33-56](file://server/src/modules/book-generator/strategies/per-chapter.strategy.ts#L33-L56)
- [book-generator.service.ts:45-143](file://server/src/modules/book-generator/book-generator.service.ts#L45-L143)

## 性能考虑
- 并行策略：内容生成节点支持并发池，显著提升长篇书籍生成效率
- 节点超时：为不同节点设置合理的超时阈值，避免长时间阻塞
- 进度监控：长时间无响应时自动告警并尝试恢复
- 配额控制：在生成前检查用户配额，避免无效调用
- 缓存与重用：工具调用可复用已生成内容摘要，减少重复生成

[本节为通用性能建议，无需特定文件引用]

## 故障排查指南
- 常见问题
  - 生成超时：检查节点超时配置与网络状况，必要时启用自动恢复
  - 额度不足：检查用户配额与累计字数，适当调整生成规模
  - 状态冲突：通过安全转移函数与乐观锁避免并发写入冲突
- 调试方法
  - 启用进度监控，观察长时间无响应任务
  - 查看容错日志，定位失败原因与重试次数
  - 通过WebSocket轮询获取实时进度与错误信息

**章节来源**
- [fault-tolerance.ts:184-257](file://server/src/modules/book-generator/fault-tolerance.ts#L184-L257)
- [fault-tolerance.ts:264-319](file://server/src/modules/book-generator/fault-tolerance.ts#L264-L319)
- [stage-manager.ts:100-147](file://server/src/modules/book-generator/stage-manager.ts#L100-L147)

## 结论
本AI内容生成引擎通过策略化设计与LangGraph工作流，实现了从大纲规划到内容创作再到多媒体产物的完整自动化。结合容错机制、配额控制与状态机管理，系统在复杂场景下具备良好的稳定性与可扩展性。建议在生产环境中持续优化并发参数、监控指标与成本控制策略，以获得最佳的生成体验。

[本节为总结性内容，无需特定文件引用]

## 附录

### 提示词工程与模型调用策略
- 动态提示词组装：根据书籍类型、目标读者、内容深度、行业领域与特殊需求动态拼装系统提示词
- 工具调用：通过LLM工具集获取已生成章节摘要与大纲，避免重复与风格不一致
- 模型调用：支持工具调用与普通消息两种模式，失败时自动降级

**章节来源**
- [builder.ts:69-137](file://server/src/modules/book-generator/prompts/builder.ts#L69-L137)
- [builder.ts:185-240](file://server/src/modules/book-generator/prompts/builder.ts#L185-L240)
- [book-tools.ts:19-103](file://server/src/services/llm/book-tools.ts#L19-L103)
- [content.node.ts:240-249](file://server/src/modules/book-generator/nodes/content.node.ts#L240-L249)

### 错误处理与状态管理机制
- 容错层：AI调用重试、节点超时、进度监控与自动恢复
- 状态机：章节线性阶段推进，支持安全转移与资源清理
- 失败回退：通过regenerateChapter实现失败章节的回退与重试

**章节来源**
- [fault-tolerance.ts:64-176](file://server/src/modules/book-generator/fault-tolerance.ts#L64-L176)
- [stage-manager.ts:158-198](file://server/src/modules/book-generator/stage-manager.ts#L158-L198)

### API 使用示例
- 创建并生成书籍：POST /api/book-generator/langgraph/books
- 获取生成进度：GET /api/book-generator/langgraph/books/{id}/progress
- 一键完整生成：POST /api/book-generator/books/{id}/batch-generate
- 取消任务：POST /api/book-generator/books/{id}/batch-generate/cancel

**章节来源**
- [langgraph-controller.ts:378-530](file://server/src/modules/book-generator/langgraph-controller.ts#L378-L530)
- [book-generator.controller.ts:24-119](file://server/src/modules/book-generator/book-generator.controller.ts#L24-L119)