# AI书籍生成引擎

<cite>
**本文档引用的文件**
- [index.ts](file://server/src/modules/book-generator/index.ts)
- [graph.ts](file://server/src/modules/book-generator/graph.ts)
- [stage-manager.ts](file://server/src/modules/book-generator/stage-manager.ts)
- [book-generator.store.ts](file://server/src/modules/book-generator/book-generator.store.ts)
- [book-generator.service.ts](file://server/src/modules/book-generator/book-generator.service.ts)
- [selector.ts](file://server/src/modules/book-generator/strategies/selector.ts)
- [full-outline.node.ts](file://server/src/modules/book-generator/nodes/full-outline.node.ts)
- [templates.ts](file://server/src/modules/book-generator/prompts/templates.ts)
- [book-generator.types.ts](file://server/src/modules/book-generator/book-generator.types.ts)
- [deep-plan-parallel.strategy.ts](file://server/src/modules/book-generator/strategies/deep-plan-parallel.strategy.ts)
- [fault-tolerance.ts](file://server/src/modules/book-generator/fault-tolerance.ts)
- [utils.ts](file://server/src/modules/book-generator/utils.ts)
- [book-type-config.ts](file://server/src/modules/book-generator/book-type-config.ts)
- [book-tools.ts](file://server/src/services/llm/book-tools.ts)
</cite>

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

## 简介
本项目是一个基于LangGraph的AI书籍生成引擎，提供从“书籍规划→大纲生成→内容创作→媒体合成”的全流程自动化能力。系统采用策略门面模式，支持多种生成策略（串行、一步大纲+并行内容、逐章内聚、DeepPlan+富大纲+并发+连贯性编辑），并通过阶段管理器、存储层、容错层与进度监控，确保大规模生成任务的稳定性与可观测性。

## 项目结构
- 服务端核心位于 server/src/modules/book-generator，包含：
  - 策略系统：strategies/selector.ts、deep-plan-parallel.strategy.ts 等
  - LangGraph工作流：graph.ts、nodes/*、prompts/templates.ts
  - 存储与阶段管理：book-generator.store.ts、stage-manager.ts
  - 批量编排与进度：book-generator.service.ts
  - 容错与监控：fault-tolerance.ts
  - 工具与配置：book-tools.ts、book-type-config.ts、utils.ts、book-generator.types.ts
- 前端位于 my-uniapp-vue3，提供书籍生成界面与状态展示

```mermaid
graph TB
subgraph "策略层"
S1["策略选择器<br/>selector.ts"]
S2["DeepPlan+并行策略<br/>deep-plan-parallel.strategy.ts"]
end
subgraph "LangGraph工作流"
G1["状态定义<br/>graph.ts"]
N1["一步大纲节点<br/>full-outline.node.ts"]
P1["提示词模板<br/>prompts/templates.ts"]
end
subgraph "编排与存储"
B1["批量编排器<br/>book-generator.service.ts"]
ST["阶段管理器<br/>stage-manager.ts"]
DS["存储层<br/>book-generator.store.ts"]
end
subgraph "容错与工具"
FT["容错层<br/>fault-tolerance.ts"]
BT["LLM工具集<br/>book-tools.ts"]
CFG["类型配置<br/>book-type-config.ts"]
end
S1 --> S2
S2 --> G1
G1 --> N1
N1 --> P1
B1 --> DS
B1 --> ST
DS --> FT
DS --> BT
DS --> CFG
```

**图表来源**
- [selector.ts:1-81](file://server/src/modules/book-generator/strategies/selector.ts#L1-L81)
- [deep-plan-parallel.strategy.ts:1-74](file://server/src/modules/book-generator/strategies/deep-plan-parallel.strategy.ts#L1-L74)
- [graph.ts:1-83](file://server/src/modules/book-generator/graph.ts#L1-L83)
- [full-outline.node.ts:1-243](file://server/src/modules/book-generator/nodes/full-outline.node.ts#L1-L243)
- [templates.ts:1-361](file://server/src/modules/book-generator/prompts/templates.ts#L1-L361)
- [book-generator.service.ts:1-549](file://server/src/modules/book-generator/book-generator.service.ts#L1-L549)
- [stage-manager.ts:1-202](file://server/src/modules/book-generator/stage-manager.ts#L1-L202)
- [book-generator.store.ts:1-800](file://server/src/modules/book-generator/book-generator.store.ts#L1-L800)
- [fault-tolerance.ts:1-387](file://server/src/modules/book-generator/fault-tolerance.ts#L1-L387)
- [book-tools.ts:1-104](file://server/src/services/llm/book-tools.ts#L1-L104)
- [book-type-config.ts:1-133](file://server/src/modules/book-generator/book-type-config.ts#L1-L133)

**章节来源**
- [index.ts:1-119](file://server/src/modules/book-generator/index.ts#L1-L119)
- [book-generator.types.ts:1-226](file://server/src/modules/book-generator/book-generator.types.ts#L1-L226)

## 核心组件
- 策略门面与主生成器：LangGraphBookGenerator，负责根据书籍规模与话题推断大纲层级，调用当前策略执行生成
- LangGraph状态与节点：GraphState定义状态字段；full-outline.node.ts等节点实现“一步大纲生成”等步骤
- 存储层：BookStore封装数据库读写、树形大纲构建、章节批量创建与更新、音频/视频生成与关联
- 阶段管理器：线性阶段模型与安全转移，支持前进与回退（regenerate），并自动清理下游资源
- 批量编排器：BatchGenerationOrchestrator，按步骤顺序执行内容生成、音频生成、音频合并、视频生成、视频合并，并推送进度
- 容错层：AI调用重试、节点超时、进度监控、自动恢复
- 提示词模板与工具：templates.ts提供系统提示词；book-tools.ts提供LLM工具（获取大纲、已写章节、问题上报）

**章节来源**
- [index.ts:74-119](file://server/src/modules/book-generator/index.ts#L74-L119)
- [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)
- [book-generator.store.ts:163-800](file://server/src/modules/book-generator/book-generator.store.ts#L163-L800)
- [stage-manager.ts:100-198](file://server/src/modules/book-generator/stage-manager.ts#L100-L198)
- [book-generator.service.ts:45-549](file://server/src/modules/book-generator/book-generator.service.ts#L45-L549)
- [fault-tolerance.ts:17-387](file://server/src/modules/book-generator/fault-tolerance.ts#L17-L387)
- [templates.ts:1-361](file://server/src/modules/book-generator/prompts/templates.ts#L1-L361)
- [book-tools.ts:19-104](file://server/src/services/llm/book-tools.ts#L19-L104)

## 架构总览
系统采用“策略门面 + LangGraph工作流 + 编排器 + 存储/阶段/容错”的分层架构。策略门面根据输入选择具体工作流；LangGraph节点负责AI提示词工程与内容生成；编排器负责跨阶段的协调与进度推送；存储层负责持久化与树形大纲构建；阶段管理器保证状态机安全；容错层提供鲁棒性保障。

```mermaid
sequenceDiagram
participant U as "用户"
participant API as "API控制器"
participant GEN as "LangGraphBookGenerator"
participant STR as "策略选择器"
participant WF as "LangGraph工作流"
participant NODE as "大纲/内容节点"
participant STORE as "BookStore"
participant STAGE as "阶段管理器"
U->>API : "提交生成任务"
API->>GEN : "generate(bookId, topic, scale, genLevel)"
GEN->>STR : "getCurrentStrategy()"
STR-->>GEN : "返回策略实例"
GEN->>WF : "runGraphWorkflow(initialState)"
WF->>NODE : "执行节点如full-outline"
NODE->>STORE : "写入大纲/章节记录"
NODE-->>WF : "返回状态更新"
WF->>STAGE : "推进章节/书籍阶段"
WF-->>GEN : "完成一轮节点"
GEN-->>API : "异步生成中"
API-->>U : "返回任务ID/进度"
```

**图表来源**
- [index.ts:74-91](file://server/src/modules/book-generator/index.ts#L74-L91)
- [selector.ts:61-77](file://server/src/modules/book-generator/strategies/selector.ts#L61-L77)
- [deep-plan-parallel.strategy.ts:44-71](file://server/src/modules/book-generator/strategies/deep-plan-parallel.strategy.ts#L44-L71)
- [full-outline.node.ts:135-218](file://server/src/modules/book-generator/nodes/full-outline.node.ts#L135-L218)
- [book-generator.store.ts:163-239](file://server/src/modules/book-generator/book-generator.store.ts#L163-L239)
- [stage-manager.ts:158-198](file://server/src/modules/book-generator/stage-manager.ts#L158-L198)

## 详细组件分析

### LangGraph工作流与状态
- 状态字段：包含书籍ID、用户ID、主题、规模、大纲层级、描述、规划结果、当前/已完成章节、完成标志、错误信息、进度、失败章节列表等
- 进度reducer：只增不减，防止回退丢失进度
- 节点：full-outline.node.ts实现“一步生成完整大纲”，并写入数据库（章→节→小节）

```mermaid
flowchart TD
Start(["开始"]) --> Init["初始化GraphState<br/>bookId/topic/scale/genLevel"]
Init --> Run["执行节点：full-outline"]
Run --> Parse["解析JSON大纲"]
Parse --> Save["写入outlineJson与章节记录"]
Save --> Next["推进进度/完成标志"]
Next --> End(["结束"])
```

**图表来源**
- [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)

**章节来源**
- [graph.ts:9-82](file://server/src/modules/book-generator/graph.ts#L9-L82)
- [full-outline.node.ts:18-108](file://server/src/modules/book-generator/nodes/full-outline.node.ts#L18-L108)

### 策略系统与门面
- 策略注册：sequential、one-step-outline、per-chapter、deep-plan-parallel
- 门面类：LangGraphBookGenerator.generate(bookId, topic, bookScale, genLevel?)，内部解析genLevel并调用当前策略
- 推荐策略：deep-plan-parallel，包含深度规划→富大纲→并发内容→连贯性编辑

```mermaid
classDiagram
class LangGraphBookGenerator {
+generate(bookId, topic, bookScale, genLevel)
}
class StrategySelector {
+getCurrentStrategy()
+setCurrentStrategy(name)
+getAllStrategies()
}
class DeepPlanParallelStrategy {
+generate(bookId, topic, bookScale, genLevel)
}
LangGraphBookGenerator --> StrategySelector : "使用"
StrategySelector --> DeepPlanParallelStrategy : "返回实例"
```

**图表来源**
- [index.ts:74-91](file://server/src/modules/book-generator/index.ts#L74-L91)
- [selector.ts:14-77](file://server/src/modules/book-generator/strategies/selector.ts#L14-L77)
- [deep-plan-parallel.strategy.ts:32-73](file://server/src/modules/book-generator/strategies/deep-plan-parallel.strategy.ts#L32-L73)

**章节来源**
- [index.ts:23-65](file://server/src/modules/book-generator/index.ts#L23-L65)
- [selector.ts:14-77](file://server/src/modules/book-generator/strategies/selector.ts#L14-L77)
- [deep-plan-parallel.strategy.ts:32-73](file://server/src/modules/book-generator/strategies/deep-plan-parallel.strategy.ts#L32-L73)

### 存储机制与树形大纲
- 存储类：BookStore封装创建/查询/更新/删除书籍与章节，批量创建章节（upsert），章节树构建
- 树形结构：按level与number排序，支持章→节→小节三层
- 大纲构建：从数据库章节记录重建BookOutline，优先使用数据库构建的树

```mermaid
erDiagram
BOOK {
int id PK
string title
string description
string bookScale
int totalChapters
int estimatedWords
string genStage
int progress
}
BOOK_CHAPTER {
int id PK
int bookId FK
int number
string title
string summary
string keyPoints
int estimatedWords
int level
int parentId
string genStage
string audioUrl
float audioDuration
string videoUrl
float videoDuration
}
BOOK ||--o{ BOOK_CHAPTER : "包含"
```

**图表来源**
- [book-generator.store.ts:244-331](file://server/src/modules/book-generator/book-generator.store.ts#L244-L331)
- [book-generator.store.ts:179-239](file://server/src/modules/book-generator/book-generator.store.ts#L179-L239)

**章节来源**
- [book-generator.store.ts:163-800](file://server/src/modules/book-generator/book-generator.store.ts#L163-L800)

### 阶段管理器与状态机
- 章节阶段：idle → outline_completed → content_generating → content_completed → audio_generating → audio_completed → video_generating → video_completed → failed
- 安全转移：验证转移矩阵、乐观锁、回退时自动清理下游资源（音频/视频URL与时长）
- 书籍阶段：由最低阶段（最落后章节）决定

```mermaid
stateDiagram-v2
[*] --> idle
idle --> outline_completed : "大纲完成"
outline_completed --> content_generating : "开始内容生成"
content_generating --> content_completed : "内容完成"
content_completed --> audio_generating : "开始音频生成"
audio_generating --> audio_completed : "音频完成"
audio_completed --> video_generating : "开始视频生成"
video_generating --> video_completed : "视频完成"
content_generating --> failed : "失败"
audio_generating --> failed : "失败"
video_generating --> failed : "失败"
failed --> content_generating : "重新生成"
failed --> audio_generating : "重新生成"
failed --> video_generating : "重新生成"
failed --> idle : "重置"
```

**图表来源**
- [stage-manager.ts:13-49](file://server/src/modules/book-generator/stage-manager.ts#L13-L49)
- [stage-manager.ts:100-198](file://server/src/modules/book-generator/stage-manager.ts#L100-L198)

**章节来源**
- [stage-manager.ts:100-198](file://server/src/modules/book-generator/stage-manager.ts#L100-L198)

### 批量生成编排器
- 步骤：generate_content → generate_audio → merge_audio → generate_video → merge_video
- 进度：通过WebSocket推送，包含步骤名、百分比与消息
- 轮询检查：等待内容/音频/视频生成完成，设置最大等待时间
- 取消机制：支持设置/检查/清理取消标志

```mermaid
sequenceDiagram
participant Orchestrator as "批量编排器"
participant Store as "BookStore"
participant LLM as "LangGraph生成"
participant Stage as "阶段管理器"
Orchestrator->>Store : "获取书籍/章节树"
Orchestrator->>LLM : "异步启动内容生成"
Orchestrator->>Store : "轮询检查完成状态"
Orchestrator->>Stage : "推进章节/书籍阶段"
Orchestrator-->>Orchestrator : "推送进度"
```

**图表来源**
- [book-generator.service.ts:45-549](file://server/src/modules/book-generator/book-generator.service.ts#L45-L549)

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

### 容错与监控
- AI调用重试：最多3次，指数退避，失败记录到errorMsg
- 节点超时：不同节点设定超时阈值，超时通知用户并触发恢复
- 进度监控：超过10分钟无进度发出警告，建议干预或自动恢复
- 自动恢复：重新加入队列，最多尝试2次

```mermaid
flowchart TD
A["开始节点"] --> B["callLLMWithRetry<br/>重试+退避"]
B --> C{"成功?"}
C -- 否 --> D["记录失败到errorMsg"]
D --> E["通知用户AI失败"]
E --> F["尝试自动恢复"]
F --> G["重新加入队列"]
C -- 是 --> H["executeNodeWithTimeout<br/>超时控制"]
H --> I{"超时?"}
I -- 是 --> J["通知节点超时"]
J --> K["尝试自动恢复"]
I -- 否 --> L["正常完成"]
```

**图表来源**
- [fault-tolerance.ts:68-180](file://server/src/modules/book-generator/fault-tolerance.ts#L68-L180)
- [fault-tolerance.ts:188-323](file://server/src/modules/book-generator/fault-tolerance.ts#L188-L323)

**章节来源**
- [fault-tolerance.ts:17-387](file://server/src/modules/book-generator/fault-tolerance.ts#L17-L387)

### 提示词工程与工具调用
- 提示词模板：大纲/章节/小节/前言/后记系统提示词，严格格式约束
- LLM工具：get_existing_chapters、get_book_outline、report_chapter_issue，支持在生成过程中动态获取上下文与反馈

**章节来源**
- [templates.ts:1-361](file://server/src/modules/book-generator/prompts/templates.ts#L1-L361)
- [book-tools.ts:19-104](file://server/src/services/llm/book-tools.ts#L19-L104)

## 依赖分析
- 组件耦合
  - 策略门面依赖策略选择器；策略实现依赖LangGraph与节点
  - 编排器依赖存储层与阶段管理器；存储层依赖Prisma与LLM服务
  - 容错层横切多个模块，提供统一的重试/超时/监控能力
- 外部依赖
  - LangGraph：状态图与节点执行
  - Prisma：数据库访问
  - WebSocket：进度推送
  - LLM服务：提示词调用与工具调用

```mermaid
graph LR
Index["index.ts"] --> Sel["strategies/selector.ts"]
Sel --> Strat["deep-plan-parallel.strategy.ts"]
Strat --> Graph["graph.ts"]
Graph --> Nodes["nodes/*.ts"]
Nodes --> Templates["prompts/templates.ts"]
Index --> Store["book-generator.store.ts"]
Store --> Stage["stage-manager.ts"]
Store --> FT["fault-tolerance.ts"]
Store --> Tools["book-tools.ts"]
Orchestrator["book-generator.service.ts"] --> Store
Orchestrator --> Stage
```

**图表来源**
- [index.ts:18-91](file://server/src/modules/book-generator/index.ts#L18-L91)
- [selector.ts:6-77](file://server/src/modules/book-generator/strategies/selector.ts#L6-L77)
- [deep-plan-parallel.strategy.ts:23-71](file://server/src/modules/book-generator/strategies/deep-plan-parallel.strategy.ts#L23-L71)
- [graph.ts:5-82](file://server/src/modules/book-generator/graph.ts#L5-L82)
- [full-outline.node.ts:7-13](file://server/src/modules/book-generator/nodes/full-outline.node.ts#L7-L13)
- [templates.ts:1-42](file://server/src/modules/book-generator/prompts/templates.ts#L1-L42)
- [book-generator.store.ts:5-13](file://server/src/modules/book-generator/book-generator.store.ts#L5-L13)
- [stage-manager.ts:6-8](file://server/src/modules/book-generator/stage-manager.ts#L6-L8)
- [fault-tolerance.ts:11-13](file://server/src/modules/book-generator/fault-tolerance.ts#L11-L13)
- [book-tools.ts:10-11](file://server/src/services/llm/book-tools.ts#L10-L11)
- [book-generator.service.ts:6-13](file://server/src/modules/book-generator/book-generator.service.ts#L6-L13)

**章节来源**
- [index.ts:18-91](file://server/src/modules/book-generator/index.ts#L18-L91)
- [book-generator.service.ts:6-13](file://server/src/modules/book-generator/book-generator.service.ts#L6-L13)

## 性能考虑
- 并行策略：deep-plan-parallel通过“并行内容生成”显著缩短总耗时
- 节点超时与重试：避免单点阻塞，提高吞吐
- 进度只增不减：减少无效回退带来的重复计算
- upsert批量创建：避免唯一约束冲突，降低写入竞争
- 音频/视频合并：按父节点分组，减少I/O与状态切换

[本节为通用性能讨论，无需列出章节来源]

## 故障排查指南
- AI调用失败
  - 现象：节点执行超时或最终失败
  - 处理：查看errorMsg记录，确认重试次数；必要时触发自动恢复
- 生成卡住
  - 现象：长时间无进度更新
  - 处理：检查进度监控日志；若达到临界值，系统会尝试自动恢复
- 章节状态异常
  - 现象：状态冲突或回退失败
  - 处理：使用regenerateChapter回退到上游阶段；系统会自动清理下游资源
- 音频/视频生成失败
  - 现象：叶节点音频/视频URL为空
  - 处理：检查对应章节内容与genStage；必要时重新生成

**章节来源**
- [fault-tolerance.ts:188-323](file://server/src/modules/book-generator/fault-tolerance.ts#L188-L323)
- [stage-manager.ts:100-198](file://server/src/modules/book-generator/stage-manager.ts#L100-L198)
- [book-generator.service.ts:222-453](file://server/src/modules/book-generator/book-generator.service.ts#L222-L453)

## 结论
本引擎通过策略门面与LangGraph工作流实现了可插拔的生成策略；通过阶段管理器与存储层确保状态一致性与数据完整性；通过容错层与监控保障大规模任务的稳定性；通过提示词工程与工具调用提升内容质量与可控性。推荐使用deep-plan-parallel策略以获得最佳的并发与质量平衡。

[本节为总结性内容，无需列出章节来源]

## 附录

### 如何启动生成任务
- 通过API提交生成请求，传入bookId、topic、bookScale与可选genLevel
- 引擎将根据策略与提示词生成大纲与内容，并推进阶段状态
- 前端可通过WebSocket轮询进度

**章节来源**
- [index.ts:74-91](file://server/src/modules/book-generator/index.ts#L74-L91)
- [book-generator.service.ts:149-217](file://server/src/modules/book-generator/book-generator.service.ts#L149-L217)

### 如何监控生成进度
- 编排器在每个步骤开始与结束时推送进度
- 进度包含步骤名、百分比与消息
- 若长时间无更新，系统会发出警告并尝试自动恢复

**章节来源**
- [book-generator.service.ts:59-142](file://server/src/modules/book-generator/book-generator.service.ts#L59-L142)
- [fault-tolerance.ts:188-261](file://server/src/modules/book-generator/fault-tolerance.ts#L188-L261)

### 如何处理生成失败
- AI调用失败：重试+记录错误；最终失败时推进到failed阶段
- 节点超时：通知用户并尝试自动恢复
- 章节失败：使用regenerateChapter回退到上游阶段，清理下游资源

**章节来源**
- [fault-tolerance.ts:68-180](file://server/src/modules/book-generator/fault-tolerance.ts#L68-L180)
- [stage-manager.ts:100-198](file://server/src/modules/book-generator/stage-manager.ts#L100-L198)

### 与AI模型的集成方式
- 通过callLLMWithMessages发送消息
- 通过callLLMWithRetry实现重试与退避
- 通过createBookTools提供工具调用（获取大纲、已写章节、问题上报）

**章节来源**
- [full-outline.node.ts:149-160](file://server/src/modules/book-generator/nodes/full-outline.node.ts#L149-L160)
- [book-tools.ts:19-104](file://server/src/services/llm/book-tools.ts#L19-L104)
- [fault-tolerance.ts:68-123](file://server/src/modules/book-generator/fault-tolerance.ts#L68-L123)

### 提示词工程与质量控制
- 严格格式约束：系统提示词要求返回合法JSON，禁止markdown与标签
- 写作指令：富信息大纲为每个节点附加writingInstructions，提升内容一致性
- 连贯性编辑：全局检查章节过渡、重复、术语统一与风格一致

**章节来源**
- [templates.ts:10-42](file://server/src/modules/book-generator/prompts/templates.ts#L10-L42)
- [templates.ts:241-318](file://server/src/modules/book-generator/prompts/templates.ts#L241-L318)
- [templates.ts:324-361](file://server/src/modules/book-generator/prompts/templates.ts#L324-L361)