# 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)
- [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)
- [stage-manager.ts](file://server/src/modules/book-generator/stage-manager.ts)
- [fault-tolerance.ts](file://server/src/modules/book-generator/fault-tolerance.ts)
- [utils.ts](file://server/src/modules/book-generator/utils.ts)
- [book-generator.types.ts](file://server/src/modules/book-generator/book-generator.types.ts)
</cite>

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

## 简介
本项目实现了基于LangGraph的AI内容生成功能，支持从主题输入到书籍大纲、章节内容的全流程自动化生成，并提供批量生成、异步处理、进度跟踪与错误恢复能力。系统采用策略模式选择不同的生成路径，结合容错层保障稳定性，通过阶段管理器确保生成流程的线性可控与可回溯。

## 项目结构
围绕“书籍生成”模块，主要文件分布如下：
- 策略与入口：index.ts、strategies/selector.ts
- LangGraph状态与工作流：graph.ts
- 节点实现：nodes/full-outline.node.ts、nodes/content.node.ts
- 提示词工程：prompts/builder.ts
- 存储与类型：book-generator.store.ts、book-generator.types.ts
- 编排与API：book-generator.service.ts、book-generator.controller.ts、langgraph-controller.ts
- 阶段管理与容错：stage-manager.ts、fault-tolerance.ts
- 工具与进度：utils.ts

```mermaid
graph TB
subgraph "策略与入口"
IDX["index.ts<br/>主入口与策略门面"]
SEL["strategies/selector.ts<br/>策略选择器"]
end
subgraph "LangGraph"
GR["graph.ts<br/>状态定义与工作流"]
N1["nodes/full-outline.node.ts<br/>一步大纲节点"]
N2["nodes/content.node.ts<br/>内容生成节点"]
end
subgraph "提示词与存储"
PB["prompts/builder.ts<br/>提示词构建器"]
ST["book-generator.store.ts<br/>数据存储"]
TY["book-generator.types.ts<br/>类型定义"]
end
subgraph "编排与API"
SVC["book-generator.service.ts<br/>批量编排"]
CTRL["book-generator.controller.ts<br/>批量API"]
LGC["langgraph-controller.ts<br/>LangGraph API"]
SM["stage-manager.ts<br/>阶段管理"]
FT["fault-tolerance.ts<br/>容错层"]
UT["utils.ts<br/>工具与进度"]
end
IDX --> SEL
IDX --> GR
GR --> N1
GR --> N2
N1 --> PB
N2 --> PB
N1 --> ST
N2 --> ST
SVC --> ST
CTRL --> SVC
LGC --> IDX
LGC --> ST
LGC --> SM
LGC --> FT
SVC --> FT
ST --> TY
```

**图表来源**
- [index.ts:74-91](file://server/src/modules/book-generator/index.ts#L74-L91)
- [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)
- [builder.ts:220-248](file://server/src/modules/book-generator/prompts/builder.ts#L220-L248)
- [book-generator.store.ts:163-800](file://server/src/modules/book-generator/book-generator.store.ts#L163-L800)
- [book-generator.service.ts:45-549](file://server/src/modules/book-generator/book-generator.service.ts#L45-L549)
- [book-generator.controller.ts:24-199](file://server/src/modules/book-generator/book-generator.controller.ts#L24-L199)
- [langgraph-controller.ts:388-546](file://server/src/modules/book-generator/langgraph-controller.ts#L388-L546)
- [stage-manager.ts:100-198](file://server/src/modules/book-generator/stage-manager.ts#L100-L198)
- [fault-tolerance.ts:17-51](file://server/src/modules/book-generator/fault-tolerance.ts#L17-L51)
- [utils.ts:15-23](file://server/src/modules/book-generator/utils.ts#L15-L23)

**章节来源**
- [index.ts:1-119](file://server/src/modules/book-generator/index.ts#L1-L119)
- [graph.ts:1-83](file://server/src/modules/book-generator/graph.ts#L1-L83)
- [book-generator.service.ts:1-549](file://server/src/modules/book-generator/book-generator.service.ts#L1-L549)
- [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)
- [selector.ts:1-81](file://server/src/modules/book-generator/strategies/selector.ts#L1-L81)
- [full-outline.node.ts:1-243](file://server/src/modules/book-generator/nodes/full-outline.node.ts#L1-L243)
- [content.node.ts:1-546](file://server/src/modules/book-generator/nodes/content.node.ts#L1-L546)
- [builder.ts:1-275](file://server/src/modules/book-generator/prompts/builder.ts#L1-L275)
- [book-generator.store.ts:1-1073](file://server/src/modules/book-generator/book-generator.store.ts#L1-L1073)
- [stage-manager.ts:1-202](file://server/src/modules/book-generator/stage-manager.ts#L1-L202)
- [fault-tolerance.ts:1-387](file://server/src/modules/book-generator/fault-tolerance.ts#L1-L387)
- [utils.ts:1-24](file://server/src/modules/book-generator/utils.ts#L1-L24)
- [book-generator.types.ts:1-226](file://server/src/modules/book-generator/book-generator.types.ts#L1-L226)

## 核心组件
- LangGraphBookGenerator：策略门面，负责根据书籍规模与类型解析大纲层级并调度策略执行。
- GraphState：LangGraph状态注解，定义bookId、topic、bookScale、genLevel、progress、completedChapters、failedChapters等状态字段及reducer。
- BatchGenerationOrchestrator：批量生成编排器，串联内容生成、音频生成、音频合并、视频生成、视频合并五个阶段，支持取消与进度推送。
- GenerationStrategy/selector：策略体系，支持sequential、one-step-outline、per-chapter、deep-plan-parallel四种策略，可运行时切换。
- Nodes：full-outline.node与content.node分别负责一步生成完整大纲与并行生成章节内容。
- Prompts/builder：动态提示词构建器，结合正则与DeepPlan输出增强大纲生成质量。
- StageManager：线性阶段管理器，提供advanceChapter与regenerateChapter，保证状态机安全流转。
- FaultTolerance：容错层，提供AI重试、节点超时、进度监控与自动恢复。
- Store/Types：Prisma数据访问与类型定义，支撑书籍、章节、任务等实体。

**章节来源**
- [index.ts:74-91](file://server/src/modules/book-generator/index.ts#L74-L91)
- [graph.ts:23-82](file://server/src/modules/book-generator/graph.ts#L23-L82)
- [book-generator.service.ts:45-143](file://server/src/modules/book-generator/book-generator.service.ts#L45-L143)
- [selector.ts:14-77](file://server/src/modules/book-generator/strategies/selector.ts#L14-L77)
- [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)
- [builder.ts:71-212](file://server/src/modules/book-generator/prompts/builder.ts#L71-L212)
- [stage-manager.ts:100-198](file://server/src/modules/book-generator/stage-manager.ts#L100-L198)
- [fault-tolerance.ts:68-180](file://server/src/modules/book-generator/fault-tolerance.ts#L68-L180)
- [book-generator.store.ts:163-800](file://server/src/modules/book-generator/book-generator.store.ts#L163-L800)
- [book-generator.types.ts:8-139](file://server/src/modules/book-generator/book-generator.types.ts#L8-L139)

## 架构总览
系统采用“策略门面 + LangGraph工作流 + 节点执行 + 容错与阶段管理”的分层架构。策略门面根据输入解析genLevel并选择具体策略；LangGraph定义状态与节点，节点通过提示词工程与LLM交互；容错层保障稳定性；阶段管理器确保生成流程可控；存储层持久化状态与结果。

```mermaid
sequenceDiagram
participant C as "客户端"
participant API as "LangGraph API(langgraph-controller)"
participant GEN as "LangGraphBookGenerator(index)"
participant STR as "策略选择器(selector)"
participant WF as "LangGraph(graph)"
participant N1 as "大纲节点(full-outline.node)"
participant N2 as "内容节点(content.node)"
participant ST as "存储(book-generator.store)"
participant FT as "容错(fault-tolerance)"
C->>API : "POST /api/book-generator/langgraph/books"
API->>GEN : "generate(bookId, topic, scale, level)"
GEN->>STR : "getCurrentStrategy()"
STR-->>GEN : "策略实例"
GEN->>WF : "执行工作流"
WF->>N1 : "生成完整大纲"
N1->>FT : "AI调用重试/超时"
N1->>ST : "写入大纲与章节记录"
WF->>N2 : "并行生成章节内容"
N2->>FT : "AI调用重试/超时"
N2->>ST : "写入章节内容与进度"
API-->>C : "返回生成状态/进度"
```

**图表来源**
- [langgraph-controller.ts:388-546](file://server/src/modules/book-generator/langgraph-controller.ts#L388-L546)
- [index.ts:74-91](file://server/src/modules/book-generator/index.ts#L74-L91)
- [selector.ts:61-62](file://server/src/modules/book-generator/strategies/selector.ts#L61-L62)
- [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.store.ts:163-800](file://server/src/modules/book-generator/book-generator.store.ts#L163-L800)
- [fault-tolerance.ts:68-180](file://server/src/modules/book-generator/fault-tolerance.ts#L68-L180)

## 详细组件分析

### LangGraph状态与节点
- 状态字段：包含bookId、userId、topic、bookScale、genLevel、description、bookPlan、currentChapter、completedChapters、finished、error、progress、failedChapters等，reducer确保进度只增不减、失败章节合并等语义正确。
- 节点职责：
  - full-outline.node：一次性生成完整树形大纲（章→节→小节），解析并写入数据库。
  - content.node：并行生成叶节点内容，支持工具调用、字数截断、配额消耗与音频触发。

```mermaid
classDiagram
class GraphState {
+string bookId
+string|number userId
+string topic
+string bookScale
+number genLevel
+string description
+string|undefined bookPlan
+number currentChapter
+number[] completedChapters
+boolean finished
+string|undefined error
+number progress
+number[] failedChapters
}
class FullOutlineNode {
+generateFullOutlineNode(state) Partial~state~
}
class ContentNode {
+writeChaptersNode(state) Partial~state~
+writeChaptersParallelNode(state) Partial~state~
}
GraphState <.. FullOutlineNode : "读取/写入"
GraphState <.. ContentNode : "读取/写入"
```

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

**章节来源**
- [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)

### 策略与生成流程
- 策略选择：selector.ts注册四种策略，可通过setCurrentStrategy运行时切换。
- 生成入口：index.ts的LangGraphBookGenerator.generate接收bookId、topic、bookScale与genLevel，委托当前策略执行。
- 生成流程：LangGraph工作流按节点顺序执行，节点间通过状态传递，最终完成内容生成。

```mermaid
flowchart TD
Start(["开始"]) --> Resolve["解析genLevel<br/>resolveGenLevel()"]
Resolve --> Select["选择策略<br/>getCurrentStrategy()"]
Select --> Exec["执行策略.generate()"]
Exec --> Outline["大纲节点<br/>full-outline.node"]
Outline --> Content["内容节点<br/>content.node(并行)"]
Content --> Done(["完成"])
```

**图表来源**
- [index.ts:74-91](file://server/src/modules/book-generator/index.ts#L74-L91)
- [selector.ts:61-62](file://server/src/modules/book-generator/strategies/selector.ts#L61-L62)
- [full-outline.node.ts:135-218](file://server/src/modules/book-generator/nodes/full-outline.node.ts#L135-L218)
- [content.node.ts:444-545](file://server/src/modules/book-generator/nodes/content.node.ts#L444-L545)

**章节来源**
- [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)

### 提示词工程与多轮对话
- 动态需求分析：builder.ts的analyzeRequirements从用户输入中抽取书籍类型、目标读者、内容深度、行业与特殊需求，支持正则与DeepPlan高置信度覆盖。
- 动态提示词：buildDynamicPrompt根据需求组合系统提示词，buildOutlineMessages等消息构建函数为各节点提供上下文。
- 多轮与工具：content.node支持callLLMWithTools与降级callLLMWithMessages，结合工具调用与内容清洗，提升质量与稳定性。

**章节来源**
- [builder.ts:71-212](file://server/src/modules/book-generator/prompts/builder.ts#L71-L212)
- [builder.ts:220-248](file://server/src/modules/book-generator/prompts/builder.ts#L220-L248)
- [content.node.ts:240-249](file://server/src/modules/book-generator/nodes/content.node.ts#L240-L249)

### 批量生成与异步处理
- 批量编排：BatchGenerationOrchestrator按顺序执行generate_content、generate_audio、merge_audio、generate_video、merge_video五个阶段，轮询检查进度并支持取消。
- API接口：book-generator.controller提供批量生成、取消与状态查询；langgraph-controller提供书籍创建与生成、进度查询等。
- 队列与降级：langgraph-controller在创建书籍时尝试加入队列，若失败则降级为同步执行，确保核心业务可用。

```mermaid
sequenceDiagram
participant Client as "客户端"
participant Ctrl as "book-generator.controller"
participant Orchestrator as "BatchGenerationOrchestrator"
participant Store as "book-generator.store"
Client->>Ctrl : "POST /api/book-generator/books/ : id/batch-generate"
Ctrl->>Orchestrator : "createBatchGenerationTask()"
Orchestrator->>Orchestrator : "execute() 阶段循环"
Orchestrator->>Store : "轮询检查章节状态/进度"
Orchestrator-->>Ctrl : "推送进度/完成"
Ctrl-->>Client : "任务启动/状态"
```

**图表来源**
- [book-generator.controller.ts:24-119](file://server/src/modules/book-generator/book-generator.controller.ts#L24-L119)
- [book-generator.service.ts:45-143](file://server/src/modules/book-generator/book-generator.service.ts#L45-L143)
- [book-generator.store.ts:677-683](file://server/src/modules/book-generator/book-generator.store.ts#L677-L683)

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

### 审核与质量控制
- 内容清洗：content.node对LLM输出进行清洗，移除思考标签与冗余换行，必要时截断至预算字数的2.5倍。
- 字数上限：累计字数达到规模上限（±20%浮动）或全书上限时自动停止生成并中断。
- 配额与安全：订阅配额检查与消耗，失败章节自动回退到上游阶段并清理下游资源。

**章节来源**
- [content.node.ts:255-281](file://server/src/modules/book-generator/nodes/content.node.ts#L255-L281)
- [content.node.ts:283-289](file://server/src/modules/book-generator/nodes/content.node.ts#L283-L289)
- [stage-manager.ts:75-92](file://server/src/modules/book-generator/stage-manager.ts#L75-L92)

### 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：取消批量任务。
  - GET /api/book-generator/books/:id/batch-generate/status：查询任务状态。
- 其他
  - GET /api/book-generator/langgraph/estimate：书籍规模预估。
  - GET /api/book-generator/langgraph/book-types：书籍类型配置。
  - POST /api/book-generator/langgraph/detect-book-type：AI自动检测书籍类型。
  - POST /api/book-generator/langgraph/smart-recommend：智能推荐难度/人群/风格/领域。

**章节来源**
- [langgraph-controller.ts:388-714](file://server/src/modules/book-generator/langgraph-controller.ts#L388-L714)
- [book-generator.controller.ts:24-199](file://server/src/modules/book-generator/book-generator.controller.ts#L24-L199)

## 依赖关系分析
- 组件耦合
  - index.ts与selector.ts：策略门面依赖策略选择器。
  - graph.ts与nodes：节点依赖LangGraph状态注解。
  - nodes与builder：节点依赖提示词构建器。
  - nodes与store：节点依赖存储层写入与查询。
  - service与controller：编排器依赖控制器暴露的API。
  - fault-tolerance与nodes/service：容错层贯穿AI调用与节点执行。
- 外部依赖
  - LLM服务：通过callLLMWithMessages/Tools调用。
  - 队列服务：用于任务排队与降级同步执行。
  - WebSocket：用于批量生成进度推送。

```mermaid
graph LR
IDX["index.ts"] --> SEL["strategies/selector.ts"]
IDX --> GR["graph.ts"]
GR --> N1["nodes/full-outline.node.ts"]
GR --> N2["nodes/content.node.ts"]
N1 --> PB["prompts/builder.ts"]
N2 --> PB
N1 --> ST["book-generator.store.ts"]
N2 --> ST
SVC["book-generator.service.ts"] --> ST
CTRL["book-generator.controller.ts"] --> SVC
LGC["langgraph-controller.ts"] --> IDX
LGC --> ST
LGC --> FT["fault-tolerance.ts"]
SVC --> FT
```

**图表来源**
- [index.ts:18-91](file://server/src/modules/book-generator/index.ts#L18-L91)
- [selector.ts:14-77](file://server/src/modules/book-generator/strategies/selector.ts#L14-L77)
- [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)
- [builder.ts:220-248](file://server/src/modules/book-generator/prompts/builder.ts#L220-L248)
- [book-generator.store.ts:163-800](file://server/src/modules/book-generator/book-generator.store.ts#L163-L800)
- [book-generator.service.ts:45-549](file://server/src/modules/book-generator/book-generator.service.ts#L45-L549)
- [book-generator.controller.ts:24-199](file://server/src/modules/book-generator/book-generator.controller.ts#L24-L199)
- [langgraph-controller.ts:388-546](file://server/src/modules/book-generator/langgraph-controller.ts#L388-L546)
- [fault-tolerance.ts:68-180](file://server/src/modules/book-generator/fault-tolerance.ts#L68-L180)

**章节来源**
- [index.ts:18-91](file://server/src/modules/book-generator/index.ts#L18-L91)
- [selector.ts:14-77](file://server/src/modules/book-generator/strategies/selector.ts#L14-L77)
- [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)
- [builder.ts:220-248](file://server/src/modules/book-generator/prompts/builder.ts#L220-L248)
- [book-generator.store.ts:163-800](file://server/src/modules/book-generator/book-generator.store.ts#L163-L800)
- [book-generator.service.ts:45-549](file://server/src/modules/book-generator/book-generator.service.ts#L45-L549)
- [book-generator.controller.ts:24-199](file://server/src/modules/book-generator/book-generator.controller.ts#L24-L199)
- [langgraph-controller.ts:388-546](file://server/src/modules/book-generator/langgraph-controller.ts#L388-L546)
- [fault-tolerance.ts:68-180](file://server/src/modules/book-generator/fault-tolerance.ts#L68-L180)

## 性能考量
- 并行内容生成：content.node的并行池（默认8路）显著缩短长篇书籍内容生成时间，需结合队列与资源限制避免过载。
- 节点超时与重试：fault-tolerance为各节点设置超时阈值与AI调用重试，平衡稳定性与响应速度。
- 进度与轮询：批量编排通过轮询检查章节状态，建议前端采用WebSocket或长轮询降低延迟。
- 存储与索引：章节树查询与状态更新频繁，建议在bookId、level、number等字段建立合适索引。

## 故障排查指南
- AI调用失败：检查fault-tolerance的重试配置与通知，确认模型可用性与限流。
- 节点超时：根据FAULT_TOLERANCE_CONFIG调整对应节点超时时间，或检查LLM响应质量。
- 进度停滞：启用startProgressMonitor，关注空闲时间与自动恢复尝试次数。
- 状态回退：使用regenerateChapter将章节回退到上游阶段，清理下游资源后重试。
- 取消任务：通过批量API的cancel接口设置取消标志，编排器会在检查点退出。

**章节来源**
- [fault-tolerance.ts:68-323](file://server/src/modules/book-generator/fault-tolerance.ts#L68-L323)
- [stage-manager.ts:158-198](file://server/src/modules/book-generator/stage-manager.ts#L158-L198)
- [book-generator.controller.ts:125-156](file://server/src/modules/book-generator/book-generator.controller.ts#L125-L156)

## 结论
本系统通过策略门面、LangGraph工作流与节点化实现，结合提示词工程、并行生成、容错与阶段管理，形成了稳定高效的AI内容生成流水线。其API设计支持从交互式创建到批量生成的多种场景，具备良好的扩展性与可维护性。

## 附录
- 关键进度常量：OUTLINE_DONE、CONTENT_START/END、FOREWORD_DONE、AFTERWORD_DONE，用于编排器与节点的进度推进。
- 类型定义：涵盖书籍、章节、任务、请求/响应与生成配置，确保前后端一致性。

**章节来源**
- [utils.ts:15-23](file://server/src/modules/book-generator/utils.ts#L15-L23)
- [book-generator.types.ts:8-139](file://server/src/modules/book-generator/book-generator.types.ts#L8-L139)