# All files / modules/book-generator/nodes sections.node.ts

0% Statements 0/183
0% Branches 0/1
0% Functions 0/1
0% Lines 0/183

Press n or j to go to the next uncovered block, b, p or k for the previous block.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237

     /**
     * 节和小节大纲生成节点
     */

    import { GraphState } from '../graph';
    import { bookStore } from '../book-generator.store';
    import { prisma } from '../../../models';
    import { callLLMWithMessages } from '../../../services/llm';
    import { parseSections } from '../parsers/section.parser';
    import { parseSubsections } from '../parsers/subsection.parser';
    import { buildSectionMessages, buildSubsectionMessages } from '../prompts/builder';
    import { PROGRESS } from '../utils';

    /**
     * 生成节大纲节点（二级大纲）
     * 为每章生成节的大纲
     * 如果 genLevel ≤ 1，跳过（仅章层级）
     */
    export async function generateSectionsNode(state: typeof GraphState.State): Promise<Partial<typeof GraphState.State>> {
      console.log('[LangGraph] 生成节大纲, bookId:', state.bookId, 'genLevel:', state.genLevel);

      // genLevel=1（仅章）：跳过
      if (state.genLevel <= 1) {
        console.log('[LangGraph] genLevel=1，跳过节点生成');
        return { progress: PROGRESS.SECTIONS_DONE };
      }

      const book = await bookStore.getById(state.bookId);
      if (!book || !book.outline) {
        console.log('[LangGraph] 无大纲，跳过节生成');
        return { finished: true, progress: PROGRESS.SECTIONS_DONE };
      }

      try {
        const updatedChapters = [];

        for (const chapter of book.outline.chapters) {
          console.log(`[LangGraph] 为第${chapter.number}章「${chapter.title}」生成节大纲`);
          const messages = buildSectionMessages(chapter.title, chapter.summary, chapter.keyPoints || []);

          let parsed = null;
          let lastError = null;
          for (let retry = 0; retry < 3; retry++) {
            try {
              const response = await callLLMWithMessages(messages);
              parsed = parseSections(response);

              if (parsed && parsed.sections.length > 0) {
                console.log(`[LangGraph] 第${chapter.number}章节大纲解析成功，共${parsed.sections.length}节`);
                break;
              } else {
                console.warn(`[LangGraph] 第${chapter.number}章节大纲解析失败（第${retry + 1}次），重试中...`);
                lastError = new Error('解析结果为空');
              }
            } catch (sectionErr) {
              console.error(`[LangGraph] 第${chapter.number}章节大纲生成失败（第${retry + 1}次）:`, sectionErr);
              lastError = sectionErr;
            }
          }

          if (parsed && parsed.sections.length > 0) {
            const bookIdNum = parseInt(state.bookId);
            const chapterRecord = await prisma.bookChapter.findFirst({
              where: {
                bookId: bookIdNum,
                parentId: 0,
                level: 1,
                number: chapter.number
              }
            });

            if (chapterRecord) {
              for (let j = 0; j < parsed.sections.length; j++) {
                const section = parsed.sections[j];
                const sectionNumber = section.number ?? (j + 1);
                await bookStore.createChapterItem(bookIdNum, {
                  number: sectionNumber,
                  title: section.title,
                  summary: section.summary,
                  keyPoints: section.keyPoints,
                  estimatedWords: section.estimatedWords,
                }, chapterRecord.id, 2);

                console.log(`[LangGraph]   - 第${chapter.number}章第${sectionNumber}节「${section.title}」`);
              }
            } else {
              console.error(`[LangGraph] 未找到第${chapter.number}章的数据库记录`);
            }

            updatedChapters.push({
              ...chapter,
              sections: parsed.sections,
            });
          } else {
            console.warn(`[LangGraph] 第${chapter.number}章节大纲解析失败，跳过。错误:`, lastError);
            updatedChapters.push(chapter);
          }
        }

        const updatedOutline = { ...book.outline, chapters: updatedChapters };
        await bookStore.update(state.bookId, {
          outlineJson: JSON.stringify(updatedOutline),
          progress: PROGRESS.SECTIONS_DONE,
        });

        console.log('[LangGraph] 节大纲生成完成');
        return { progress: PROGRESS.SECTIONS_DONE };
      } catch (error) {
        console.error('[LangGraph] 节大纲生成失败:', error);
        return { error: error instanceof Error ? error.message : '失败', finished: true };
      }
    }

    /**
     * 生成小节大纲节点（三级大纲）
     * 为每节生成小节的大纲
     * 如果 genLevel ≤ 2，跳过（仅章→节层级）
     */
    export async function generateSubsectionsNode(state: typeof GraphState.State): Promise<Partial<typeof GraphState.State>> {
      console.log('[LangGraph] 生成小节大纲, bookId:', state.bookId, 'genLevel:', state.genLevel);

      // genLevel≤2（仅章→节）：跳过
      if (state.genLevel <= 2) {
        console.log('[LangGraph] genLevel≤2，跳过小节生成');
        return { progress: PROGRESS.SUBSECTIONS_DONE };
      }

      const book = await bookStore.getById(state.bookId);
      if (!book || !book.outline) {
        console.log('[LangGraph] 无大纲，跳过小节生成');
        return { finished: true, progress: PROGRESS.SUBSECTIONS_DONE };
      }

      try {
        const updatedChapters = [];

        for (const chapter of book.outline.chapters) {
          const updatedSections = [];

          if (chapter.sections && chapter.sections.length > 0) {
            for (const section of chapter.sections) {
              console.log(`[LangGraph] 为第${chapter.number}章第${section.number}节「${section.title}」生成小节大纲`);
              const messages = buildSubsectionMessages(section.title, section.summary || '', section.keyPoints || []);

              let parsed = null;
              let lastError = null;
              for (let retry = 0; retry < 3; retry++) {
                try {
                  const response = await callLLMWithMessages(messages);
                  parsed = parseSubsections(response);

                  if (parsed && parsed.subsections.length > 0) {
                    console.log(`[LangGraph] 第${chapter.number}章第${section.number}节小节大纲解析成功，共${parsed.subsections.length}小节`);
                    break;
                  } else {
                    console.warn(`[LangGraph] 第${chapter.number}章第${section.number}节小节大纲解析失败（第${retry + 1}次），重试中...`);
                    lastError = new Error('解析结果为空');
                  }
                } catch (subErr) {
                  console.error(`[LangGraph] 第${chapter.number}章第${section.number}节小节大纲生成失败（第${retry + 1}次）:`, subErr);
                  lastError = subErr;
                }
              }

              if (parsed && parsed.subsections.length > 0) {
                const bookIdNum = parseInt(state.bookId);
                const chapterRecord = await prisma.bookChapter.findFirst({
                  where: {
                    bookId: bookIdNum,
                    parentId: 0,
                    level: 1,
                    number: chapter.number
                  }
                });

                if (!chapterRecord) {
                  console.error(`[LangGraph] 未找到第${chapter.number}章的数据库记录`);
                  updatedSections.push(section);
                  continue;
                }

                const sectionRecord = await prisma.bookChapter.findFirst({
                  where: {
                    bookId: bookIdNum,
                    parentId: chapterRecord.id,
                    level: 2,
                    number: section.number
                  }
                });

                if (sectionRecord) {
                  for (const subsection of parsed.subsections) {
                    await bookStore.createChapterItem(bookIdNum, {
                      number: subsection.number,
                      title: subsection.title,
                      summary: subsection.summary,
                      keyPoints: subsection.keyPoints,
                      estimatedWords: subsection.estimatedWords,
                    }, sectionRecord.id, 3);

                    console.log(`[LangGraph]     - 第${chapter.number}章第${section.number}节第${subsection.number}小节「${subsection.title}」`);
                  }
                } else {
                  console.error(`[LangGraph] 未找到第${chapter.number}章第${section.number}节的数据库记录`);
                }

                updatedSections.push({
                  ...section,
                  subsections: parsed.subsections,
                });
              } else {
                console.warn(`[LangGraph] 第${chapter.number}章第${section.number}节小节大纲解析失败，跳过。错误:`, lastError);
                updatedSections.push(section);
              }
            }
          }

          updatedChapters.push({
            ...chapter,
            sections: updatedSections.length > 0 ? updatedSections : chapter.sections,
          });
        }

        const updatedOutline = { ...book.outline, chapters: updatedChapters };
        await bookStore.update(state.bookId, {
          outlineJson: JSON.stringify(updatedOutline),
          progress: PROGRESS.SUBSECTIONS_DONE,
        });

        console.log('[LangGraph] 小节大纲生成完成');
        return { progress: PROGRESS.SUBSECTIONS_DONE };
      } catch (error) {
        console.error('[LangGraph] 小节大纲生成失败:', error);
        return { error: error instanceof Error ? error.message : '失败', finished: true };
      }
    }