book-langgraph.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  1. "use strict";
  2. /**
  3. * LangGraph 书籍生成器
  4. * 使用 @langchain/langgraph v1.2.8 API
  5. * 状态通过数据库传递,LangGraph 只负责流程控制
  6. */
  7. var __importDefault = (this && this.__importDefault) || function (mod) {
  8. return (mod && mod.__esModule) ? mod : { "default": mod };
  9. };
  10. Object.defineProperty(exports, "__esModule", { value: true });
  11. exports.langGraphGenerator = exports.LangGraphBookGenerator = void 0;
  12. const axios_1 = __importDefault(require("axios"));
  13. const config_1 = require("../../../config");
  14. const book_generator_store_1 = require("../book-generator.store");
  15. const langgraph_1 = require("@langchain/langgraph");
  16. // ============ 定义 State ============
  17. const GraphState = langgraph_1.Annotation.Root({
  18. bookId: (langgraph_1.Annotation),
  19. topic: (langgraph_1.Annotation),
  20. bookScale: (langgraph_1.Annotation), // '小册子' | '标准教程' | '系统教材' | '专业厚本' | '大部头'
  21. currentChapter: (langgraph_1.Annotation),
  22. finished: (langgraph_1.Annotation),
  23. error: (langgraph_1.Annotation),
  24. progress: (langgraph_1.Annotation),
  25. });
  26. // ============ LLM 配置 ============
  27. const TEMPERATURE = 0.7;
  28. const MAX_RETRIES = 2;
  29. async function callLLM(prompt, currentModel) {
  30. const modelId = currentModel || config_1.config.models.textGeneration.defaultModel;
  31. const modelConfig = config_1.config.models.getModel(modelId);
  32. const apiKey = modelConfig?.apiKey;
  33. const baseUrl = modelConfig?.baseUrl;
  34. if (!apiKey || !baseUrl)
  35. throw new Error(`模型 ${modelId} 缺少 API 配置`);
  36. try {
  37. const response = await axios_1.default.post(`${baseUrl}/chat/completions`, { model: modelId, messages: [{ role: 'user', content: prompt }] }, { headers: { Authorization: `Bearer ${apiKey}`, 'Content-Type': 'application/json' }, timeout: 180000 });
  38. const result = response.data?.choices?.[0]?.message?.content || '';
  39. if (!result)
  40. throw new Error('API 返回内容为空');
  41. return result;
  42. }
  43. catch (error) {
  44. const errorMessage = error.response?.data?.message || error.message || 'API 调用失败';
  45. console.log(`[LLM] 模型 ${modelId} 调用失败: ${errorMessage}`);
  46. // 检查是否需要切换模型
  47. if (config_1.config.models.shouldSwitchModel(errorMessage)) {
  48. const nextModel = config_1.config.models.getNextModel(modelId, 'text');
  49. if (nextModel) {
  50. console.log(`[LLM] 自动切换到模型: ${nextModel}`);
  51. return callLLM(prompt, nextModel);
  52. }
  53. }
  54. throw new Error(errorMessage);
  55. }
  56. }
  57. function countWords(text) {
  58. return (text.match(/[\u4e00-\u9fa5]/g) || []).length;
  59. }
  60. function parseOutline(jsonStr) {
  61. try {
  62. const match = jsonStr.match(/\{[\s\S]*\}/);
  63. if (match) {
  64. const data = JSON.parse(match[0]);
  65. return {
  66. mainTheme: data.mainTheme || '主题待定',
  67. structureLogic: data.structureLogic || '由浅入深',
  68. chapters: (data.chapters || []).map((c, i) => ({
  69. number: c.number || i + 1,
  70. title: c.title || `第${i + 1}章`,
  71. summary: c.summary || '',
  72. keyPoints: c.keyPoints || [],
  73. estimatedWords: c.estimatedWords || 1000,
  74. })),
  75. };
  76. }
  77. }
  78. catch {
  79. console.error('解析大纲失败');
  80. }
  81. return null;
  82. }
  83. // ============ LangGraph 节点(从数据库读取状态)============
  84. // 规模对应的章节范围
  85. const SCALE_CHAPTER_RANGE = {
  86. '800': { min: 1, max: 1, wordsPerChapter: 800 },
  87. '2000': { min: 1, max: 1, wordsPerChapter: 2000 },
  88. '5000': { min: 1, max: 1, wordsPerChapter: 5000 },
  89. 小册子: { min: 3, max: 8, wordsPerChapter: 3000 },
  90. 标准教程: { min: 5, max: 15, wordsPerChapter: 2500 },
  91. 系统教材: { min: 10, max: 20, wordsPerChapter: 2500 },
  92. };
  93. async function generateOutlineNode(state) {
  94. console.log('[LangGraph] 生成大纲, bookId:', state.bookId, 'scale:', state.bookScale);
  95. // 规模说明
  96. const scaleDesc = {
  97. '800': '短文,约800字',
  98. '2000': '短文,约2000字',
  99. '5000': '短文,约5000字',
  100. 小册子: '小册子,1-5万字,快速上手/技巧合集,3-8章',
  101. 标准教程: '标准教程,5-15万字,大众技能/职场工具,5-15章',
  102. 系统教材: '系统教材,15-30万字,完整课程/职业培训,10-20章',
  103. };
  104. const prompt = `请为书籍《${state.topic}》设计大纲。
  105. 书籍规模:${scaleDesc[state.bookScale] || '中篇'}
  106. 请分析这个主题的复杂程度,决定合适的章节数量(${SCALE_CHAPTER_RANGE[state.bookScale]?.min || 5}-${SCALE_CHAPTER_RANGE[state.bookScale]?.max || 10}章之间),并生成完整大纲。
  107. 返回JSON格式:
  108. {
  109. "mainTheme": "主题一句话描述",
  110. "structureLogic": "结构逻辑说明",
  111. "chapters": [
  112. {
  113. "number": 1,
  114. "title": "章节标题",
  115. "summary": "章节摘要,50字左右",
  116. "keyPoints": ["要点1", "要点2", "要点3"],
  117. "estimatedWords": 预估字数
  118. }
  119. ]
  120. }
  121. 请确保:
  122. 1. 章节数根据主题实际复杂度决定,不要固定用中间值
  123. 2. 章节之间有清晰的逻辑递进关系
  124. 3. 每章的预估字数要符合规模要求`;
  125. try {
  126. const response = await callLLM(prompt);
  127. const outline = parseOutline(response);
  128. if (!outline)
  129. throw new Error('大纲解析失败');
  130. // 更新书籍的总章节数
  131. const totalChapters = outline.chapters.length;
  132. // 保存大纲和创建章节到数据库
  133. await book_generator_store_1.bookStore.update(state.bookId, {
  134. totalChapters,
  135. outlineJson: JSON.stringify(outline),
  136. status: 'planning',
  137. progress: 5,
  138. });
  139. // 创建章节记录
  140. await book_generator_store_1.bookStore.createChapters(state.bookId, outline.chapters.map(c => ({
  141. number: c.number,
  142. title: c.title,
  143. summary: c.summary,
  144. keyPoints: c.keyPoints,
  145. estimatedWords: c.estimatedWords,
  146. })));
  147. console.log('[LangGraph] 大纲生成完成,章节数:', outline.chapters.length);
  148. return { progress: 5 };
  149. }
  150. catch (error) {
  151. console.error('[LangGraph] 大纲生成失败:', error);
  152. return { error: error instanceof Error ? error.message : '失败', finished: true };
  153. }
  154. }
  155. async function writeChaptersNode(state) {
  156. console.log('[LangGraph] 生成章节, bookId:', state.bookId);
  157. // 从数据库读取书籍和章节
  158. const book = await book_generator_store_1.bookStore.getById(state.bookId);
  159. if (!book || !book.outline) {
  160. console.log('[LangGraph] 无大纲或书籍,跳过章节生成');
  161. return { finished: true, progress: 90 };
  162. }
  163. const chapters = [];
  164. const failedChapters = [];
  165. for (const chapterOutline of book.outline.chapters) {
  166. console.log(`[LangGraph] 生成第${chapterOutline.number}章: ${chapterOutline.title}`);
  167. const prompt = `撰写《${state.topic}》第${chapterOutline.number}章。章节:${chapterOutline.title},概述:${chapterOutline.summary},知识点:${chapterOutline.keyPoints.join(', ')},长度${chapterOutline.estimatedWords}字左右。直接输出正文:`;
  168. try {
  169. const content = await callLLM(prompt);
  170. const wordCount = countWords(content);
  171. await book_generator_store_1.bookStore.updateChapter(state.bookId, chapterOutline.number, {
  172. content,
  173. wordCount,
  174. status: 'completed',
  175. });
  176. chapters.push({
  177. number: chapterOutline.number,
  178. title: chapterOutline.title,
  179. content,
  180. wordCount,
  181. status: 'completed',
  182. });
  183. const progress = Math.round((chapters.length / book.outline.chapters.length) * 80) + 10;
  184. await book_generator_store_1.bookStore.update(state.bookId, { progress, status: 'generating' });
  185. console.log(`[LangGraph] 第${chapterOutline.number}章完成,进度${progress}%`);
  186. }
  187. catch (error) {
  188. const errorMsg = error instanceof Error ? error.message : '失败';
  189. await book_generator_store_1.bookStore.updateChapter(state.bookId, chapterOutline.number, { status: 'failed', errorMsg });
  190. failedChapters.push(chapterOutline.number);
  191. console.error(`[LangGraph] 第${chapterOutline.number}章失败:`, errorMsg);
  192. }
  193. }
  194. return {
  195. currentChapter: book.outline.chapters.length,
  196. progress: 90,
  197. error: failedChapters.length > 0 ? `章节${failedChapters.join(',')}失败` : undefined,
  198. };
  199. }
  200. async function writeForewordNode(state) {
  201. console.log('[LangGraph] 生成前言, bookId:', state.bookId);
  202. const prompt = `为《${state.topic}》写前言。主题:${state.topic},300-500字。直接输出:`;
  203. try {
  204. const foreword = await callLLM(prompt);
  205. await book_generator_store_1.bookStore.update(state.bookId, { foreword, progress: 95 });
  206. return { progress: 95 };
  207. }
  208. catch (error) {
  209. console.error('[LangGraph] 前言生成失败:', error);
  210. return { progress: 95 };
  211. }
  212. }
  213. async function writeAfterwordNode(state) {
  214. console.log('[LangGraph] 生成后记, bookId:', state.bookId);
  215. const prompt = `为《${state.topic}》写后记。主题:${state.topic},300-500字。直接输出:`;
  216. try {
  217. const afterword = await callLLM(prompt);
  218. await book_generator_store_1.bookStore.update(state.bookId, { afterword });
  219. return { finished: true, progress: 100 };
  220. }
  221. catch (error) {
  222. console.error('[LangGraph] 后记生成失败:', error);
  223. return { finished: true, progress: 100 };
  224. }
  225. }
  226. // ============ 创建工作流 ============
  227. function createGraph() {
  228. const workflow = new langgraph_1.StateGraph(GraphState)
  229. .addNode('generate_outline', generateOutlineNode)
  230. .addNode('write_chapters', writeChaptersNode)
  231. .addNode('write_foreword', writeForewordNode)
  232. .addNode('write_afterword', writeAfterwordNode)
  233. .setEntryPoint('generate_outline')
  234. // 顺序流程
  235. .addEdge('generate_outline', 'write_chapters')
  236. .addEdge('write_chapters', 'write_foreword')
  237. .addEdge('write_foreword', 'write_afterword')
  238. .addEdge('write_afterword', langgraph_1.END);
  239. return workflow.compile();
  240. }
  241. // ============ 主类 ============
  242. class LangGraphBookGenerator {
  243. graph = createGraph();
  244. async generate(bookId, topic, bookScale = 'medium') {
  245. const initialState = {
  246. bookId,
  247. topic,
  248. bookScale,
  249. currentChapter: 0,
  250. finished: false,
  251. error: undefined,
  252. progress: 0,
  253. };
  254. await book_generator_store_1.bookStore.update(bookId, { status: 'generating', progress: 0 });
  255. try {
  256. const stream = await this.graph.stream(initialState);
  257. for await (const step of stream) {
  258. console.log('[LangGraph] Step:', Object.keys(step));
  259. }
  260. await book_generator_store_1.bookStore.update(bookId, { status: 'completed', progress: 100 });
  261. await book_generator_store_1.bookStore.publishAlbum(bookId); // 发布专辑
  262. console.log('[LangGraph] 书籍生成完成');
  263. }
  264. catch (error) {
  265. console.error('[LangGraph] 生成失败:', error);
  266. await book_generator_store_1.bookStore.update(bookId, { status: 'failed', errorMsg: error instanceof Error ? error.message : '生成失败' });
  267. }
  268. }
  269. }
  270. exports.LangGraphBookGenerator = LangGraphBookGenerator;
  271. exports.langGraphGenerator = new LangGraphBookGenerator();