book-langgraph.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  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), // 纯数字字符串,如 '1000', '130000', '340000'
  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. '2000': { min: 2, max: 8, wordsPerChapter: 3000 },
  90. '130000': { min: 5, max: 15, wordsPerChapter: 2500 },
  91. '340000': { 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. };
  101. const scaleLabel = scaleDesc[state.bookScale] || `书籍,约${state.bookScale}字`;
  102. const prompt = `请为书籍《${state.topic}》设计大纲。
  103. 书籍规模:${scaleDesc[state.bookScale] || '中篇'}
  104. 请分析这个主题的复杂程度,决定合适的章节数量(${SCALE_CHAPTER_RANGE[state.bookScale]?.min || 5}-${SCALE_CHAPTER_RANGE[state.bookScale]?.max || 10}章之间),并生成完整大纲。
  105. 返回JSON格式:
  106. {
  107. "mainTheme": "主题一句话描述",
  108. "structureLogic": "结构逻辑说明",
  109. "chapters": [
  110. {
  111. "number": 1,
  112. "title": "章节标题",
  113. "summary": "章节摘要,50字左右",
  114. "keyPoints": ["要点1", "要点2", "要点3"],
  115. "estimatedWords": 预估字数
  116. }
  117. ]
  118. }
  119. 请确保:
  120. 1. 章节数根据主题实际复杂度决定,不要固定用中间值
  121. 2. 章节之间有清晰的逻辑递进关系
  122. 3. 每章的预估字数要符合规模要求`;
  123. try {
  124. const response = await callLLM(prompt);
  125. const outline = parseOutline(response);
  126. if (!outline)
  127. throw new Error('大纲解析失败');
  128. // 更新书籍的总章节数
  129. const totalChapters = outline.chapters.length;
  130. // 保存大纲和创建章节到数据库
  131. await book_generator_store_1.bookStore.update(state.bookId, {
  132. totalChapters,
  133. outlineJson: JSON.stringify(outline),
  134. status: 'planning',
  135. progress: 5,
  136. });
  137. // 创建章节记录
  138. await book_generator_store_1.bookStore.createChapters(state.bookId, outline.chapters.map(c => ({
  139. number: c.number,
  140. title: c.title,
  141. summary: c.summary,
  142. keyPoints: c.keyPoints,
  143. estimatedWords: c.estimatedWords,
  144. })));
  145. console.log('[LangGraph] 大纲生成完成,章节数:', outline.chapters.length);
  146. return { progress: 5 };
  147. }
  148. catch (error) {
  149. console.error('[LangGraph] 大纲生成失败:', error);
  150. return { error: error instanceof Error ? error.message : '失败', finished: true };
  151. }
  152. }
  153. async function writeChaptersNode(state) {
  154. console.log('[LangGraph] 生成章节, bookId:', state.bookId);
  155. // 从数据库读取书籍和章节
  156. const book = await book_generator_store_1.bookStore.getById(state.bookId);
  157. if (!book || !book.outline) {
  158. console.log('[LangGraph] 无大纲或书籍,跳过章节生成');
  159. return { finished: true, progress: 90 };
  160. }
  161. const chapters = [];
  162. const failedChapters = [];
  163. for (const chapterOutline of book.outline.chapters) {
  164. console.log(`[LangGraph] 生成第${chapterOutline.number}章: ${chapterOutline.title}`);
  165. const prompt = `撰写《${state.topic}》第${chapterOutline.number}章。章节:${chapterOutline.title},概述:${chapterOutline.summary},知识点:${chapterOutline.keyPoints.join(', ')},长度${chapterOutline.estimatedWords}字左右。直接输出正文:`;
  166. try {
  167. const content = await callLLM(prompt);
  168. const wordCount = countWords(content);
  169. await book_generator_store_1.bookStore.updateChapter(state.bookId, chapterOutline.number, {
  170. content,
  171. wordCount,
  172. status: 'completed',
  173. });
  174. chapters.push({
  175. number: chapterOutline.number,
  176. title: chapterOutline.title,
  177. content,
  178. wordCount,
  179. status: 'completed',
  180. });
  181. const progress = Math.round((chapters.length / book.outline.chapters.length) * 80) + 10;
  182. await book_generator_store_1.bookStore.update(state.bookId, { progress, status: 'generating' });
  183. console.log(`[LangGraph] 第${chapterOutline.number}章完成,进度${progress}%`);
  184. }
  185. catch (error) {
  186. const errorMsg = error instanceof Error ? error.message : '失败';
  187. await book_generator_store_1.bookStore.updateChapter(state.bookId, chapterOutline.number, { status: 'failed', errorMsg });
  188. failedChapters.push(chapterOutline.number);
  189. console.error(`[LangGraph] 第${chapterOutline.number}章失败:`, errorMsg);
  190. }
  191. }
  192. return {
  193. currentChapter: book.outline.chapters.length,
  194. progress: 90,
  195. error: failedChapters.length > 0 ? `章节${failedChapters.join(',')}失败` : undefined,
  196. };
  197. }
  198. async function writeForewordNode(state) {
  199. console.log('[LangGraph] 生成前言, bookId:', state.bookId);
  200. const prompt = `为《${state.topic}》写前言。主题:${state.topic},300-500字。直接输出:`;
  201. try {
  202. const foreword = await callLLM(prompt);
  203. await book_generator_store_1.bookStore.update(state.bookId, { foreword, progress: 95 });
  204. return { progress: 95 };
  205. }
  206. catch (error) {
  207. console.error('[LangGraph] 前言生成失败:', error);
  208. return { progress: 95 };
  209. }
  210. }
  211. async function writeAfterwordNode(state) {
  212. console.log('[LangGraph] 生成后记, bookId:', state.bookId);
  213. const prompt = `为《${state.topic}》写后记。主题:${state.topic},300-500字。直接输出:`;
  214. try {
  215. const afterword = await callLLM(prompt);
  216. await book_generator_store_1.bookStore.update(state.bookId, { afterword });
  217. return { finished: true, progress: 100 };
  218. }
  219. catch (error) {
  220. console.error('[LangGraph] 后记生成失败:', error);
  221. return { finished: true, progress: 100 };
  222. }
  223. }
  224. // ============ 创建工作流 ============
  225. function createGraph() {
  226. const workflow = new langgraph_1.StateGraph(GraphState)
  227. .addNode('generate_outline', generateOutlineNode)
  228. .addNode('write_chapters', writeChaptersNode)
  229. .addNode('write_foreword', writeForewordNode)
  230. .addNode('write_afterword', writeAfterwordNode)
  231. .setEntryPoint('generate_outline')
  232. // 顺序流程
  233. .addEdge('generate_outline', 'write_chapters')
  234. .addEdge('write_chapters', 'write_foreword')
  235. .addEdge('write_foreword', 'write_afterword')
  236. .addEdge('write_afterword', langgraph_1.END);
  237. return workflow.compile();
  238. }
  239. // ============ 主类 ============
  240. class LangGraphBookGenerator {
  241. graph = createGraph();
  242. async generate(bookId, topic, bookScale = '130000') {
  243. const initialState = {
  244. bookId,
  245. topic,
  246. bookScale,
  247. currentChapter: 0,
  248. finished: false,
  249. error: undefined,
  250. progress: 0,
  251. };
  252. await book_generator_store_1.bookStore.update(bookId, { status: 'generating', progress: 0 });
  253. try {
  254. const stream = await this.graph.stream(initialState);
  255. for await (const step of stream) {
  256. console.log('[LangGraph] Step:', Object.keys(step));
  257. }
  258. await book_generator_store_1.bookStore.update(bookId, { status: 'completed', progress: 100 });
  259. await book_generator_store_1.bookStore.publishAlbum(bookId); // 发布专辑
  260. console.log('[LangGraph] 书籍生成完成');
  261. }
  262. catch (error) {
  263. console.error('[LangGraph] 生成失败:', error);
  264. await book_generator_store_1.bookStore.update(bookId, { status: 'failed', errorMsg: error instanceof Error ? error.message : '生成失败' });
  265. }
  266. }
  267. }
  268. exports.LangGraphBookGenerator = LangGraphBookGenerator;
  269. exports.langGraphGenerator = new LangGraphBookGenerator();