langgraph-controller.ts 102 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129
  1. /**
  2. * LangGraph 书籍生成 - API 路由
  3. * 支持书籍创建时的预估显示
  4. */
  5. import Router from '@koa/router';
  6. import { Context } from 'koa';
  7. import { langGraphGenerator, getScaleConfig, resolveGenLevel, mapBookTypeToGenLevel } from './index';
  8. import { bookStore, cancelAudioGeneration } from './book-generator.store';
  9. import { prisma } from '../../models';
  10. import { estimateBookWords, estimateAudioMinutesFromWords, checkBookGenerationQuota, checkAudioQuota, atomicReserveQuota, releaseQuota, AUDIO_BILLING_CONFIG } from '../subscription/subscription.service';
  11. import { optionalAuth } from '../../middleware/auth';
  12. import { getAllBookTypes, getDetectableTypes, getBookTypeConfig, BOOK_TYPE_CONFIG, DETECTABLE_TYPES } from './book-type-config';
  13. import { callLLMWithMessages, callLLM, ChatMessage } from '../../services/llm';
  14. import { cleanLlmShortText, extractJsonFromResponse } from '../../services/llm/response-cleaner';
  15. import { runWithContext } from '../../services/llm-context';
  16. import { createVideoProjectFromBook, generateVideoForProject } from '../video-generator/video-generator.service';
  17. import { mergeChapterAudios } from '../player/player.service';
  18. import { DEFAULT_VOICE_SPEED } from '../tts/tts.service';
  19. import { exec } from 'child_process';
  20. import { promisify } from 'util';
  21. import fs from 'fs/promises';
  22. import path from 'path';
  23. import { advanceChapter, regenerateChapter } from './stage-manager';
  24. import { deepPlanBookNode } from './nodes/deep-plan.node';
  25. import { richOutlineNode } from './nodes/rich-outline.node';
  26. import { writeChaptersParallelNode } from './nodes/content.node';
  27. import { continuityEditNode } from './nodes/continuity-edit.node';
  28. import { GraphState } from './graph';
  29. const execPromise = promisify(exec);
  30. // 开发环境测试用户ID
  31. const TEST_USER_ID = '1';
  32. const router = new Router();
  33. /**
  34. * GET /api/book-generator/langgraph/estimate
  35. * 获取书籍规模预估信息
  36. */
  37. router.get('/estimate', async (ctx: Context) => {
  38. const { scale, userId, bookType } = ctx.query as { scale?: string; userId?: string; bookType?: string };
  39. if (!scale) {
  40. ctx.status = 400;
  41. ctx.body = { code: 1, message: '请提供书籍规模' };
  42. return;
  43. }
  44. const scaleConfig = getScaleConfig(scale);
  45. const totalWords = scaleConfig.totalWords;
  46. const audioMinutes = estimateAudioMinutesFromWords(totalWords);
  47. // 章节数
  48. const estimatedChapters = scaleConfig.isShortArticle ? 1 : scaleConfig.chapters;
  49. // 大纲层级(优先使用书籍类型映射)
  50. const genLevel = bookType && bookType !== 'auto'
  51. ? mapBookTypeToGenLevel(bookType)
  52. : resolveGenLevel(scale);
  53. const genLevelDescriptions: Record<number, { label: string; desc: string }> = {
  54. 1: { label: '仅章', desc: '无节和小节,适合短文、小说' },
  55. 2: { label: '章→节', desc: '有节无小节,适合科普、商业书' },
  56. 3: { label: '章→节→小节', desc: '完整三级结构,适合教材、技术书' },
  57. };
  58. const result: any = {
  59. scale,
  60. scaleConfig,
  61. audioMinutes: {
  62. min: estimateAudioMinutesFromWords(Math.round(totalWords * 0.8)),
  63. max: estimateAudioMinutesFromWords(Math.round(totalWords * 1.2)),
  64. avg: audioMinutes
  65. },
  66. estimatedChapters,
  67. defaultGenLevel: genLevel,
  68. genLevelInfo: genLevelDescriptions[genLevel] || { label: '章→节', desc: '' },
  69. };
  70. // 如果提供了 userId,同时检查用户配额
  71. if (userId) {
  72. const quotaCheck = await checkBookGenerationQuota(parseInt(userId), scale);
  73. result.quotaCheck = quotaCheck;
  74. }
  75. ctx.body = {
  76. code: 0,
  77. message: 'success',
  78. data: result
  79. };
  80. });
  81. /**
  82. * POST /api/book-generator/langgraph/detect-scale
  83. * AI 预览检测书籍规模(创建前调用,让用户看到检测结果)
  84. */
  85. router.post('/detect-scale', async (ctx) => {
  86. const { description } = ctx.request.body as { description?: string };
  87. if (!description) {
  88. ctx.body = { code: 1, message: '缺少 description' };
  89. return;
  90. }
  91. const scale = await autoDetectBookType('', description);
  92. const config = getScaleConfig(scale);
  93. ctx.body = {
  94. code: 0,
  95. data: {
  96. bookScale: scale,
  97. totalWords: config.totalWords,
  98. chapters: config.chapters,
  99. isShortArticle: config.isShortArticle,
  100. },
  101. };
  102. });
  103. /**
  104. * GET /api/book-generator/langgraph/book-types
  105. * 获取所有书籍类型配置(供前端显示)
  106. */
  107. router.get('/book-types', async (ctx: Context) => {
  108. const types = getAllBookTypes().map(t => ({
  109. key: t.key,
  110. label: t.label,
  111. description: t.description,
  112. chapters: t.chapters,
  113. totalWords: t.totalWords,
  114. audioMinutes: t.audioMinutes,
  115. chapterWords: t.chapterWords,
  116. structureFormat: t.structureFormat,
  117. readingDifficulty: t.readingDifficulty,
  118. isShortArticle: t.isShortArticle,
  119. }));
  120. ctx.body = {
  121. code: 0,
  122. message: 'success',
  123. data: types,
  124. };
  125. });
  126. /**
  127. * POST /api/book-generator/langgraph/detect-book-type
  128. * AI 自动检测书籍类型
  129. */
  130. router.post('/detect-book-type', async (ctx: Context) => {
  131. const { title, description } = ctx.request.body as {
  132. title?: string;
  133. description?: string;
  134. };
  135. if (!title) {
  136. ctx.status = 400;
  137. ctx.body = { code: 1, message: '请提供书籍标题' };
  138. return;
  139. }
  140. const detectableTypes = DETECTABLE_TYPES;
  141. // 构建类型特征描述,帮助 AI 分类
  142. const typeDescriptions = detectableTypes.map(key => {
  143. const t = BOOK_TYPE_CONFIG[key];
  144. return `- ${t.key}: ${t.description},${t.chapters}章,总字数约${t.totalWords}字,每章约${t.chapterWords}字,结构形式:${t.structureFormat},阅读难度:${t.readingDifficulty}`;
  145. }).join('\n');
  146. const messages: ChatMessage[] = [
  147. {
  148. role: 'system',
  149. content: `你是一位专业的图书分类编辑。根据用户提供的标题和描述,判断这本书最可能属于以下哪种类型:
  150. 可选类型:
  151. ${typeDescriptions}
  152. ## 分类规则
  153. 1. 分析标题中的关键词(如"科普""青少年""专业""小说"等)
  154. 2. 分析描述中的目标读者、写作风格、内容深度
  155. 3. 匹配最符合的类型
  156. ## 输出格式
  157. 必须返回 JSON,不要包含 markdown 代码块标记:
  158. {
  159. "detectedType": "类型 key",
  160. "confidence": 0.85,
  161. "reasoning": "分类理由,1-2句话"
  162. }
  163. confidence 是 0-1 的数值,表示置信程度。`,
  164. },
  165. {
  166. role: 'user',
  167. content: `标题:《${title}》\n描述:${description || '无'}`,
  168. },
  169. ];
  170. try {
  171. const response = await callLLMWithMessages(messages);
  172. const parsed = parseDetectResult(response);
  173. if (!parsed) {
  174. // 降级到关键词匹配
  175. const fallback = keywordFallback(title, description || '');
  176. ctx.body = {
  177. code: 0,
  178. message: 'success',
  179. data: {
  180. detectedType: fallback.detectedType,
  181. confidence: 0.5,
  182. reasoning: '基于关键词匹配(AI 解析失败,使用降级策略)',
  183. config: getBookTypeConfig(fallback.detectedType),
  184. },
  185. };
  186. return;
  187. }
  188. ctx.body = {
  189. code: 0,
  190. message: 'success',
  191. data: {
  192. detectedType: parsed.detectedType,
  193. confidence: parsed.confidence,
  194. reasoning: parsed.reasoning,
  195. config: getBookTypeConfig(parsed.detectedType),
  196. },
  197. };
  198. } catch (error: any) {
  199. // 最终降级:关键词匹配
  200. const fallback = keywordFallback(title, description || '');
  201. ctx.body = {
  202. code: 0,
  203. message: 'success',
  204. data: {
  205. detectedType: fallback.detectedType,
  206. confidence: 0.3,
  207. reasoning: 'LLM 调用失败,使用关键词匹配降级',
  208. config: getBookTypeConfig(fallback.detectedType),
  209. },
  210. };
  211. }
  212. });
  213. function parseDetectResult(text: string): { detectedType: string; confidence: number; reasoning: string } | null {
  214. try {
  215. const match = text.match(/\{[\s\S]*\}/);
  216. if (!match) return null;
  217. const data = JSON.parse(match[0]);
  218. if (!data.detectedType) return null;
  219. // 验证类型是否有效
  220. if (!DETECTABLE_TYPES.includes(data.detectedType)) {
  221. // 尝试模糊匹配
  222. const found = DETECTABLE_TYPES.find(t => data.detectedType.includes(t) || t.includes(data.detectedType));
  223. if (!found) return null;
  224. data.detectedType = found;
  225. }
  226. return {
  227. detectedType: data.detectedType,
  228. confidence: Math.min(1, Math.max(0, data.confidence || 0.5)),
  229. reasoning: data.reasoning || '',
  230. };
  231. } catch {
  232. return null;
  233. }
  234. }
  235. function keywordFallback(_title: string, _description: string): { detectedType: string } {
  236. // 完全由 AI 判断,fallback 只在 LLM 完全失败时作为最后保险
  237. return { detectedType: '1000' }; // 最小规模
  238. }
  239. /**
  240. * AI 根据描述自动生成书名
  241. */
  242. async function autoGenerateTitle(description: string, userId?: number): Promise<string> {
  243. return runWithContext({ userId }, async () => {
  244. const prompt = `根据以下描述起一个书名。要求:中文不超过20字,英文不超过20个单词。只返回书名,不要任何解释、思考或前缀。
  245. 描述:${description.substring(0, 200)}
  246. 书名:`;
  247. try {
  248. const response = await callLLM(prompt);
  249. const title = cleanLlmShortText(response, {
  250. maxLength: 50,
  251. maxChineseChars: 20,
  252. maxEnglishWords: 20,
  253. });
  254. console.log(`[LangGraph] AI 生成书名: "${title}"`);
  255. return title || '未命名书籍';
  256. } catch (e) {
  257. console.warn('[LangGraph] AI 自动生成书名失败,使用默认:', e);
  258. return '未命名书籍';
  259. }
  260. });
  261. }
  262. /**
  263. * AI 自动检测书籍规模(字数等级),后端静默调用
  264. * AI 分析描述中的字数要求,以 JSON 格式返回,供程序提取
  265. */
  266. async function autoDetectBookType(title: string, description: string, userId?: number): Promise<string> {
  267. return runWithContext({ userId }, async () => {
  268. console.log(`[autoDetectBookType] 被调用: title="${title}", desc前50="${description?.substring(0, 50)}"`);
  269. const messages: ChatMessage[] = [
  270. {
  271. role: 'system',
  272. content: `你是一位专业的图书分类编辑。根据标题和描述,判断书籍适合的字数规模。
  273. ## 判断规则
  274. **规则1 - 字数直接返回**:如果描述里有"X字"(如"200字""500字""几千字"),直接返回X作为bookScale值,不要映射到预定义规模。
  275. - 描述含"200字"→返回200
  276. - 描述含"500字"→返回500
  277. - 描述含"几千字"→估计约3000,返回3000
  278. - 描述含"上万字"→估计约10000,返回10000
  279. **规则2 - 无法判断**:描述中没有字数信息 → 返回1000
  280. ## 输出格式(必须严格JSON)
  281. {"bookScale": 数字}
  282. 只返回JSON,不要任何其他文字。`,
  283. },
  284. {
  285. role: 'user',
  286. content: `标题:《${title}》\n描述:${description}`,
  287. },
  288. ];
  289. try {
  290. const response = await callLLMWithMessages(messages);
  291. const trimmed = response.trim();
  292. console.log(`[autoDetectBookType] AI原始响应: ${trimmed.substring(0, 200)}`);
  293. const jsonMatch = trimmed.match(/\{[\s\S]*\}/);
  294. if (jsonMatch) {
  295. try {
  296. const data = JSON.parse(jsonMatch[0]);
  297. if (typeof data.bookScale === 'number') {
  298. const wordCount = data.bookScale;
  299. console.log(`[autoDetectBookType] AI返回: bookScale=${wordCount}`);
  300. return String(wordCount);
  301. }
  302. } catch {
  303. // JSON解析失败,忽略
  304. }
  305. }
  306. console.log(`[autoDetectBookType] AI响应无法解析,使用默认值1000`);
  307. return '1000';
  308. } catch (error: any) {
  309. console.error(`[autoDetectBookType] AI调用异常:`, error?.message || error);
  310. return '1000';
  311. }
  312. });
  313. }
  314. /**
  315. * POST /api/book-generator/langgraph/smart-recommend
  316. * 根据书籍描述智能推荐难度、人群、风格、领域
  317. */
  318. router.post('/smart-recommend', async (ctx: Context) => {
  319. try {
  320. const { description, title } = ctx.request.body as { description: string; title?: string };
  321. if (!description || !description.trim()) {
  322. ctx.status = 400;
  323. ctx.body = { code: 1, message: '描述不能为空' };
  324. return;
  325. }
  326. // 默认推荐值
  327. const defaultResult = {
  328. knowledgeLevel: '入门',
  329. targetAudience: '通用',
  330. style: '轻松幽默',
  331. industry: '教育',
  332. reason: '默认推荐',
  333. };
  334. const prompt = `根据以下书籍描述,推荐合适的知识难度、目标人群、写作风格和行业领域。
  335. 书名:${title || '未命名'}
  336. 描述:${description}
  337. 请以 JSON 格式返回推荐结果,不要包含任何其他文字:
  338. {
  339. "knowledgeLevel": "入门|进阶|专业",
  340. "targetAudience": "推荐的目标人群",
  341. "style": "推荐风格",
  342. "industry": "推荐行业领域",
  343. "reason": "简要说明推荐理由"
  344. }`;
  345. const messages: ChatMessage[] = [
  346. { role: 'system', content: '你是一位专业的图书策划编辑,擅长根据书籍内容推荐合适的定位。' },
  347. { role: 'user', content: prompt },
  348. ];
  349. const response = await callLLMWithMessages(messages);
  350. const result = extractJsonFromResponse(response) || defaultResult;
  351. ctx.body = { code: 0, message: 'success', data: result };
  352. } catch (error) {
  353. console.error('智能推荐失败:', error);
  354. // 返回默认值而不是错误
  355. ctx.body = {
  356. code: 0,
  357. message: 'success',
  358. data: {
  359. knowledgeLevel: '入门',
  360. targetAudience: '通用',
  361. style: '轻松幽默',
  362. industry: '教育',
  363. reason: 'AI服务暂时不可用,使用默认推荐',
  364. },
  365. };
  366. }
  367. });
  368. /**
  369. * POST /api/book-generator/langgraph/books
  370. * 使用 LangGraph 创建并生成书籍(异步,自动生成大纲和内容)
  371. * AI 根据标题+描述自动判断书籍类型
  372. *
  373. * 优化策略:
  374. * 1. 并行执行 autoGenerateTitle + autoDetectBookType(串行→并行,耗时减半)
  375. * 2. 先创建书籍返回响应,AI 结果异步回填(用户无需等待 AI 完成即可看到书籍)
  376. */
  377. router.post('/books', optionalAuth, async (ctx: Context) => {
  378. try {
  379. const body = ctx.request.body as {
  380. title: string;
  381. description: string;
  382. bookScale?: string;
  383. bookType?: string;
  384. genLevel?: number;
  385. generateForeword?: boolean;
  386. generateAfterword?: boolean;
  387. immediateGenerate?: boolean;
  388. voiceSpeed?: number;
  389. };
  390. if (!body.description) {
  391. ctx.status = 400;
  392. ctx.body = { code: 1, message: '描述不能为空' };
  393. return;
  394. }
  395. // 获取用户 ID(未登录时使用测试用户)
  396. const userId = ctx.state.user?.userId ? parseInt(ctx.state.user.userId as string) : parseInt(TEST_USER_ID);
  397. const providedTitle = body.title?.trim();
  398. // 只接受数字格式的 bookScale(如 '200', '1000', '130000'),非数字当作未提供
  399. const providedBookScale = body.bookScale && /^\d+$/.test(body.bookScale) ? body.bookScale : undefined;
  400. // ========== 语速决策 ==========
  401. // 规则(更新于 2026-06-14):
  402. // 1. 用户显式传了 voiceSpeed → 直接用用户的(userSpecifiedVoiceSpeed=true)
  403. // 2. 用户没传 → 占位 1.0,由 plan 节点 AI 归纳后写回 book.voiceSpeed
  404. // (Plan 节点会输出 suggestedSpeed,持久化时覆盖 voiceSpeed 字段)
  405. const userSpecifiedVoiceSpeed = (body.voiceSpeed !== undefined && body.voiceSpeed !== null);
  406. const finalVoiceSpeed = userSpecifiedVoiceSpeed
  407. ? body.voiceSpeed
  408. : DEFAULT_VOICE_SPEED; // 临时占位,AI 规划后会被覆盖
  409. // ========== 快速路径:用户已提供 title 和 bookScale,无需 AI ==========
  410. if (providedTitle && providedBookScale) {
  411. const bookScale = providedBookScale;
  412. const genLevel = body.genLevel !== undefined
  413. ? resolveGenLevel(bookScale, body.genLevel)
  414. : body.bookType && body.bookType !== 'auto'
  415. ? mapBookTypeToGenLevel(body.bookType)
  416. : resolveGenLevel(bookScale);
  417. const scaleConfig = getScaleConfig(bookScale);
  418. const totalWords = scaleConfig.totalWords;
  419. // 风控:预估费用 + 原子预留
  420. const estimatedCost = AUDIO_BILLING_CONFIG.pricing.monthly * estimateAudioMinutesFromWords(totalWords) + 0.05; // +LLM预估
  421. const quotaOk = await atomicReserveQuota(userId, estimatedCost);
  422. if (!quotaOk) {
  423. ctx.status = 403;
  424. ctx.body = { code: 1, message: '月度额度不足,请升级套餐', data: { estimatedCost, estimatedWords: totalWords } };
  425. return;
  426. }
  427. const audioQuota = await checkAudioQuota(userId, totalWords);
  428. if (!audioQuota.allowed) {
  429. await releaseQuota(userId, estimatedCost); // 退回预留
  430. ctx.status = 403;
  431. ctx.body = { code: 1, message: audioQuota.reason, data: { estimatedWords: totalWords, estimatedAudioMinutes: estimateAudioMinutesFromWords(totalWords), remainingMinutes: audioQuota.remainingMinutes, totalMinutes: audioQuota.totalMinutes } };
  432. return;
  433. }
  434. const book = await bookStore.create({
  435. userId,
  436. title: providedTitle,
  437. description: body.description,
  438. bookScale,
  439. totalChapters: scaleConfig.isShortArticle ? 1 : scaleConfig.chapters,
  440. estimatedWords: totalWords,
  441. voiceSpeed: finalVoiceSpeed,
  442. });
  443. console.log(`[LangGraph.fastPath] finalVoiceSpeed=${finalVoiceSpeed}, type=${typeof finalVoiceSpeed}, body.voiceSpeed=${body.voiceSpeed}`);
  444. if (body.immediateGenerate === false) {
  445. ctx.body = { code: 0, message: '书籍创建成功(交互模式)', data: { book, genStage: 'draft', mode: 'interactive' } };
  446. return;
  447. }
  448. await bookStore.update(book.id, { genStage: 'outlining' });
  449. langGraphGenerator.generate(book.id.toString(), body.description, bookScale, genLevel, userId, userSpecifiedVoiceSpeed)
  450. .then(() => console.log(`[LangGraph] 生成完成: bookId=${book.id}`))
  451. .catch(err => {
  452. console.error(`[LangGraph] 生成失败: bookId=${book.id}`, err);
  453. bookStore.update(book.id.toString(), { genStage: 'failed', errorMsg: err instanceof Error ? err.message : '生成失败', failedStage: 'outlining' });
  454. });
  455. ctx.body = { code: 0, message: '书籍创建成功,生成已开始', data: { book, genStage: 'outlining', mode: 'async' } };
  456. return;
  457. }
  458. // ========== 需要 AI 辅助的路径:先创建书籍,再异步回填 ==========
  459. // 使用临时标题/默认规模先创建书籍,立即返回给前端
  460. // 规模会由 AI 异步回填,配额也会相应调整
  461. const fallbackScale = providedBookScale || '1000';
  462. const fallbackTitle = providedTitle || '正在生成标题...';
  463. const fallbackConfig = getScaleConfig(fallbackScale);
  464. const fallbackWords = fallbackConfig.totalWords;
  465. const fallbackCost = AUDIO_BILLING_CONFIG.pricing.monthly * estimateAudioMinutesFromWords(fallbackWords) + 0.05;
  466. // 配额预检查 + 原子预留(使用 fallback 规模估算)
  467. const audioQuota = await checkAudioQuota(userId, fallbackWords);
  468. if (!audioQuota.allowed) {
  469. ctx.status = 403;
  470. ctx.body = { code: 1, message: audioQuota.reason, data: { estimatedWords: fallbackWords, estimatedAudioMinutes: estimateAudioMinutesFromWords(fallbackWords), remainingMinutes: audioQuota.remainingMinutes, totalMinutes: audioQuota.totalMinutes } };
  471. return;
  472. }
  473. // 原子预留 fallback 配额,防止并发请求超发
  474. const reserveOk = await atomicReserveQuota(userId, fallbackCost);
  475. if (!reserveOk) {
  476. ctx.status = 403;
  477. ctx.body = { code: 1, message: '月度额度不足,请升级套餐', data: { estimatedCost: fallbackCost, estimatedWords: fallbackWords } };
  478. return;
  479. }
  480. // 先创建书籍,立即返回
  481. const book = await bookStore.create({
  482. userId,
  483. title: fallbackTitle,
  484. description: body.description,
  485. bookScale: fallbackScale,
  486. totalChapters: fallbackConfig.isShortArticle ? 1 : fallbackConfig.chapters,
  487. estimatedWords: fallbackWords,
  488. voiceSpeed: finalVoiceSpeed,
  489. });
  490. // 标记为 AI 正在准备中
  491. const needTitle = !providedTitle;
  492. const needScale = !providedBookScale;
  493. const aiPreparing = needTitle || needScale;
  494. if (body.immediateGenerate === false) {
  495. // 交互模式:异步填充 AI 结果,但不需要启动生成
  496. if (aiPreparing) {
  497. fillAiResultsAsync(book.id.toString(), body.description, providedTitle, providedBookScale, userId);
  498. }
  499. // 交互模式暂不调整配额,等用户真正开始生成时再做
  500. ctx.body = { code: 0, message: '书籍创建成功(交互模式)', data: { book, genStage: 'draft', mode: 'interactive', aiPreparing } };
  501. return;
  502. }
  503. // 非交互模式:需要等 AI 完成后才能确定 bookScale/genLevel 启动生成
  504. await bookStore.update(book.id, { genStage: 'outlining' });
  505. // 立即返回响应
  506. ctx.body = {
  507. code: 0,
  508. message: '书籍创建成功,AI 正在准备标题和规模...',
  509. data: {
  510. book,
  511. genStage: 'outlining',
  512. mode: 'async',
  513. aiPreparing,
  514. },
  515. };
  516. // 异步:并行执行 AI 生成标题 + 检测规模,然后启动内容生成
  517. (async () => {
  518. try {
  519. let title = providedTitle;
  520. let bookScale = providedBookScale;
  521. // 并行执行 AI 调用
  522. const aiPromises: Promise<any>[] = [];
  523. const titleIdx = needTitle ? aiPromises.push(autoGenerateTitle(body.description, userId)) - 1 : -1;
  524. const scaleIdx = needScale ? aiPromises.push(autoDetectBookType(providedTitle || '', body.description, userId)) - 1 : -1;
  525. if (aiPromises.length > 0) {
  526. const results = await Promise.all(aiPromises);
  527. if (titleIdx >= 0) {
  528. title = results[titleIdx] as string;
  529. console.log(`[LangGraph] AI 自动生成书名: "${title}"`);
  530. }
  531. if (scaleIdx >= 0) {
  532. bookScale = results[scaleIdx] as string;
  533. console.log(`[LangGraph] AI 自动检测规模: ${title} -> ${bookScale}`);
  534. }
  535. }
  536. // 回填 AI 结果到数据库
  537. const scaleConfig = getScaleConfig(bookScale!);
  538. const actualWords = scaleConfig.totalWords;
  539. const actualCost = AUDIO_BILLING_CONFIG.pricing.monthly * estimateAudioMinutesFromWords(actualWords) + 0.05;
  540. // 调整配额预留:从 fallback 切换到实际规模
  541. if (bookScale !== fallbackScale) {
  542. await releaseQuota(userId, fallbackCost);
  543. const adjustOk = await atomicReserveQuota(userId, actualCost);
  544. if (!adjustOk) {
  545. console.error(`[LangGraph] 实际规模配额不足,回退到 fallback: bookId=${book.id}, actual=${actualCost}, fallback=${fallbackCost}`);
  546. // fallback 规模已在之前预留,继续使用
  547. } else {
  548. console.log(`[LangGraph] 配额已调整: fallback=${fallbackCost} -> actual=${actualCost}, bookId=${book.id}`);
  549. }
  550. }
  551. await bookStore.update(book.id.toString(), {
  552. title: title!,
  553. bookScale: bookScale!,
  554. totalChapters: scaleConfig.isShortArticle ? 1 : scaleConfig.chapters,
  555. estimatedWords: actualWords,
  556. });
  557. // 确定生成层级并启动内容生成
  558. const genLevel = body.genLevel !== undefined
  559. ? resolveGenLevel(bookScale!, body.genLevel)
  560. : body.bookType && body.bookType !== 'auto'
  561. ? mapBookTypeToGenLevel(body.bookType)
  562. : resolveGenLevel(bookScale!);
  563. await langGraphGenerator.generate(book.id.toString(), body.description, bookScale!, genLevel, userId, userSpecifiedVoiceSpeed);
  564. console.log(`[LangGraph] 生成完成: bookId=${book.id}`);
  565. } catch (err) {
  566. console.error(`[LangGraph] AI 准备或生成失败: bookId=${book.id}`, err);
  567. // 释放预留配额
  568. await releaseQuota(userId, fallbackCost);
  569. bookStore.update(book.id.toString(), {
  570. genStage: 'failed',
  571. errorMsg: err instanceof Error ? err.message : '生成失败',
  572. failedStage: 'outlining',
  573. });
  574. }
  575. })();
  576. } catch (error) {
  577. console.error('启动失败:', error);
  578. ctx.status = 500;
  579. ctx.body = {
  580. code: 1,
  581. message: error instanceof Error ? error.message : '启动失败',
  582. };
  583. }
  584. });
  585. /**
  586. * 异步填充 AI 结果(交互模式使用,不启动生成)
  587. */
  588. async function fillAiResultsAsync(
  589. bookId: string,
  590. description: string,
  591. providedTitle?: string,
  592. providedBookScale?: string,
  593. userId?: number,
  594. ): Promise<void> {
  595. console.log(`[fillAiResultsAsync] 开始: bookId=${bookId}, providedTitle="${providedTitle}", providedBookScale="${providedBookScale}", desc前50字="${description?.substring(0, 50)}"`);
  596. try {
  597. let title = providedTitle;
  598. let bookScale = providedBookScale;
  599. const needTitle = !title;
  600. const needScale = !bookScale;
  601. const aiPromises: Promise<any>[] = [];
  602. const titleIdx = needTitle ? aiPromises.push(autoGenerateTitle(description, userId)) - 1 : -1;
  603. const scaleIdx = needScale ? aiPromises.push(autoDetectBookType(title || '', description, userId)) - 1 : -1;
  604. if (aiPromises.length > 0) {
  605. const results = await Promise.all(aiPromises);
  606. if (titleIdx >= 0) {
  607. title = results[titleIdx] as string;
  608. console.log(`[LangGraph] AI 自动生成书名 (交互): "${title}"`);
  609. }
  610. if (scaleIdx >= 0) {
  611. bookScale = results[scaleIdx] as string;
  612. console.log(`[LangGraph] AI 自动检测规模 (交互): ${title} -> ${bookScale}`);
  613. }
  614. }
  615. const scaleConfig = getScaleConfig(bookScale!);
  616. await bookStore.update(bookId.toString(), {
  617. title: title!,
  618. bookScale: bookScale!,
  619. totalChapters: scaleConfig.isShortArticle ? 1 : scaleConfig.chapters,
  620. estimatedWords: scaleConfig.totalWords,
  621. });
  622. } catch (err) {
  623. console.warn(`[LangGraph] AI 异步填充失败: bookId=${bookId}`, err);
  624. }
  625. }
  626. /**
  627. * GET /api/book-generator/langgraph/books
  628. * 获取书籍列表
  629. * 返回:公开的书籍(有公开音频)+ 当前用户自己的书籍
  630. * 注意:此接口已废弃,请使用 /public-books 或 /my-books
  631. */
  632. router.get('/books', optionalAuth, async (ctx: Context) => {
  633. try {
  634. const userId = ctx.state.user?.userId;
  635. const userIdNum = userId ? parseInt(userId as string) : undefined;
  636. // 获取公开书籍(有公开音频的书籍)
  637. const publicBooks = await bookStore.getPublicBooks();
  638. // 如果用户已登录,获取用户自己的书籍
  639. let userBooks: any[] = [];
  640. if (userIdNum) {
  641. userBooks = await bookStore.getAllByUser(userIdNum, false);
  642. }
  643. // 合并并去重(按 id)
  644. const bookMap = new Map<string, any>();
  645. publicBooks.forEach(b => bookMap.set(b.id, b));
  646. userBooks.forEach(b => {
  647. if (!bookMap.has(b.id)) {
  648. bookMap.set(b.id, b);
  649. }
  650. });
  651. const books = Array.from(bookMap.values());
  652. ctx.body = { code: 0, message: 'success', data: { books } };
  653. } catch (error) {
  654. console.error('查询失败:', error);
  655. ctx.status = 500;
  656. ctx.body = { code: 1, message: error instanceof Error ? error.message : '查询失败' };
  657. }
  658. });
  659. /**
  660. * GET /api/book-generator/langgraph/public-books
  661. * 获取公开书籍列表(首页专用)
  662. * 只返回有公开音频的书籍
  663. */
  664. router.get('/public-books', async (ctx: Context) => {
  665. try {
  666. const publicBooks = await bookStore.getPublicBooks();
  667. ctx.body = { code: 0, message: 'success', data: { books: publicBooks } };
  668. } catch (error) {
  669. console.error('查询公开书籍失败:', error);
  670. ctx.status = 500;
  671. ctx.body = { code: 1, message: error instanceof Error ? error.message : '查询失败' };
  672. }
  673. });
  674. /**
  675. * GET /api/book-generator/langgraph/my-books
  676. * 获取当前用户自己的书籍列表(管理页专用)
  677. * 只返回当前用户创建的书籍
  678. */
  679. router.get('/my-books', optionalAuth, async (ctx: Context) => {
  680. try {
  681. const userId = ctx.state.user?.userId;
  682. if (!userId) {
  683. ctx.status = 401;
  684. ctx.body = { code: 1, message: '请先登录' };
  685. return;
  686. }
  687. const userBooks = await bookStore.getAllByUser(parseInt(userId as string), false);
  688. ctx.body = { code: 0, message: 'success', data: { books: userBooks } };
  689. } catch (error) {
  690. console.error('查询用户书籍失败:', error);
  691. ctx.status = 500;
  692. ctx.body = { code: 1, message: error instanceof Error ? error.message : '查询失败' };
  693. }
  694. });
  695. /**
  696. * PUT /api/book-generator/langgraph/books/:id/publish
  697. * 切换书籍公开状态
  698. */
  699. router.put('/books/:id/publish', optionalAuth, async (ctx: Context) => {
  700. try {
  701. const bookId = ctx.params.id;
  702. const newStatus = await bookStore.togglePublish(bookId);
  703. ctx.body = {
  704. code: 0,
  705. message: 'success',
  706. data: { isPublished: newStatus }
  707. };
  708. } catch (error) {
  709. console.error('切换发布状态失败:', error);
  710. ctx.status = 500;
  711. ctx.body = { code: 1, message: error instanceof Error ? error.message : '操作失败' };
  712. }
  713. });
  714. /**
  715. * GET /api/book-generator/langgraph/books/:id
  716. * 获取书籍详情
  717. * 支持公开过滤:?filterPublic=true&userId=1
  718. */
  719. router.get('/books/:id', optionalAuth, async (ctx: Context) => {
  720. try {
  721. const bookId = ctx.params.id as string;
  722. const userId = ctx.state.user?.userId || TEST_USER_ID;
  723. const filterPublic = ctx.query.filterPublic === 'true';
  724. const book = await bookStore.getById(bookId, filterPublic, parseInt(userId as string));
  725. if (!book) {
  726. ctx.status = 404;
  727. ctx.body = { code: 1, message: '书籍不存在' };
  728. return;
  729. }
  730. ctx.body = { code: 0, message: 'success', data: { book } };
  731. } catch (error) {
  732. console.error('查询失败:', error);
  733. ctx.status = 500;
  734. ctx.body = { code: 1, message: error instanceof Error ? error.message : '查询失败' };
  735. }
  736. });
  737. /**
  738. * GET /api/book-generator/langgraph/books/:id/progress
  739. * 获取书籍生成进度
  740. */
  741. router.get('/books/:id/progress', async (ctx: Context) => {
  742. try {
  743. const bookId = ctx.params.id as string;
  744. const book = await bookStore.getById(bookId);
  745. if (!book) {
  746. ctx.status = 404;
  747. ctx.body = { code: 1, message: '书籍不存在' };
  748. return;
  749. }
  750. // 计算实际进度(基于章节完成情况)
  751. const completedChapters = book.chapters.filter((c) => c.genStage === 'video_completed').length;
  752. const totalChapters = book.outline?.chapters?.length || book.totalChapters || 0;
  753. // 查找当前正在生成的章节
  754. const currentGenerating = book.chapters.find(
  755. (c) => c.genStage === 'content_generating' || c.genStage === 'audio_generating' || c.genStage === 'video_generating'
  756. );
  757. const currentChapter = currentGenerating
  758. ? { number: currentGenerating.number, title: currentGenerating.title, level: currentGenerating.level }
  759. : null;
  760. // 如果有大纲,使用大纲章节数计算进度
  761. let progress = book.progress;
  762. if (totalChapters > 0 && book.genStage !== 'video_completed') {
  763. progress = Math.round((completedChapters / totalChapters) * 100);
  764. }
  765. ctx.body = {
  766. code: 0,
  767. message: 'success',
  768. data: {
  769. bookId,
  770. genStage: book.genStage,
  771. progress,
  772. completedChapters,
  773. totalChapters,
  774. currentChapter,
  775. },
  776. };
  777. } catch (error) {
  778. console.error('查询进度失败:', error);
  779. ctx.status = 500;
  780. ctx.body = { code: 1, message: error instanceof Error ? error.message : '查询失败' };
  781. }
  782. });
  783. /**
  784. * DELETE /api/book-generator/langgraph/books/:id
  785. * 删除书籍
  786. */
  787. router.delete('/books/:id', async (ctx: Context) => {
  788. try {
  789. const bookId = ctx.params.id as string;
  790. await bookStore.delete(bookId);
  791. ctx.body = { code: 0, message: '删除成功' };
  792. } catch (error) {
  793. console.error('删除失败:', error);
  794. ctx.status = 500;
  795. ctx.body = { code: 1, message: error instanceof Error ? error.message : '删除失败' };
  796. }
  797. });
  798. /**
  799. * POST /api/book-generator/langgraph/books/:id/generate
  800. * 对已有书籍使用 LangGraph 生成
  801. */
  802. router.post('/books/:id/generate', optionalAuth, async (ctx: Context) => {
  803. try {
  804. const bookId = ctx.params.id as string;
  805. console.log(`[LangGraph Generate] 收到请求 bookId=${bookId}`);
  806. const body = (ctx.request.body || {}) as { bookScale?: string; genLevel?: number };
  807. const book = await bookStore.getById(bookId);
  808. console.log(`[LangGraph Generate] book对象:`, book ? '存在' : 'null');
  809. if (!book) {
  810. ctx.status = 404;
  811. ctx.body = { code: 1, message: '书籍不存在' };
  812. return;
  813. }
  814. // ========== 确定 bookScale ==========
  815. // 优先级(避免覆盖用户已选值):
  816. // 1) 请求显式指定(body.bookScale)→ 用户选的,直接用
  817. // 2) 书籍已有规模(book.bookScale)→ 重新生成时沿用,不再让 AI 重新判断
  818. // (避免描述无明确字数时被 AI 误判为 1000,覆盖原值导致章节缩水)
  819. // 3) AI 根据描述自动检测 → 仅首次生成、无任何来源时
  820. // 4) 兜底 → 1000(最小规模)
  821. let bookScale: string | undefined;
  822. if (body.bookScale && BOOK_TYPE_CONFIG[body.bookScale]) {
  823. // 用户在当前请求中显式选了规模
  824. bookScale = body.bookScale;
  825. console.log(`[LangGraph Generate] 使用请求指定的 bookScale=${bookScale}`);
  826. } else if (book.bookScale && BOOK_TYPE_CONFIG[book.bookScale]) {
  827. // 重新生成场景:沿用书籍已有规模,避免 AI 把"认知心理学"等无字数描述误判为 1000
  828. bookScale = book.bookScale;
  829. console.log(`[LangGraph Generate] 沿用书籍已有 bookScale=${bookScale}`);
  830. } else {
  831. // 首次生成 + 无显式选择 → 让 AI 根据描述判断
  832. const desc = book.description || '';
  833. try {
  834. console.log(`[LangGraph Generate] AI 自动检测规模...`);
  835. bookScale = await autoDetectBookType(book.title || '', desc, book.userId ?? undefined);
  836. console.log(`[LangGraph Generate] AI 检测结果 → bookScale=${bookScale}`);
  837. } catch (e) {
  838. console.warn(`[LangGraph Generate] AI 检测失败,回退:`, e);
  839. }
  840. // AI 失败或返回无效值 → 兜底 1000
  841. if (!bookScale || !BOOK_TYPE_CONFIG[bookScale]) {
  842. bookScale = '1000';
  843. }
  844. }
  845. // 持久化检测结果
  846. if (bookScale !== book.bookScale) {
  847. await bookStore.update(bookId, { bookScale });
  848. }
  849. const genLevel = resolveGenLevel(bookScale, body.genLevel, book.description);
  850. // ========== 生成前配额检查 ==========
  851. const userId = ctx.state.user?.userId ? parseInt(ctx.state.user.userId as string) : (book.userId || parseInt(TEST_USER_ID));
  852. const scaleConfig = getScaleConfig(bookScale);
  853. const totalWords = scaleConfig.totalWords;
  854. // 风控预估
  855. const estimatedCost = AUDIO_BILLING_CONFIG.pricing.monthly * estimateAudioMinutesFromWords(totalWords) + 0.05;
  856. const quotaOk = await atomicReserveQuota(userId, estimatedCost);
  857. if (!quotaOk) {
  858. ctx.status = 403;
  859. ctx.body = { code: 1, message: '月度额度不足,请升级套餐' };
  860. return;
  861. }
  862. const audioQuota = await checkAudioQuota(userId, totalWords);
  863. if (!audioQuota.allowed) {
  864. await releaseQuota(userId, estimatedCost);
  865. ctx.status = 403;
  866. ctx.body = {
  867. code: 1,
  868. message: audioQuota.reason,
  869. data: {
  870. estimatedWords: totalWords,
  871. estimatedAudioMinutes: estimateAudioMinutesFromWords(totalWords),
  872. remainingMinutes: audioQuota.remainingMinutes,
  873. totalMinutes: audioQuota.totalMinutes,
  874. }
  875. };
  876. return;
  877. }
  878. // 防止重复生成:如果书籍正在生成中,拒绝请求
  879. if (book.genStage === 'content_generating' || book.genStage === 'audio_generating' || book.genStage === 'video_generating') {
  880. console.log(`[LangGraph Generate] 书籍正在生成中,拒绝重复请求 bookId=${bookId}`);
  881. ctx.status = 400;
  882. ctx.body = {
  883. code: 1,
  884. message: '书籍正在生成中,请勿重复提交',
  885. data: {
  886. bookId,
  887. genStage: book.genStage,
  888. progress: book.progress,
  889. }
  890. };
  891. return;
  892. }
  893. // 异步生成(跳过队列,开发环境下队列不可靠)
  894. // 先清理旧章节,避免扩缩后残留孤儿数据
  895. await bookStore.deleteAllChapters(bookId);
  896. await bookStore.update(bookId, { genStage: 'outlining', totalChapters: 0, progress: 0 });
  897. langGraphGenerator.generate(bookId, book.description, bookScale, genLevel, userId, false)
  898. .then(async () => {
  899. console.log(`[LangGraph] 生成完成: bookId=${bookId}`);
  900. // 根据实际章节状态更新书籍 genStage
  901. const chapters = await bookStore.getChapterTree(bookId);
  902. const leafNodes = chapters.filter((c: any) => {
  903. const maxLevel = Math.max(...chapters.map((ch: any) => ch.level || 0));
  904. return c.level === maxLevel;
  905. });
  906. const allContentDone = leafNodes.length > 0 && leafNodes.every((c: any) => c.genStage === 'content_completed' || c.genStage === 'audio_completed' || c.genStage === 'video_completed');
  907. const allAudioDone = leafNodes.length > 0 && leafNodes.every((c: any) => c.genStage === 'audio_completed' || c.genStage === 'video_completed');
  908. const finalStage = allAudioDone ? 'audio_completed' : allContentDone ? 'content_completed' : 'outlining';
  909. await bookStore.update(bookId, { genStage: finalStage, progress: 100 });
  910. console.log(`[LangGraph] 最终状态: ${finalStage}, 叶节点: ${leafNodes.length}`);
  911. })
  912. .catch(err => {
  913. console.error(`[LangGraph] 生成失败: bookId=${bookId}`, err);
  914. bookStore.update(bookId, {
  915. genStage: 'failed', failedStage: 'outlining',
  916. errorMsg: err instanceof Error ? err.message : '生成失败',
  917. });
  918. });
  919. ctx.body = {
  920. code: 0,
  921. message: 'LangGraph 生成任务已启动',
  922. data: { bookId, genStage: 'outlining', mode: 'async' },
  923. };
  924. } catch (error) {
  925. console.error('启动失败:', error);
  926. ctx.status = 500;
  927. ctx.body = {
  928. code: 1,
  929. message: error instanceof Error ? error.message : '启动失败',
  930. };
  931. }
  932. });
  933. /**
  934. * POST /api/book-generator/langgraph/books/:id/audio
  935. * 批量生成书籍所有小节的音频
  936. */
  937. router.post('/books/:id/audio', async (ctx: Context) => {
  938. try {
  939. const bookId = ctx.params.id as string;
  940. const { voiceId = 'longyingling_v3' } = ctx.request.body as { voiceId?: string };
  941. const book = await bookStore.getById(bookId);
  942. if (!book) {
  943. ctx.status = 404;
  944. ctx.body = { code: 1, message: '书籍不存在' };
  945. return;
  946. }
  947. // 获取章节树
  948. const chapters = await bookStore.getChapterTree(bookId);
  949. // 动态获取叶节点层级(最大level值)
  950. const maxLevel = chapters.length > 0
  951. ? Math.max(...chapters.map((c: any) => c.level || 0))
  952. : 0;
  953. if (maxLevel === 0) {
  954. ctx.body = { code: 1, message: '没有章节' };
  955. return;
  956. }
  957. // 获取叶节点(最大level的所有节点)
  958. const leafNodes = chapters.filter((c: any) => c.level === maxLevel);
  959. // 检查内容状态 - 叶节点必须有content且genStage为content_completed
  960. const leafNodesWithContent = leafNodes.filter((c: any) => c.content && c.genStage === 'content_completed');
  961. if (leafNodes.length === 0) {
  962. ctx.body = { code: 1, message: `没有${maxLevel === 3 ? '小节' : maxLevel === 2 ? '节' : '章节'}` };
  963. return;
  964. }
  965. if (leafNodesWithContent.length === 0) {
  966. ctx.body = {
  967. code: 1,
  968. message: `没有内容生成完成的${maxLevel === 3 ? '小节' : maxLevel === 2 ? '节' : '章节'},请先生成内容`,
  969. data: {
  970. totalSubsections: leafNodes.length,
  971. completedSubsections: 0,
  972. }
  973. };
  974. return;
  975. }
  976. console.log(`[Audio] 书籍 ${bookId} 共有 ${leafNodes.length} 个${maxLevel === 3 ? '小节' : maxLevel === 2 ? '节' : '章节'},其中 ${leafNodesWithContent.length} 个内容已生成完成`);
  977. // 异步生成所有叶节点音频
  978. for (const sub of leafNodesWithContent) {
  979. bookStore.generateChapterAudioById(sub.id, book.userId || 1).catch(err => {
  980. console.error(`[Audio] ${maxLevel === 3 ? '小节' : '节'}${sub.number}音频生成失败:`, err);
  981. });
  982. }
  983. ctx.body = {
  984. code: 0,
  985. message: '音频生成任务已启动',
  986. data: {
  987. totalSubsections: leafNodesWithContent.length,
  988. taskId: `audio_${bookId}_${Date.now()}`,
  989. },
  990. };
  991. } catch (error) {
  992. console.error('音频生成失败:', error);
  993. ctx.status = 500;
  994. ctx.body = { code: 1, message: error instanceof Error ? error.message : '音频生成失败' };
  995. }
  996. });
  997. /**
  998. * POST /api/book-generator/langgraph/books/:id/audio/cancel
  999. * 取消书籍所有章节的音频生成
  1000. */
  1001. router.post('/books/:id/audio/cancel', async (ctx: Context) => {
  1002. try {
  1003. const bookId = ctx.params.id as string;
  1004. const book = await bookStore.getById(bookId);
  1005. if (!book) {
  1006. ctx.status = 404;
  1007. ctx.body = { code: 1, message: '书籍不存在' };
  1008. return;
  1009. }
  1010. const result = await cancelAudioGeneration(bookId);
  1011. if (result.cancelledCount === 0) {
  1012. ctx.body = {
  1013. code: 0,
  1014. message: '没有正在运行的音频生成任务',
  1015. data: result,
  1016. };
  1017. return;
  1018. }
  1019. console.log(`[Audio] 书籍 ${bookId} 取消音频生成,已取消 ${result.cancelledCount} 个任务,回退 ${result.rolledBackChapters.length} 个章节`);
  1020. ctx.body = {
  1021. code: 0,
  1022. message: `已取消 ${result.cancelledCount} 个音频生成任务`,
  1023. data: result,
  1024. };
  1025. } catch (error) {
  1026. console.error('取消音频生成失败:', error);
  1027. ctx.status = 500;
  1028. ctx.body = { code: 1, message: error instanceof Error ? error.message : '取消失败' };
  1029. }
  1030. });
  1031. /**
  1032. * GET /api/book-generator/langgraph/books/:id/video-status
  1033. * 获取书籍视频生成状态(用于前端轮询)
  1034. */
  1035. router.get('/books/:id/video-status', async (ctx: Context) => {
  1036. try {
  1037. const bookId = ctx.params.id as string;
  1038. const book = await bookStore.getById(bookId);
  1039. if (!book) {
  1040. ctx.status = 404;
  1041. ctx.body = { code: 1, message: '书籍不存在' };
  1042. return;
  1043. }
  1044. // 获取章节树
  1045. const chapters = await bookStore.getChapterTree(bookId);
  1046. // 动态获取叶节点层级
  1047. const maxLevel = chapters.length > 0
  1048. ? Math.max(...chapters.map((c: any) => c.level || 0))
  1049. : 0;
  1050. // 获取叶节点
  1051. const leafNodes = chapters.filter((c: any) => c.level === maxLevel);
  1052. // 统计视频状态
  1053. const total = leafNodes.length;
  1054. const completed = leafNodes.filter((c: any) => c.videoUrl && c.videoUrl !== '').length;
  1055. const pending = leafNodes.filter((c: any) => !c.videoUrl || c.videoUrl === '').length;
  1056. ctx.body = {
  1057. code: 0,
  1058. message: 'success',
  1059. data: {
  1060. bookId,
  1061. total,
  1062. completed,
  1063. pending,
  1064. allCompleted: completed >= total && total > 0,
  1065. },
  1066. };
  1067. } catch (error) {
  1068. console.error('获取视频状态失败:', error);
  1069. ctx.status = 500;
  1070. ctx.body = { code: 1, message: error instanceof Error ? error.message : '获取失败' };
  1071. }
  1072. });
  1073. /**
  1074. * GET /api/book-generator/langgraph/books/:id/audio-status
  1075. * 获取书籍音频生成状态(用于前端轮询)
  1076. */
  1077. router.get('/books/:id/audio-status', async (ctx: Context) => {
  1078. try {
  1079. const bookId = ctx.params.id as string;
  1080. const book = await bookStore.getById(bookId);
  1081. if (!book) {
  1082. ctx.status = 404;
  1083. ctx.body = { code: 1, message: '书籍不存在' };
  1084. return;
  1085. }
  1086. // 获取章节树
  1087. const chapters = await bookStore.getChapterTree(bookId);
  1088. // 动态获取叶节点层级
  1089. const maxLevel = chapters.length > 0
  1090. ? Math.max(...chapters.map((c: any) => c.level || 0))
  1091. : 0;
  1092. // 获取叶节点
  1093. const leafNodes = chapters.filter((c: any) => c.level === maxLevel);
  1094. // 统计音频状态
  1095. const total = leafNodes.length;
  1096. const completed = leafNodes.filter((c: any) => c.audioUrl && c.audioUrl !== '').length;
  1097. const pending = leafNodes.filter((c: any) => !c.audioUrl || c.audioUrl === '').length;
  1098. ctx.body = {
  1099. code: 0,
  1100. message: 'success',
  1101. data: {
  1102. bookId,
  1103. total,
  1104. completed,
  1105. pending,
  1106. allCompleted: completed >= total && total > 0,
  1107. },
  1108. };
  1109. } catch (error) {
  1110. console.error('获取音频状态失败:', error);
  1111. ctx.status = 500;
  1112. ctx.body = { code: 1, message: error instanceof Error ? error.message : '获取失败' };
  1113. }
  1114. });
  1115. /**
  1116. * GET /api/book-generator/langgraph/books/:id/failed-chapters
  1117. * 获取生成失败的小节列表
  1118. */
  1119. router.get('/books/:id/failed-chapters', async (ctx: Context) => {
  1120. try {
  1121. const bookId = ctx.params.id as string;
  1122. const book = await bookStore.getById(bookId);
  1123. if (!book) {
  1124. ctx.status = 404;
  1125. ctx.body = { code: 1, message: '书籍不存在' };
  1126. return;
  1127. }
  1128. // 获取所有失败的小节
  1129. const chapters = await bookStore.getChapterTree(bookId);
  1130. const failedSubsections = chapters.filter(c => c.genStage === 'failed');
  1131. ctx.body = {
  1132. code: 0,
  1133. message: 'success',
  1134. data: {
  1135. bookId,
  1136. failedCount: failedSubsections.length,
  1137. failedChapters: failedSubsections.map(c => ({
  1138. id: c.id,
  1139. number: c.number,
  1140. title: c.title,
  1141. level: c.level,
  1142. errorMsg: c.errorMsg,
  1143. parentId: c.parentId,
  1144. })),
  1145. },
  1146. };
  1147. } catch (error) {
  1148. console.error('获取失败小节失败:', error);
  1149. ctx.status = 500;
  1150. ctx.body = { code: 1, message: error instanceof Error ? error.message : '获取失败' };
  1151. }
  1152. });
  1153. /**
  1154. * POST /api/book-generator/langgraph/books/:id/resume
  1155. * 从断点处继续生成(重试失败的小节)
  1156. */
  1157. router.post('/books/:id/resume', async (ctx: Context) => {
  1158. try {
  1159. const bookId = ctx.params.id as string;
  1160. const book = await bookStore.getById(bookId);
  1161. if (!book) {
  1162. ctx.status = 404;
  1163. ctx.body = { code: 1, message: '书籍不存在' };
  1164. return;
  1165. }
  1166. if (book.genStage === 'video_completed') {
  1167. ctx.body = { code: 1, message: '书籍已生成完成,无需继续' };
  1168. return;
  1169. }
  1170. // 获取失败的小节
  1171. const chapters = await bookStore.getChapterTree(bookId);
  1172. const failedSubsections = chapters.filter(c => c.genStage === 'failed');
  1173. if (failedSubsections.length === 0) {
  1174. ctx.body = { code: 1, message: '没有失败的小节需要重试' };
  1175. return;
  1176. }
  1177. // 重置失败小节的状态为 pending
  1178. for (const sub of failedSubsections) {
  1179. await bookStore.updateChapterById(sub.id, {
  1180. genStage: 'idle',
  1181. errorMsg: null,
  1182. content: null,
  1183. });
  1184. }
  1185. // 直接重新生成(跳过队列)
  1186. const { langGraphGenerator } = await import('./index.js');
  1187. langGraphGenerator.generate(
  1188. bookId,
  1189. book.description || book.title,
  1190. book.bookScale || '1000'
  1191. ).then(() => {
  1192. console.log(`[LangGraph] 续生成完成: bookId=${bookId}`);
  1193. }).catch(err => {
  1194. console.error(`[LangGraph] 续生成失败: bookId=${bookId}`, err);
  1195. });
  1196. ctx.body = {
  1197. code: 0,
  1198. message: `已重启生成,将重试 ${failedSubsections.length} 个失败的小节`,
  1199. data: {
  1200. bookId,
  1201. retryCount: failedSubsections.length,
  1202. genStage: 'resuming',
  1203. },
  1204. };
  1205. } catch (error) {
  1206. console.error('继续生成失败:', error);
  1207. ctx.status = 500;
  1208. ctx.body = { code: 1, message: error instanceof Error ? error.message : '继续生成失败' };
  1209. }
  1210. });
  1211. /**
  1212. * POST /api/book-generator/langgraph/books/:id/retry-chapter
  1213. * 单独重试某个失败的小节
  1214. */
  1215. router.post('/books/:id/retry-chapter', async (ctx: Context) => {
  1216. try {
  1217. const bookId = ctx.params.id as string;
  1218. const { chapterId } = ctx.request.body as { chapterId: number };
  1219. if (!chapterId) {
  1220. ctx.status = 400;
  1221. ctx.body = { code: 1, message: '请提供章节 ID' };
  1222. return;
  1223. }
  1224. // 获取所有章节查找指定的章节
  1225. const chapters = await bookStore.getChapterTree(bookId);
  1226. const chapter = chapters.find(c => c.id === chapterId);
  1227. if (!chapter) {
  1228. ctx.status = 404;
  1229. ctx.body = { code: 1, message: '章节不存在' };
  1230. return;
  1231. }
  1232. // 重置章节状态
  1233. await bookStore.updateChapterById(chapterId, {
  1234. genStage: 'idle',
  1235. errorMsg: null,
  1236. content: null,
  1237. });
  1238. ctx.body = {
  1239. code: 0,
  1240. message: '章节已重置为待生成状态',
  1241. data: { chapterId },
  1242. };
  1243. } catch (error) {
  1244. console.error('重试章节失败:', error);
  1245. ctx.status = 500;
  1246. ctx.body = { code: 1, message: error instanceof Error ? error.message : '重试失败' };
  1247. }
  1248. });
  1249. /**
  1250. * GET /api/book-generator/langgraph/books/:id/full-content
  1251. * 获取完整书籍内容(所有章节内容合并)
  1252. */
  1253. router.get('/books/:id/full-content', async (ctx: Context) => {
  1254. try {
  1255. const bookId = ctx.params.id as string;
  1256. const book = await bookStore.getById(bookId);
  1257. if (!book) {
  1258. ctx.status = 404;
  1259. ctx.body = { code: 1, message: '书籍不存在' };
  1260. return;
  1261. }
  1262. // 获取章节树
  1263. const chapters = await bookStore.getChapterTree(bookId);
  1264. // 按层级和顺序构建内容
  1265. let fullContent = `# ${book.title}\n\n`;
  1266. if (book.description) {
  1267. fullContent += `## 简介\n${book.description}\n\n`;
  1268. }
  1269. // 递归添加章节内容
  1270. const addChapterContent = (chapter: any, indent: string = '') => {
  1271. if (chapter.content && chapter.genStage === 'content_completed') {
  1272. fullContent += `${indent}${chapter.number}. ${chapter.title}\n\n`;
  1273. fullContent += chapter.content + '\n\n';
  1274. }
  1275. // 处理子章节
  1276. const children = chapters.filter((c: any) => c.parentId === chapter.id);
  1277. children.forEach(child => {
  1278. addChapterContent(child, indent + ' ');
  1279. });
  1280. };
  1281. // 添加一级章节
  1282. const level1Chapters = chapters.filter((c: any) => c.level === 1);
  1283. level1Chapters.forEach(chapter => addChapterContent(chapter));
  1284. ctx.body = {
  1285. code: 0,
  1286. message: 'success',
  1287. data: {
  1288. bookId,
  1289. title: book.title,
  1290. totalChapters: level1Chapters.length,
  1291. content: fullContent,
  1292. wordCount: book.estimatedWords,
  1293. },
  1294. };
  1295. } catch (error) {
  1296. console.error('获取完整内容失败:', error);
  1297. ctx.status = 500;
  1298. ctx.body = { code: 1, message: error instanceof Error ? error.message : '获取失败' };
  1299. }
  1300. });
  1301. /**
  1302. * POST /api/book-generator/langgraph/books/:id/outline
  1303. * 生成书籍大纲
  1304. */
  1305. router.post('/books/:id/outline', async (ctx: Context) => {
  1306. try {
  1307. const bookId = ctx.params.id as string;
  1308. const book = await bookStore.getById(bookId);
  1309. if (!book) {
  1310. ctx.status = 404;
  1311. ctx.body = { code: 1, message: '书籍不存在' };
  1312. return;
  1313. }
  1314. // 检查是否已经有大纲
  1315. if (book.outline && book.outline.chapters && book.outline.chapters.length > 0) {
  1316. ctx.body = {
  1317. code: 0,
  1318. message: '大纲已存在,无需重复生成',
  1319. data: { outline: book.outline },
  1320. };
  1321. return;
  1322. }
  1323. // 获取书籍类型配置
  1324. const scaleConfig = getScaleConfig(book.bookScale || '1000');
  1325. // 调用AI生成大纲
  1326. const { generateOutline } = await import('./index.js');
  1327. const outline = await generateOutline(bookId, book.description, book.bookScale || '1000');
  1328. // 更新书籍的大纲
  1329. await bookStore.update(bookId, { outline });
  1330. ctx.body = {
  1331. code: 0,
  1332. message: '大纲生成成功',
  1333. data: { outline },
  1334. };
  1335. } catch (error) {
  1336. console.error('生成大纲失败:', error);
  1337. ctx.status = 500;
  1338. ctx.body = { code: 1, message: error instanceof Error ? error.message : '生成大纲失败' };
  1339. }
  1340. });
  1341. /**
  1342. * POST /api/book-generator/langgraph/books/:id/chapters
  1343. * 生成单个章节(或全部章节,取决于参数)
  1344. * body: { chapterNumber?: number } - 如果不传chapterNumber,则生成全部
  1345. */
  1346. router.post('/books/:id/chapters', async (ctx: Context) => {
  1347. try {
  1348. const bookId = ctx.params.id as string;
  1349. const body = ctx.request.body as { chapterNumber?: number };
  1350. const book = await bookStore.getById(bookId);
  1351. if (!book) {
  1352. ctx.status = 404;
  1353. ctx.body = { code: 1, message: '书籍不存在' };
  1354. return;
  1355. }
  1356. // 如果指定了章节号,只生成单个章节
  1357. if (body.chapterNumber) {
  1358. // 检查章节是否存在
  1359. const chapters = await bookStore.getChapterTree(bookId);
  1360. const targetChapter = chapters.find((c: any) => c.number === body.chapterNumber);
  1361. if (!targetChapter) {
  1362. ctx.status = 404;
  1363. ctx.body = { code: 1, message: `章节 ${body.chapterNumber} 不存在` };
  1364. return;
  1365. }
  1366. // 异步生成章节内容
  1367. bookStore.generateSingleChapterContent(bookId, targetChapter.id).catch(err => {
  1368. console.error(`[Generate Chapter] 章节${body.chapterNumber}生成失败:`, err);
  1369. });
  1370. ctx.body = {
  1371. code: 0,
  1372. message: `章节 ${body.chapterNumber} 生成任务已启动`,
  1373. data: { chapterId: targetChapter.id, chapterNumber: body.chapterNumber },
  1374. };
  1375. } else {
  1376. // 没有指定章节号,触发整本书生成
  1377. ctx.body = {
  1378. code: 0,
  1379. message: '请使用 /generate 接口生成整本书',
  1380. data: { hint: '使用 POST /books/:id/generate' },
  1381. };
  1382. }
  1383. } catch (error) {
  1384. console.error('生成章节失败:', error);
  1385. ctx.status = 500;
  1386. ctx.body = { code: 1, message: error instanceof Error ? error.message : '生成章节失败' };
  1387. }
  1388. });
  1389. /**
  1390. * POST /api/book-generator/langgraph/books/:id/foreword
  1391. * 生成前言
  1392. */
  1393. router.post('/books/:id/foreword', async (ctx: Context) => {
  1394. try {
  1395. const bookId = ctx.params.id as string;
  1396. const book = await bookStore.getById(bookId);
  1397. if (!book) {
  1398. ctx.status = 404;
  1399. ctx.body = { code: 1, message: '书籍不存在' };
  1400. return;
  1401. }
  1402. // 调用LLM生成前言
  1403. const messages: ChatMessage[] = [
  1404. {
  1405. role: 'system',
  1406. content: `你是一位专业的图书作者。请根据以下信息为书籍生成前言(前言通常介绍写作背景、目标读者、内容概要)。
  1407. 要求:
  1408. 1. 字数控制在300-500字
  1409. 2. 语言正式但亲切
  1410. 3. 不要使用 markdown 格式,直接输出纯文本
  1411. 输出格式:
  1412. 直接输出前言内容,不要包含任何标记。`,
  1413. },
  1414. {
  1415. role: 'user',
  1416. content: `书籍信息:
  1417. - 书名:${book.title}
  1418. - 描述:${book.description}
  1419. - 目标读者:${book.targetAudience || '普通读者'}
  1420. - 风格:${book.style || '专业'}
  1421. 请生成这本书的前言。`,
  1422. },
  1423. ];
  1424. const foreword = await callLLMWithMessages(messages);
  1425. // 更新书籍前言字段
  1426. await bookStore.update(bookId, { foreword });
  1427. ctx.body = {
  1428. code: 0,
  1429. message: '前言生成成功',
  1430. data: { foreword },
  1431. };
  1432. } catch (error) {
  1433. console.error('生成前言失败:', error);
  1434. ctx.status = 500;
  1435. ctx.body = { code: 1, message: error instanceof Error ? error.message : '生成前言失败' };
  1436. }
  1437. });
  1438. /**
  1439. * POST /api/book-generator/langgraph/books/:id/afterword
  1440. * 生成后记
  1441. */
  1442. router.post('/books/:id/afterword', async (ctx: Context) => {
  1443. try {
  1444. const bookId = ctx.params.id as string;
  1445. const book = await bookStore.getById(bookId);
  1446. if (!book) {
  1447. ctx.status = 404;
  1448. ctx.body = { code: 1, message: '书籍不存在' };
  1449. return;
  1450. }
  1451. // 调用LLM生成后记
  1452. const messages: ChatMessage[] = [
  1453. {
  1454. role: 'system',
  1455. content: `你是一位专业的图书作者。请为书籍生成后记(后记通常总结全书核心观点、分享写作心得、感谢读者)。
  1456. 要求:
  1457. 1. 字数控制在300-500字
  1458. 2. 语言真挚、诚恳
  1459. 3. 不要使用 markdown 格式,直接输出纯文本
  1460. 输出格式:
  1461. 直接输出后记内容,不要包含任何标记。`,
  1462. },
  1463. {
  1464. role: 'user',
  1465. content: `书籍信息:
  1466. - 书名:${book.title}
  1467. - 描述:${book.description}
  1468. - 章节数:${book.totalChapters}
  1469. - 总字数:约${book.estimatedWords}字
  1470. 请生成这本书的后记。`,
  1471. },
  1472. ];
  1473. const afterword = await callLLMWithMessages(messages);
  1474. // 更新书籍后记字段
  1475. await bookStore.update(bookId, { afterword });
  1476. ctx.body = {
  1477. code: 0,
  1478. message: '后记生成成功',
  1479. data: { afterword },
  1480. };
  1481. } catch (error) {
  1482. console.error('生成后记失败:', error);
  1483. ctx.status = 500;
  1484. ctx.body = { code: 1, message: error instanceof Error ? error.message : '生成后记失败' };
  1485. }
  1486. });
  1487. /**
  1488. * GET /api/book-generator/langgraph/workflow/:bookId
  1489. * 获取书籍生成工作流状态
  1490. */
  1491. router.get('/workflow/:bookId', async (ctx: Context) => {
  1492. try {
  1493. const bookId = ctx.params.bookId as string;
  1494. const book = await bookStore.getById(bookId);
  1495. if (!book) {
  1496. ctx.status = 404;
  1497. ctx.body = { code: 1, message: '书籍不存在' };
  1498. return;
  1499. }
  1500. // 获取章节树
  1501. const chapters = await bookStore.getChapterTree(bookId);
  1502. // 分析工作流状态
  1503. const completedChapters = chapters.filter((c: any) => ['content_completed', 'audio_completed', 'video_completed'].includes(c.genStage)).length;
  1504. const failedChapters = chapters.filter((c: any) => c.genStage === 'failed').length;
  1505. const pendingChapters = chapters.filter((c: any) => c.genStage === 'idle' || !c.genStage).length;
  1506. const generatingChapters = chapters.filter((c: any) => ['content_generating', 'audio_generating', 'video_generating'].includes(c.genStage)).length;
  1507. // 确定当前阶段
  1508. let phase: 'planning' | 'writing' | 'supplement' | 'done' = 'planning';
  1509. if (['content_generating', 'audio_generating', 'video_generating'].includes(book.genStage)) {
  1510. phase = 'writing';
  1511. } else if (completedChapters > 0 && failedChapters === 0) {
  1512. phase = 'done';
  1513. } else if (failedChapters > 0) {
  1514. phase = 'supplement';
  1515. }
  1516. ctx.body = {
  1517. code: 0,
  1518. message: 'success',
  1519. data: {
  1520. bookId,
  1521. genStage: book.genStage,
  1522. phase,
  1523. progress: book.progress || 0,
  1524. completedChapters,
  1525. failedChapters,
  1526. pendingChapters,
  1527. generatingChapters,
  1528. totalChapters: chapters.length,
  1529. failedChapterIds: chapters.filter((c: any) => c.genStage === 'failed').map((c: any) => c.id),
  1530. },
  1531. };
  1532. } catch (error) {
  1533. console.error('获取工作流状态失败:', error);
  1534. ctx.status = 500;
  1535. ctx.body = { code: 1, message: error instanceof Error ? error.message : '获取失败' };
  1536. }
  1537. });
  1538. /**
  1539. * GET /api/book-generator/langgraph/books/:id/chapters/:chapterId/content
  1540. * 获取指定章节的内容
  1541. */
  1542. router.get('/books/:id/chapters/:chapterId/content', optionalAuth, async (ctx: Context) => {
  1543. try {
  1544. const { id: bookId, chapterId } = ctx.params as { id: string; chapterId: string };
  1545. const chapterIdNum = parseInt(chapterId);
  1546. // 获取书籍
  1547. const book = await bookStore.getById(bookId);
  1548. if (!book) {
  1549. ctx.status = 404;
  1550. ctx.body = { code: 1, message: '书籍不存在' };
  1551. return;
  1552. }
  1553. // 获取章节
  1554. const chapter = await prisma.bookChapter.findUnique({
  1555. where: { id: chapterIdNum },
  1556. });
  1557. if (!chapter) {
  1558. ctx.status = 404;
  1559. ctx.body = { code: 1, message: '章节不存在' };
  1560. return;
  1561. }
  1562. // 检查是否属于该书籍
  1563. if (chapter.bookId !== parseInt(bookId)) {
  1564. ctx.status = 404;
  1565. ctx.body = { code: 1, message: '章节不属于该书籍' };
  1566. return;
  1567. }
  1568. ctx.body = {
  1569. code: 0,
  1570. message: 'success',
  1571. data: {
  1572. id: chapter.id,
  1573. bookId: chapter.bookId,
  1574. number: chapter.number,
  1575. title: chapter.title,
  1576. content: chapter.content || '',
  1577. wordCount: chapter.wordCount || 0,
  1578. genStage: chapter.genStage || null,
  1579. level: chapter.level,
  1580. parentId: chapter.parentId,
  1581. summary: chapter.summary || '',
  1582. keyPoints: chapter.keyPoints ? JSON.parse(chapter.keyPoints) : [],
  1583. audioUrl: chapter.audioUrl || '',
  1584. videoUrl: chapter.videoUrl || '',
  1585. isPublic: chapter.isPublic || false,
  1586. },
  1587. };
  1588. } catch (error) {
  1589. console.error('获取章节内容失败:', error);
  1590. ctx.status = 500;
  1591. ctx.body = { code: 1, message: error instanceof Error ? error.message : '获取章节内容失败' };
  1592. }
  1593. });
  1594. /**
  1595. * POST /api/book-generator/langgraph/books/:id/chapters/:chapterId/content
  1596. * 保存章节内容(手工编辑后保存)
  1597. */
  1598. router.post('/books/:id/chapters/:chapterId/content', optionalAuth, async (ctx: Context) => {
  1599. try {
  1600. const { id: bookId, chapterId } = ctx.params as { id: string; chapterId: string };
  1601. const chapterIdNum = parseInt(chapterId);
  1602. const { content } = ctx.request.body as { content: string };
  1603. if (content === undefined) {
  1604. ctx.status = 400;
  1605. ctx.body = { code: 1, message: '内容不能为空' };
  1606. return;
  1607. }
  1608. // 获取章节
  1609. const chapter = await prisma.bookChapter.findUnique({
  1610. where: { id: chapterIdNum },
  1611. });
  1612. if (!chapter) {
  1613. ctx.status = 404;
  1614. ctx.body = { code: 1, message: '章节不存在' };
  1615. return;
  1616. }
  1617. // 检查是否属于该书籍
  1618. if (chapter.bookId !== parseInt(bookId)) {
  1619. ctx.status = 404;
  1620. ctx.body = { code: 1, message: '章节不属于该书籍' };
  1621. return;
  1622. }
  1623. // 计算字数
  1624. const wordCount = content.replace(/<[^>]*>/g, '').length;
  1625. // 更新章节内容
  1626. await bookStore.updateChapterById(chapterIdNum, {
  1627. content,
  1628. wordCount,
  1629. });
  1630. ctx.body = {
  1631. code: 0,
  1632. message: '保存成功',
  1633. data: { chapterId: chapterIdNum, wordCount },
  1634. };
  1635. } catch (error) {
  1636. console.error('保存章节内容失败:', error);
  1637. ctx.status = 500;
  1638. ctx.body = { code: 1, message: error instanceof Error ? error.message : '保存章节内容失败' };
  1639. }
  1640. });
  1641. /**
  1642. * POST /api/book-generator/langgraph/books/:id/chapters/batch-regenerate
  1643. * 批量重新生成章节内容
  1644. */
  1645. router.post('/books/:id/chapters/batch-regenerate', optionalAuth, async (ctx: Context) => {
  1646. try {
  1647. const { id: bookId } = ctx.params as { id: string };
  1648. const { chapterIds } = ctx.request.body as { chapterIds: number[] };
  1649. if (!chapterIds || !Array.isArray(chapterIds) || chapterIds.length === 0) {
  1650. ctx.status = 400;
  1651. ctx.body = { code: 1, message: '请选择要重新生成的章节' };
  1652. return;
  1653. }
  1654. // 获取书籍
  1655. const book = await bookStore.getById(bookId);
  1656. if (!book) {
  1657. ctx.status = 404;
  1658. ctx.body = { code: 1, message: '书籍不存在' };
  1659. return;
  1660. }
  1661. // 更新书籍状态为 content_generating,让前端能正确追踪轮询
  1662. await bookStore.update(bookId, { genStage: 'content_generating' });
  1663. // 重置并触发每个选中章节的重新生成
  1664. for (const chapterId of chapterIds) {
  1665. await bookStore.updateChapterById(chapterId, {
  1666. genStage: 'idle',
  1667. content: null,
  1668. });
  1669. // 后台异步执行
  1670. bookStore.generateSingleChapterContent(bookId, chapterId).catch(err => {
  1671. console.error(`[BatchRegenerate] 章节${chapterId}内容生成失败:`, err);
  1672. });
  1673. }
  1674. ctx.body = {
  1675. code: 0,
  1676. message: `已提交 ${chapterIds.length} 个章节的重新生成任务`,
  1677. data: { count: chapterIds.length },
  1678. };
  1679. } catch (error) {
  1680. console.error('批量重新生成章节失败:', error);
  1681. ctx.status = 500;
  1682. ctx.body = { code: 1, message: error instanceof Error ? error.message : '批量重新生成失败' };
  1683. }
  1684. });
  1685. /**
  1686. * POST /api/book-generator/langgraph/books/:id/chapters/batch-delete
  1687. * 批量删除章节
  1688. */
  1689. router.post('/books/:id/chapters/batch-delete', optionalAuth, async (ctx: Context) => {
  1690. try {
  1691. const { id: bookId } = ctx.params as { id: string };
  1692. const { chapterIds } = ctx.request.body as { chapterIds: number[] };
  1693. if (!chapterIds || !Array.isArray(chapterIds) || chapterIds.length === 0) {
  1694. ctx.status = 400;
  1695. ctx.body = { code: 1, message: '请选择要删除的章节' };
  1696. return;
  1697. }
  1698. // 获取书籍
  1699. const book = await bookStore.getById(bookId);
  1700. if (!book) {
  1701. ctx.status = 404;
  1702. ctx.body = { code: 1, message: '书籍不存在' };
  1703. return;
  1704. }
  1705. // 删除章节(同时会删除子章节,因为没有设置级联删除,需要手动处理)
  1706. // 对于每个要删除的章节,先删除其所有子节点,再删除自身
  1707. for (const chapterId of chapterIds) {
  1708. // 删除子章节(level > 当前章节)
  1709. await prisma.bookChapter.deleteMany({
  1710. where: {
  1711. bookId: parseInt(bookId),
  1712. parentId: chapterId,
  1713. },
  1714. });
  1715. // 删除自身
  1716. await prisma.bookChapter.deleteMany({
  1717. where: {
  1718. id: chapterId,
  1719. bookId: parseInt(bookId),
  1720. },
  1721. });
  1722. }
  1723. ctx.body = {
  1724. code: 0,
  1725. message: `已删除 ${chapterIds.length} 个章节`,
  1726. data: { count: chapterIds.length },
  1727. };
  1728. } catch (error) {
  1729. console.error('批量删除章节失败:', error);
  1730. ctx.status = 500;
  1731. ctx.body = { code: 1, message: error instanceof Error ? error.message : '批量删除失败' };
  1732. }
  1733. });
  1734. /**
  1735. * POST /api/book-generator/langgraph/books/:id/chapters/:chapterId/regenerate
  1736. * 重新生成指定章节的内容(仅叶节点允许)
  1737. */
  1738. router.post('/books/:id/chapters/:chapterId/regenerate', async (ctx: Context) => {
  1739. try {
  1740. const { id: bookId, chapterId } = ctx.params as { id: string; chapterId: string };
  1741. const chapterIdNum = parseInt(chapterId);
  1742. // 获取书籍
  1743. const book = await bookStore.getById(bookId);
  1744. if (!book) {
  1745. ctx.status = 404;
  1746. ctx.body = { code: 1, message: '书籍不存在' };
  1747. return;
  1748. }
  1749. // 获取章节
  1750. const chapter = await prisma.bookChapter.findUnique({
  1751. where: { id: chapterIdNum },
  1752. });
  1753. if (!chapter) {
  1754. ctx.status = 404;
  1755. ctx.body = { code: 1, message: '章节不存在' };
  1756. return;
  1757. }
  1758. // 检查是否为叶节点(没有子节点的节点)
  1759. const childChapters = await prisma.bookChapter.findMany({
  1760. where: { parentId: chapterIdNum },
  1761. });
  1762. if (childChapters.length > 0) {
  1763. ctx.status = 400;
  1764. ctx.body = { code: 1, message: '只有叶节点(小节)才允许重新生成内容' };
  1765. return;
  1766. }
  1767. // 重置章节状态和内容
  1768. await bookStore.updateChapterById(chapterIdNum, {
  1769. genStage: 'idle',
  1770. errorMsg: null,
  1771. content: null,
  1772. });
  1773. // 直接调用单个章节内容生成(不触发整个书籍生成流程)
  1774. // 在后台异步执行
  1775. bookStore.generateSingleChapterContent(bookId, chapterIdNum).catch(err => {
  1776. console.error(`[Regenerate] 章节${chapterIdNum}内容生成失败:`, err);
  1777. });
  1778. ctx.body = {
  1779. code: 0,
  1780. message: '章节内容重新生成任务已启动',
  1781. data: { chapterId: chapterIdNum },
  1782. };
  1783. } catch (error) {
  1784. console.error('重新生成章节失败:', error);
  1785. ctx.status = 500;
  1786. ctx.body = { code: 1, message: error instanceof Error ? error.message : '重新生成失败' };
  1787. }
  1788. });
  1789. /**
  1790. * POST /api/book-generator/langgraph/books/:id/chapters/:chapterId/regenerate-audio
  1791. * 重新生成章节音频(仅叶节点)
  1792. */
  1793. router.post('/books/:id/chapters/:chapterId/regenerate-audio', async (ctx: Context) => {
  1794. try {
  1795. const { id: bookId, chapterId } = ctx.params as { id: string; chapterId: string };
  1796. const chapterIdNum = parseInt(chapterId);
  1797. // 获取书籍
  1798. const book = await bookStore.getById(bookId);
  1799. if (!book) {
  1800. ctx.status = 404;
  1801. ctx.body = { code: 1, message: '书籍不存在' };
  1802. return;
  1803. }
  1804. // 获取章节
  1805. const chapter = await prisma.bookChapter.findUnique({
  1806. where: { id: chapterIdNum },
  1807. });
  1808. if (!chapter) {
  1809. ctx.status = 404;
  1810. ctx.body = { code: 1, message: '章节不存在' };
  1811. return;
  1812. }
  1813. // 检查是否为叶节点
  1814. const childChapters = await prisma.bookChapter.findMany({
  1815. where: { parentId: chapterIdNum },
  1816. });
  1817. if (childChapters.length > 0) {
  1818. ctx.status = 400;
  1819. ctx.body = { code: 1, message: '只有叶节点(小节)才允许重新生成音频' };
  1820. return;
  1821. }
  1822. // 检查内容是否已完成(有内容即可重生成音频,content_generating 但 content 已存在也允许)
  1823. if (!chapter.content || chapter.genStage === 'idle') {
  1824. ctx.status = 400;
  1825. ctx.body = { code: 1, message: '章节内容未生成完成,无法生成音频' };
  1826. return;
  1827. }
  1828. // 清空现有音频并回退状态
  1829. await bookStore.updateChapterById(chapterIdNum, {
  1830. audioUrl: '',
  1831. audioDuration: 0,
  1832. lrcLyrics: null,
  1833. genStage: 'content_completed',
  1834. });
  1835. // 同时清空父章节的合并音频(因为子节音频变了,合并音频也需要重新生成)
  1836. if (chapter.parentId) {
  1837. const parentChapter = await prisma.bookChapter.findUnique({
  1838. where: { id: chapter.parentId },
  1839. });
  1840. if (parentChapter?.audioUrl?.includes('_merged')) {
  1841. console.log(`[RegenerateAudio] 清除父章节 ${parentChapter.id} 的合并音频(子节${chapterIdNum}已重新生成)`);
  1842. await bookStore.updateChapterById(parentChapter.id, {
  1843. audioUrl: '',
  1844. audioDuration: 0,
  1845. });
  1846. // 如果父章节之上还有更高级的合并音频,也一并清除
  1847. if (parentChapter.parentId) {
  1848. const grandParent = await prisma.bookChapter.findUnique({
  1849. where: { id: parentChapter.parentId },
  1850. });
  1851. if (grandParent?.audioUrl?.includes('_merged')) {
  1852. console.log(`[RegenerateAudio] 清除祖父章节 ${grandParent.id} 的合并音频`);
  1853. await bookStore.updateChapterById(grandParent.id, {
  1854. audioUrl: '',
  1855. audioDuration: 0,
  1856. });
  1857. }
  1858. }
  1859. }
  1860. }
  1861. // 异步生成新音频
  1862. bookStore.generateChapterAudioById(chapterIdNum, book.userId || 1);
  1863. ctx.body = {
  1864. code: 0,
  1865. message: '音频重新生成任务已启动',
  1866. data: { chapterId: chapterIdNum },
  1867. };
  1868. } catch (error) {
  1869. console.error('重新生成音频失败:', error);
  1870. ctx.status = 500;
  1871. ctx.body = { code: 1, message: error instanceof Error ? error.message : '重新生成音频失败' };
  1872. }
  1873. });
  1874. /**
  1875. * POST /api/book-generator/langgraph/books/:id/chapters/:chapterId/video
  1876. * 生成单个章节视频
  1877. */
  1878. router.post('/books/:id/chapters/:chapterId/video', async (ctx: Context) => {
  1879. try {
  1880. const { id: bookId, chapterId } = ctx.params as { id: string; chapterId: string };
  1881. const chapterIdNum = parseInt(chapterId);
  1882. const chapter = await prisma.bookChapter.findUnique({
  1883. where: { id: chapterIdNum },
  1884. });
  1885. if (!chapter) {
  1886. ctx.status = 404;
  1887. ctx.body = { code: 1, message: '章节不存在' };
  1888. return;
  1889. }
  1890. // 检查章节是否有音频
  1891. if (!chapter.audioUrl) {
  1892. ctx.status = 400;
  1893. ctx.body = { code: 1, message: '该章节没有音频,请先生成音频' };
  1894. return;
  1895. }
  1896. // 设置视频状态为生成中
  1897. await advanceChapter(chapterIdNum, 'video_generating');
  1898. // 调用视频服务创建视频项目
  1899. const project = await createVideoProjectFromBook(parseInt(bookId), chapterIdNum);
  1900. if (!project) {
  1901. await regenerateChapter(chapterIdNum, 'failed');
  1902. ctx.status = 400;
  1903. ctx.body = { code: 1, message: '创建视频项目失败' };
  1904. return;
  1905. }
  1906. // 异步生成视频
  1907. generateVideoForProject(project.id)
  1908. .then(async (result) => {
  1909. if (result.success) {
  1910. await bookStore.updateChapterById(chapterIdNum, {
  1911. videoUrl: result.outputUrl,
  1912. videoDuration: result.duration,
  1913. });
  1914. await advanceChapter(chapterIdNum, 'video_completed');
  1915. } else {
  1916. await regenerateChapter(chapterIdNum, 'failed');
  1917. }
  1918. })
  1919. .catch(async (err) => {
  1920. console.error(`[Video] 章节${chapter.number}视频生成失败:`, err);
  1921. await regenerateChapter(chapterIdNum, 'failed');
  1922. });
  1923. ctx.body = {
  1924. code: 0,
  1925. message: '视频生成任务已启动',
  1926. data: {
  1927. projectId: project.id,
  1928. chapterId: String(chapterId),
  1929. },
  1930. };
  1931. } catch (error) {
  1932. console.error('视频生成失败:', error);
  1933. ctx.status = 500;
  1934. ctx.body = { code: 1, message: error instanceof Error ? error.message : '视频生成失败' };
  1935. }
  1936. });
  1937. /**
  1938. * POST /api/book-generator/langgraph/books/:id/videos
  1939. * 批量生成书籍所有章节视频
  1940. */
  1941. router.post('/books/:id/videos', async (ctx: Context) => {
  1942. try {
  1943. const bookId = ctx.params.id as string;
  1944. const book = await bookStore.getById(bookId);
  1945. if (!book) {
  1946. ctx.status = 404;
  1947. ctx.body = { code: 1, message: '书籍不存在' };
  1948. return;
  1949. }
  1950. // 获取章节树
  1951. const chapters = await bookStore.getChapterTree(bookId);
  1952. // 动态获取叶节点层级(最大level值)
  1953. const maxLevel = chapters.length > 0
  1954. ? Math.max(...chapters.map((c: any) => c.level || 0))
  1955. : 0;
  1956. if (maxLevel === 0) {
  1957. ctx.body = { code: 1, message: '没有章节' };
  1958. return;
  1959. }
  1960. // 获取叶节点(最大level的所有节点)
  1961. const leafNodes = chapters.filter((c: any) => c.level === maxLevel);
  1962. // 过滤出有音频的叶节点
  1963. const leafNodesWithAudio = leafNodes.filter((c: any) => c.audioUrl && c.audioUrl !== '');
  1964. const leafTypeName = maxLevel === 3 ? '小节' : maxLevel === 2 ? '节' : '章节';
  1965. if (leafNodes.length === 0) {
  1966. ctx.body = { code: 1, message: `没有${leafTypeName}` };
  1967. return;
  1968. }
  1969. if (leafNodesWithAudio.length === 0) {
  1970. ctx.body = {
  1971. code: 1,
  1972. message: `没有音频生成完成的${leafTypeName},请先生成音频`,
  1973. data: {
  1974. totalSubsections: leafNodes.length,
  1975. audioCompletedSubsections: 0,
  1976. }
  1977. };
  1978. return;
  1979. }
  1980. console.log(`[Video] 书籍 ${bookId} 共有 ${leafNodes.length} 个${leafTypeName},其中 ${leafNodesWithAudio.length} 个音频已生成完成`);
  1981. // 异步生成所有叶节点视频
  1982. const taskId = `video_${bookId}_${Date.now()}`;
  1983. console.log(`[Video] 开始批量生成视频: bookId=${bookId}, taskId=${taskId}, 总数=${leafNodesWithAudio.length}`);
  1984. for (const sub of leafNodesWithAudio) {
  1985. // 设置视频状态为生成中
  1986. await advanceChapter(sub.id, 'video_generating').catch(() => {});
  1987. // 异步处理每个章节的视频生成
  1988. (async () => {
  1989. try {
  1990. console.log(`[Video] 开始生成章节 ${sub.number} 的视频: ${sub.title}`);
  1991. // 从书籍章节创建视频项目
  1992. const project = await createVideoProjectFromBook(
  1993. parseInt(bookId),
  1994. sub.id,
  1995. book.userId || 1
  1996. );
  1997. if (!project) {
  1998. console.error(`[Video] 章节 ${sub.number} 视频项目创建失败`);
  1999. await regenerateChapter(sub.id, 'failed').catch(() => {});
  2000. return;
  2001. }
  2002. console.log(`[Video] 章节 ${sub.number} 视频项目创建成功: projectId=${project.id}`);
  2003. // 生成视频
  2004. const result = await generateVideoForProject(project.id);
  2005. if (result.success && result.outputUrl) {
  2006. await bookStore.updateChapterById(sub.id, {
  2007. videoUrl: result.outputUrl,
  2008. videoDuration: result.duration,
  2009. });
  2010. await advanceChapter(sub.id, 'video_completed');
  2011. } else {
  2012. await regenerateChapter(sub.id, 'failed');
  2013. }
  2014. } catch (error) {
  2015. console.error(`[Video] 章节 ${sub.number} 视频生成异常:`, error);
  2016. await regenerateChapter(sub.id, 'failed');
  2017. }
  2018. })();
  2019. }
  2020. ctx.body = {
  2021. code: 0,
  2022. message: '视频生成任务已启动',
  2023. data: {
  2024. taskId,
  2025. totalChapters: leafNodesWithAudio.length,
  2026. totalSubsections: leafNodes.length,
  2027. },
  2028. };
  2029. } catch (error) {
  2030. console.error('批量生成视频失败:', error);
  2031. ctx.status = 500;
  2032. ctx.body = { code: 1, message: error instanceof Error ? error.message : '批量生成视频失败' };
  2033. }
  2034. });
  2035. /**
  2036. * POST /api/book-generator/langgraph/books/:id/merge-audio
  2037. * 合并叶节点音频到上级章节
  2038. */
  2039. router.post('/books/:id/merge-audio', async (ctx: Context) => {
  2040. try {
  2041. const bookId = ctx.params.id as string;
  2042. const book = await bookStore.getById(bookId);
  2043. if (!book) {
  2044. ctx.status = 404;
  2045. ctx.body = { code: 1, message: '书籍不存在' };
  2046. return;
  2047. }
  2048. // 获取章节树
  2049. const chapters = await bookStore.getChapterTree(bookId);
  2050. // 动态获取叶节点层级(最大level值)
  2051. const maxLevel = chapters.length > 0
  2052. ? Math.max(...chapters.map((c: any) => c.level || 0))
  2053. : 0;
  2054. if (maxLevel <= 1) {
  2055. ctx.body = { code: 1, message: '书籍层级不足,无法合并音频' };
  2056. return;
  2057. }
  2058. // 获取叶节点(最大level的所有节点)
  2059. const leafNodes = chapters.filter((c: any) => c.level === maxLevel);
  2060. // 检查所有叶节点是否都有音频
  2061. const leafNodesWithAudio = leafNodes.filter((c: any) => c.audioUrl && c.audioUrl !== '');
  2062. if (leafNodes.length === 0) {
  2063. ctx.body = { code: 1, message: `没有${maxLevel === 3 ? '小节' : maxLevel === 2 ? '节' : '章节'}` };
  2064. return;
  2065. }
  2066. if (leafNodesWithAudio.length !== leafNodes.length) {
  2067. ctx.body = {
  2068. code: 1,
  2069. message: `并非所有${maxLevel === 3 ? '小节' : maxLevel === 2 ? '节' : '章节'}都已完成音频生成,无法合并`,
  2070. data: {
  2071. totalLeafNodes: leafNodes.length,
  2072. completedAudioNodes: leafNodesWithAudio.length,
  2073. }
  2074. };
  2075. return;
  2076. }
  2077. // 构建 sectionId → chapterId 映射(3层树需要,2层树直接 parentId 就是 chapterId)
  2078. const sectionToChapter = new Map<number, number>();
  2079. if (maxLevel >= 3) {
  2080. const sections = chapters.filter((c: any) => c.level === 2);
  2081. for (const sec of sections) {
  2082. if (sec.parentId) {
  2083. sectionToChapter.set(sec.id, sec.parentId);
  2084. }
  2085. }
  2086. }
  2087. // 按章(level=1)分组叶节点
  2088. const groupedByChapter: { [key: number]: any[] } = {};
  2089. const chapterMeta: { [key: number]: any } = {}; // 章的基本信息
  2090. leafNodesWithAudio.forEach(node => {
  2091. // 找到该叶节点所属的1级章ID
  2092. let chapterId: number | null = null;
  2093. if (maxLevel === 2) {
  2094. chapterId = node.parentId; // level=2叶节点的parentId就是章
  2095. } else if (maxLevel === 3 && node.parentId) {
  2096. chapterId = sectionToChapter.get(node.parentId) || null; // 通过节→章映射
  2097. }
  2098. if (chapterId) {
  2099. if (!groupedByChapter[chapterId]) {
  2100. groupedByChapter[chapterId] = [];
  2101. }
  2102. groupedByChapter[chapterId].push(node);
  2103. }
  2104. });
  2105. // 收集各章的元信息
  2106. for (const ch of chapters) {
  2107. if (ch.level === 1) {
  2108. chapterMeta[ch.id] = ch;
  2109. }
  2110. }
  2111. const chapterIds = Object.keys(groupedByChapter);
  2112. // 对每个章下的叶节点音频进行合并
  2113. for (const chapterId of chapterIds) {
  2114. const chId = parseInt(chapterId);
  2115. const childNodes = groupedByChapter[chId];
  2116. const chInfo = chapterMeta[chId];
  2117. if (childNodes.length > 0) {
  2118. try {
  2119. const mergedAudioUrl = await mergeChapterAudios(chId);
  2120. if (mergedAudioUrl) {
  2121. console.log(`[Merge Audio] 章 ${chInfo?.number || chId}(${chInfo?.title || ''}) 音频合并完成: ${mergedAudioUrl}`);
  2122. }
  2123. } catch (error) {
  2124. console.error(`[Merge Audio] 章 ${chInfo?.number || chId}(${chInfo?.title || ''}) 音频合并失败:`, error);
  2125. }
  2126. }
  2127. }
  2128. ctx.body = {
  2129. code: 0,
  2130. message: `音频合并任务已启动,共处理 ${chapterIds.length} 个章`,
  2131. data: {
  2132. processedParents: chapterIds.length,
  2133. totalLeafNodes: leafNodes.length,
  2134. },
  2135. };
  2136. } catch (error) {
  2137. console.error('合并音频失败:', error);
  2138. ctx.status = 500;
  2139. ctx.body = { code: 1, message: error instanceof Error ? error.message : '合并音频失败' };
  2140. }
  2141. });
  2142. /**
  2143. * POST /api/book-generator/langgraph/books/:id/merge-video
  2144. * 合并叶节点视频到上级章节
  2145. */
  2146. router.post('/books/:id/merge-video', async (ctx: Context) => {
  2147. try {
  2148. const bookId = ctx.params.id as string;
  2149. const book = await bookStore.getById(bookId);
  2150. if (!book) {
  2151. ctx.status = 404;
  2152. ctx.body = { code: 1, message: '书籍不存在' };
  2153. return;
  2154. }
  2155. // 获取章节树
  2156. const chapters = await bookStore.getChapterTree(bookId);
  2157. // 动态获取叶节点层级(最大level值)
  2158. const maxLevel = chapters.length > 0
  2159. ? Math.max(...chapters.map((c: any) => c.level || 0))
  2160. : 0;
  2161. if (maxLevel <= 1) {
  2162. ctx.body = { code: 1, message: '书籍层级不足,无法合并视频' };
  2163. return;
  2164. }
  2165. // 获取叶节点(最大level的所有节点)
  2166. const leafNodes = chapters.filter((c: any) => c.level === maxLevel);
  2167. // 检查所有叶节点是否都有视频
  2168. const leafNodesWithVideo = leafNodes.filter((c: any) => c.videoUrl && c.videoUrl !== '');
  2169. if (leafNodes.length === 0) {
  2170. ctx.body = { code: 1, message: `没有${maxLevel === 3 ? '小节' : maxLevel === 2 ? '节' : '章节'}` };
  2171. return;
  2172. }
  2173. if (leafNodesWithVideo.length !== leafNodes.length) {
  2174. ctx.body = {
  2175. code: 1,
  2176. message: `并非所有${maxLevel === 3 ? '小节' : maxLevel === 2 ? '节' : '章节'}都已完成视频生成,无法合并`,
  2177. data: {
  2178. totalLeafNodes: leafNodes.length,
  2179. completedVideoNodes: leafNodesWithVideo.length,
  2180. }
  2181. };
  2182. return;
  2183. }
  2184. // 按父节点分组叶节点(通常是1级章节)
  2185. const groupedByParent: { [key: number]: any[] } = {};
  2186. leafNodesWithVideo.forEach(node => {
  2187. if (node.parentId) {
  2188. if (!groupedByParent[node.parentId]) {
  2189. groupedByParent[node.parentId] = [];
  2190. }
  2191. groupedByParent[node.parentId].push(node);
  2192. }
  2193. });
  2194. // 对每个父节点下的叶节点视频进行合并
  2195. let totalProcessedParents = 0;
  2196. for (const parentId in groupedByParent) {
  2197. const childNodes = groupedByParent[parentId];
  2198. if (childNodes.length > 0) {
  2199. // 获取父章节信息
  2200. const parentChapter = chapters.find((c: any) => c.id === parseInt(parentId));
  2201. if (parentChapter) {
  2202. try {
  2203. // 调用合并函数
  2204. const mergedVideoUrl = await mergeChapterVideos(
  2205. parentChapter,
  2206. childNodes,
  2207. book.userId || 1
  2208. );
  2209. if (mergedVideoUrl) {
  2210. // 更新父章节的视频URL
  2211. await bookStore.updateChapterById(parentChapter.id, {
  2212. videoUrl: mergedVideoUrl,
  2213. });
  2214. console.log(`[Merge Video] 章节 ${parentChapter.number}(${parentChapter.title}) 视频合并完成: ${mergedVideoUrl}`);
  2215. totalProcessedParents++;
  2216. }
  2217. } catch (error) {
  2218. console.error(`[Merge Video] 章节 ${parentChapter.number}(${parentChapter.title}) 视频合并失败:`, error);
  2219. // 不抛出异常,继续处理其他章节
  2220. }
  2221. }
  2222. }
  2223. }
  2224. ctx.body = {
  2225. code: 0,
  2226. message: `视频合并任务已完成,共处理 ${totalProcessedParents} 个上级章节`,
  2227. data: {
  2228. processedParents: totalProcessedParents,
  2229. totalLeafNodes: leafNodes.length,
  2230. },
  2231. };
  2232. } catch (error) {
  2233. console.error('合并视频失败:', error);
  2234. ctx.status = 500;
  2235. ctx.body = { code: 1, message: error instanceof Error ? error.message : '合并视频失败' };
  2236. }
  2237. });
  2238. /**
  2239. * 合并章节视频的辅助函数
  2240. */
  2241. async function mergeChapterVideos(parentChapter: any, childChapters: any[], userId: number) {
  2242. try {
  2243. // 获取项目根目录(假设视频文件存储在特定目录下)
  2244. const videoDir = path.join(__dirname, '../../../../../../uploads/video');
  2245. const outputDir = path.join(videoDir, 'merged');
  2246. // 确保输出目录存在
  2247. await fs.mkdir(outputDir, { recursive: true });
  2248. // 创建合并文件列表
  2249. const fileListPath = path.join(videoDir, `merge_list_${parentChapter.id}.txt`);
  2250. const outputPath = path.join(outputDir, `merged_chapter_${parentChapter.id}_${Date.now()}.mp4`);
  2251. // 准备要合并的视频文件路径
  2252. const videoPaths = [];
  2253. for (const child of childChapters) {
  2254. if (child.videoUrl) {
  2255. // 从URL提取文件名
  2256. const fileName = path.basename(child.videoUrl);
  2257. const fullPath = path.join(videoDir, fileName);
  2258. // 检查文件是否存在
  2259. try {
  2260. await fs.access(fullPath);
  2261. videoPaths.push(fullPath);
  2262. } catch (err) {
  2263. console.error(`[Merge Video] 文件不存在: ${fullPath}`, err);
  2264. continue; // 跳过不存在的文件
  2265. }
  2266. }
  2267. }
  2268. if (videoPaths.length === 0) {
  2269. throw new Error('没有找到有效的视频文件');
  2270. }
  2271. if (videoPaths.length === 1) {
  2272. // 如果只有一个视频,检查格式是否一致
  2273. const srcExt = videoPaths[0].split('.').pop()?.toLowerCase();
  2274. const dstExt = outputPath.split('.').pop()?.toLowerCase();
  2275. if (srcExt !== dstExt) {
  2276. // 格式不同,用 FFmpeg 转码
  2277. const cmd = `ffmpeg -i "${videoPaths[0]}" -c copy -y "${outputPath}"`;
  2278. console.log(`[Merge Video] 格式不同,转码: ${cmd}`);
  2279. await execPromise(cmd);
  2280. } else {
  2281. await fs.copyFile(videoPaths[0], outputPath);
  2282. }
  2283. const relativePath = outputPath.replace(videoDir, '/uploads/video').replace(/\\/g, '/');
  2284. return relativePath;
  2285. }
  2286. // 创建FFmpeg输入列表 - 使用concat协议来合并视频
  2287. const inputLines = videoPaths.map(videoPath => `file '${videoPath}'`).join('\n');
  2288. await fs.writeFile(fileListPath, inputLines);
  2289. // 使用FFmpeg合并视频 - 更安全的方式,避免编码问题
  2290. // 先尝试简单的copy方式
  2291. const cmd = `ffmpeg -f concat -safe 0 -i "${fileListPath}" -c copy -avoid_negative_ts make_zero "${outputPath}"`;
  2292. console.log(`[Merge Video] 执行命令: ${cmd}`);
  2293. let result;
  2294. try {
  2295. result = await execPromise(cmd);
  2296. console.log(`[Merge Video] FFmpeg stdout:`, result.stdout);
  2297. console.log(`[Merge Video] FFmpeg stderr:`, result.stderr);
  2298. } catch (execErr: any) {
  2299. console.warn(`[Merge Video] copy模式失败,尝试重新编码:`, execErr.message);
  2300. // 如果简单copy失败,尝试重新编码
  2301. const reencodeCmd = `ffmpeg -f concat -safe 0 -i "${fileListPath}" -c:v libx264 -c:a aac -avoid_negative_ts make_zero "${outputPath}"`;
  2302. console.log(`[Merge Video] 执行重新编码命令: ${reencodeCmd}`);
  2303. result = await execPromise(reencodeCmd);
  2304. console.log(`[Merge Video] FFmpeg reencode stdout:`, result.stdout);
  2305. console.log(`[Merge Video] FFmpeg reencode stderr:`, result.stderr);
  2306. }
  2307. // 清理临时文件
  2308. await fs.unlink(fileListPath).catch(() => {});
  2309. // 检查输出文件是否成功创建
  2310. try {
  2311. await fs.access(outputPath);
  2312. } catch (err) {
  2313. throw new Error('视频合并后文件未生成');
  2314. }
  2315. // 返回相对路径(相对于上传目录)
  2316. const relativePath = outputPath.replace(videoDir, '/uploads/video').replace(/\\/g, '/');
  2317. return relativePath;
  2318. } catch (error) {
  2319. console.error('[Merge Video] 合并过程中出错:', error);
  2320. throw error;
  2321. }
  2322. }
  2323. /**
  2324. * DEBUG: 手动触发章节音频生成(强制从content_completed重新开始)
  2325. * POST /api/book-generator/debug/trigger-audio
  2326. */
  2327. router.post('/debug/trigger-audio', async (ctx: Context) => {
  2328. try {
  2329. const { chapterId } = ctx.request.body as { chapterId?: number };
  2330. if (!chapterId) {
  2331. ctx.status = 400;
  2332. ctx.body = { code: 1, message: '缺少 chapterId' };
  2333. return;
  2334. }
  2335. // 先检查chapter状态,如果是audio_generating但没有audioUrl,说明之前的生成卡住了
  2336. const chapter = await prisma.bookChapter.findUnique({ where: { id: chapterId } });
  2337. if (chapter?.genStage === 'audio_generating' && !chapter?.audioUrl) {
  2338. console.log(`[DEBUG] 章节${chapterId}卡在audio_generating无audioUrl,重置到content_completed重新生成`);
  2339. await prisma.bookChapter.update({ where: { id: chapterId }, data: { genStage: 'content_completed' } });
  2340. }
  2341. console.log(`[DEBUG] 手动触发章节${chapterId}音频生成`);
  2342. await bookStore.generateChapterAudioById(chapterId);
  2343. const updated = await prisma.bookChapter.findUnique({ where: { id: chapterId } });
  2344. ctx.body = {
  2345. code: 0,
  2346. message: '音频生成已触发',
  2347. data: { chapterId, genStage: updated?.genStage, audioUrl: updated?.audioUrl },
  2348. };
  2349. } catch (error) {
  2350. console.error('[DEBUG] 触发音频失败:', error);
  2351. ctx.status = 500;
  2352. ctx.body = { code: 1, message: error instanceof Error ? error.message : '触发失败' };
  2353. }
  2354. });
  2355. // ============ 交互式生成 API ============
  2356. /**
  2357. * POST /api/book-generator/langgraph/books/:id/interactive/plan
  2358. * 异步启动深度规划,前端通过 GET 同名接口轮询结果
  2359. */
  2360. router.post('/books/:id/interactive/plan', optionalAuth, async (ctx: Context) => {
  2361. try {
  2362. const bookId = ctx.params.id;
  2363. const idNum = parseInt(bookId);
  2364. const book = await prisma.book.findUnique({ where: { id: idNum } });
  2365. if (!book) {
  2366. ctx.status = 404;
  2367. ctx.body = { code: 1, message: '书籍不存在' };
  2368. return;
  2369. }
  2370. // 标记为生成中,立即返回
  2371. await prisma.book.update({
  2372. where: { id: idNum },
  2373. data: { genStage: 'plan_generating' },
  2374. });
  2375. // 构造 minimal state
  2376. const body = (ctx.request as any).body || {};
  2377. const userFeedback = body.feedback || '';
  2378. const initState: any = {
  2379. bookId,
  2380. topic: book.description,
  2381. bookScale: book.bookScale || '1000',
  2382. genLevel: (book as any).genLevel || 2,
  2383. description: book.description,
  2384. title: book.title,
  2385. userId: book.userId,
  2386. completedChapters: [],
  2387. failedChapters: [],
  2388. userFeedback,
  2389. };
  2390. console.log(`[Interactive] 深度规划已启动(异步): bookId=${bookId}${userFeedback ? ', 含用户反馈' : ''}`);
  2391. // 异步执行 AI 调用,不阻塞响应
  2392. setImmediate(async () => {
  2393. try {
  2394. const result = await deepPlanBookNode(initState);
  2395. const bookPlan = result.bookPlan || '';
  2396. await prisma.book.update({
  2397. where: { id: idNum },
  2398. data: { bookAnalysis: bookPlan, genStage: 'plan_ready' },
  2399. });
  2400. console.log(`[Interactive] 深度规划完成: bookId=${bookId}`);
  2401. } catch (err) {
  2402. console.error(`[Interactive] 深度规划失败: bookId=${bookId}`, err);
  2403. await prisma.book.update({
  2404. where: { id: idNum },
  2405. data: { genStage: 'plan_failed', errorMsg: err instanceof Error ? err.message : '规划失败' },
  2406. });
  2407. }
  2408. });
  2409. ctx.body = {
  2410. code: 0,
  2411. message: '规划已启动',
  2412. data: { genStage: 'plan_generating' },
  2413. };
  2414. } catch (error) {
  2415. console.error('[Interactive] plan 启动失败:', error);
  2416. ctx.status = 500;
  2417. ctx.body = { code: 1, message: error instanceof Error ? error.message : '启动失败' };
  2418. }
  2419. });
  2420. /**
  2421. * GET /api/book-generator/langgraph/books/:id/interactive/plan
  2422. * 轮询获取深度规划结果
  2423. */
  2424. router.get('/books/:id/interactive/plan', optionalAuth, async (ctx: Context) => {
  2425. try {
  2426. const bookId = ctx.params.id;
  2427. const book = await prisma.book.findUnique({ where: { id: parseInt(bookId) } });
  2428. if (!book) {
  2429. ctx.status = 404;
  2430. ctx.body = { code: 1, message: '书籍不存在' };
  2431. return;
  2432. }
  2433. const stage = (book as any).genStage || '';
  2434. if (stage === 'plan_failed') {
  2435. ctx.body = { code: 0, data: { genStage: 'plan_failed', error: (book as any).errorMsg || '规划失败' } };
  2436. return;
  2437. }
  2438. if (stage === 'plan_ready' || book.bookAnalysis) {
  2439. const bookPlan = book.bookAnalysis || '';
  2440. let planData: any = null;
  2441. try {
  2442. const fixed_json = bookPlan.replace(/\\u000a/g, '\\n').replace(/\\\\/g, '\\');
  2443. const match = fixed_json.match(/\{[\s\S]*\}/);
  2444. if (match) planData = JSON.parse(match[0]);
  2445. } catch (e) { /* ignore */ }
  2446. ctx.body = {
  2447. code: 0,
  2448. message: '规划完成',
  2449. data: { rawPlan: bookPlan, planData, genStage: 'plan_ready' },
  2450. };
  2451. return;
  2452. }
  2453. // 还在生成中
  2454. ctx.body = {
  2455. code: 0,
  2456. data: { genStage: stage || 'plan_generating' },
  2457. };
  2458. } catch (error) {
  2459. console.error('[Interactive] 查询 plan 失败:', error);
  2460. ctx.status = 500;
  2461. ctx.body = { code: 1, message: '查询失败' };
  2462. }
  2463. });
  2464. /**
  2465. * PUT /api/book-generator/langgraph/books/:id/interactive/plan
  2466. * 保存用户修改后的 plan
  2467. */
  2468. router.put('/books/:id/interactive/plan', optionalAuth, async (ctx: Context) => {
  2469. try {
  2470. const bookId = ctx.params.id;
  2471. const { plan } = ctx.request.body as { plan: string };
  2472. if (!plan) {
  2473. ctx.status = 400;
  2474. ctx.body = { code: 1, message: 'plan 不能为空' };
  2475. return;
  2476. }
  2477. await prisma.book.update({
  2478. where: { id: parseInt(bookId) },
  2479. data: { bookAnalysis: plan },
  2480. });
  2481. ctx.body = { code: 0, message: 'Plan 已保存' };
  2482. } catch (error) {
  2483. console.error('[Interactive] 保存 plan 失败:', error);
  2484. ctx.status = 500;
  2485. ctx.body = { code: 1, message: error instanceof Error ? error.message : '保存失败' };
  2486. }
  2487. });
  2488. /**
  2489. * POST /api/book-generator/langgraph/books/:id/interactive/outline
  2490. * 异步启动大纲生成,前端通过 GET 同名接口轮询结果
  2491. */
  2492. router.post('/books/:id/interactive/outline', optionalAuth, async (ctx: Context) => {
  2493. try {
  2494. const bookId = ctx.params.id;
  2495. const idNum = parseInt(bookId);
  2496. const book = await prisma.book.findUnique({ where: { id: idNum } });
  2497. if (!book) {
  2498. ctx.status = 404;
  2499. ctx.body = { code: 1, message: '书籍不存在' };
  2500. return;
  2501. }
  2502. // 标记为生成中,立即返回
  2503. await prisma.book.update({
  2504. where: { id: idNum },
  2505. data: { genStage: 'outline_generating' },
  2506. });
  2507. // 构造 state,使用已保存的 plan
  2508. const initState: any = {
  2509. bookId,
  2510. topic: book.description,
  2511. bookScale: book.bookScale || '1000',
  2512. genLevel: (book as any).genLevel || 2,
  2513. description: book.description,
  2514. title: book.title,
  2515. userId: book.userId,
  2516. bookPlan: book.bookAnalysis || '',
  2517. completedChapters: [],
  2518. failedChapters: [],
  2519. };
  2520. console.log(`[Interactive] 大纲生成已启动(异步): bookId=${bookId}`);
  2521. // 异步执行 AI 调用
  2522. setImmediate(async () => {
  2523. try {
  2524. await richOutlineNode(initState);
  2525. // richOutlineNode 内部已通过 bookStore.update 写入 outlineJson
  2526. await prisma.book.update({
  2527. where: { id: idNum },
  2528. data: { genStage: 'outline_ready' },
  2529. });
  2530. console.log(`[Interactive] 大纲生成完成: bookId=${bookId}`);
  2531. } catch (err) {
  2532. console.error(`[Interactive] 大纲生成失败: bookId=${bookId}`, err);
  2533. await prisma.book.update({
  2534. where: { id: idNum },
  2535. data: { genStage: 'outline_failed', errorMsg: err instanceof Error ? err.message : '大纲生成失败' },
  2536. });
  2537. }
  2538. });
  2539. ctx.body = {
  2540. code: 0,
  2541. message: '大纲生成已启动',
  2542. data: { genStage: 'outline_generating' },
  2543. };
  2544. } catch (error) {
  2545. console.error('[Interactive] outline 启动失败:', error);
  2546. ctx.status = 500;
  2547. ctx.body = { code: 1, message: error instanceof Error ? error.message : '启动失败' };
  2548. }
  2549. });
  2550. /**
  2551. * GET /api/book-generator/langgraph/books/:id/interactive/outline
  2552. * 轮询获取大纲生成结果
  2553. */
  2554. router.get('/books/:id/interactive/outline', optionalAuth, async (ctx: Context) => {
  2555. try {
  2556. const bookId = ctx.params.id;
  2557. const book = await prisma.book.findUnique({ where: { id: parseInt(bookId) } });
  2558. if (!book) {
  2559. ctx.status = 404;
  2560. ctx.body = { code: 1, message: '书籍不存在' };
  2561. return;
  2562. }
  2563. const stage = (book as any).genStage || '';
  2564. if (stage === 'outline_failed') {
  2565. ctx.body = { code: 0, data: { genStage: 'outline_failed', error: (book as any).errorMsg || '大纲生成失败' } };
  2566. return;
  2567. }
  2568. if (stage === 'outline_ready' || book.outlineJson) {
  2569. const outlineJson = book.outlineJson || '';
  2570. let outlineData: any = null;
  2571. try {
  2572. outlineData = typeof outlineJson === 'string' ? JSON.parse(outlineJson) : outlineJson;
  2573. } catch (e) { /* ignore */ }
  2574. ctx.body = {
  2575. code: 0,
  2576. message: '大纲生成完成',
  2577. data: { rawOutline: outlineJson, outlineData, genStage: 'outline_ready' },
  2578. };
  2579. return;
  2580. }
  2581. // 还在生成中
  2582. ctx.body = {
  2583. code: 0,
  2584. data: { genStage: stage || 'outline_generating' },
  2585. };
  2586. } catch (error) {
  2587. console.error('[Interactive] 查询 outline 失败:', error);
  2588. ctx.status = 500;
  2589. ctx.body = { code: 1, message: '查询失败' };
  2590. }
  2591. });
  2592. /**
  2593. * PUT /api/book-generator/langgraph/books/:id/interactive/outline
  2594. * 保存用户修改后的大纲,并重建章节树
  2595. */
  2596. router.put('/books/:id/interactive/outline', optionalAuth, async (ctx: Context) => {
  2597. try {
  2598. const bookId = ctx.params.id;
  2599. const { outline } = ctx.request.body as { outline: any };
  2600. if (!outline) {
  2601. ctx.status = 400;
  2602. ctx.body = { code: 1, message: 'outline 不能为空' };
  2603. return;
  2604. }
  2605. const outlineStr = typeof outline === 'string' ? outline : JSON.stringify(outline);
  2606. await prisma.book.update({
  2607. where: { id: parseInt(bookId) },
  2608. data: { outlineJson: outlineStr },
  2609. });
  2610. // 根据大纲重建章节树(删除旧章节,创建新章节)
  2611. const chapterData = typeof outline === 'string' ? JSON.parse(outline) : outline;
  2612. const chapters = chapterData.chapters || [];
  2613. // 删除旧章节
  2614. await prisma.bookChapter.deleteMany({ where: { bookId: parseInt(bookId) } });
  2615. // 插入新章节(递归处理章→节→小节)
  2616. let chapterNumber = 0;
  2617. async function insertChapters(parentId: number | null, items: any[], level: number) {
  2618. for (const item of items) {
  2619. chapterNumber++;
  2620. const section = await prisma.bookChapter.create({
  2621. data: {
  2622. bookId: parseInt(bookId),
  2623. title: item.title || '未命名章节',
  2624. summary: item.summary || '',
  2625. content: '',
  2626. wordCount: item.estimatedWords || 0,
  2627. number: chapterNumber,
  2628. level,
  2629. parentId,
  2630. genStage: 'draft',
  2631. },
  2632. });
  2633. // 递归处理子节点(节、小节)
  2634. if (item.sections && item.sections.length > 0) {
  2635. await insertChapters(section.id, item.sections, level + 1);
  2636. }
  2637. if (item.subsections && item.subsections.length > 0) {
  2638. await insertChapters(section.id, item.subsections, level + 1);
  2639. }
  2640. }
  2641. }
  2642. await insertChapters(null, chapters, 1);
  2643. // 更新书籍的章节计数
  2644. await prisma.book.update({
  2645. where: { id: parseInt(bookId) },
  2646. data: { totalChapters: chapterNumber },
  2647. });
  2648. ctx.body = {
  2649. code: 0,
  2650. message: '大纲已保存,章节树已重建',
  2651. data: { chapterCount: chapterNumber },
  2652. };
  2653. } catch (error) {
  2654. console.error('[Interactive] 保存 outline 失败:', error);
  2655. ctx.status = 500;
  2656. ctx.body = { code: 1, message: error instanceof Error ? error.message : '保存失败' };
  2657. }
  2658. });
  2659. /**
  2660. * POST /api/book-generator/langgraph/books/:id/interactive/generate
  2661. * 运行并行内容生成 + 连贯性编辑
  2662. */
  2663. router.post('/books/:id/interactive/generate', optionalAuth, async (ctx: Context) => {
  2664. try {
  2665. const bookId = ctx.params.id;
  2666. const book = await prisma.book.findUnique({ where: { id: parseInt(bookId) } });
  2667. if (!book) {
  2668. ctx.status = 404;
  2669. ctx.body = { code: 1, message: '书籍不存在' };
  2670. return;
  2671. }
  2672. const userId = book.userId || parseInt(TEST_USER_ID);
  2673. // 配额检查
  2674. const scaleConfig = getScaleConfig(book.bookScale || '1000');
  2675. const totalWords = scaleConfig.totalWords;
  2676. const audioQuota = await checkAudioQuota(userId, totalWords);
  2677. if (!audioQuota.allowed) {
  2678. ctx.status = 403;
  2679. ctx.body = { code: 1, message: audioQuota.reason };
  2680. return;
  2681. }
  2682. // 构造 minimal state
  2683. const initState: any = {
  2684. bookId,
  2685. topic: book.description,
  2686. bookScale: book.bookScale || '1000',
  2687. genLevel: (book as any).genLevel || 2,
  2688. description: book.description,
  2689. title: book.title,
  2690. userId,
  2691. bookPlan: book.bookAnalysis || '',
  2692. outline: book.outlineJson || '',
  2693. completedChapters: [],
  2694. failedChapters: [],
  2695. };
  2696. console.log(`[Interactive] 开始并行生成内容: bookId=${bookId}`);
  2697. // ===== 直接异步生成(跳过队列) =====
  2698. const { langGraphGenerator } = await import('./index.js');
  2699. langGraphGenerator.generate(
  2700. bookId,
  2701. book.description,
  2702. book.bookScale || '1000',
  2703. (book as any).genLevel || 2
  2704. ).then(() => {
  2705. console.log(`[Interactive] 生成完成: bookId=${bookId}`);
  2706. }).catch(err => {
  2707. console.error(`[Interactive] 生成失败: bookId=${bookId}`, err);
  2708. });
  2709. await prisma.book.update({
  2710. where: { id: parseInt(bookId) },
  2711. data: { genStage: 'generating_content' },
  2712. });
  2713. ctx.body = {
  2714. code: 0,
  2715. message: '内容生成已启动',
  2716. data: { bookId, genStage: 'generating_content', mode: 'direct' },
  2717. };
  2718. return;
  2719. try {
  2720. await prisma.book.update({
  2721. where: { id: parseInt(bookId) },
  2722. data: { genStage: 'generating_content' },
  2723. });
  2724. // Step 1: 并行生成内容
  2725. const contentResult = await writeChaptersParallelNode(initState);
  2726. console.log(`[Interactive] 并行内容生成完成: bookId=${bookId}`);
  2727. // Step 2: 连贯性编辑
  2728. const mergeState = { ...initState, ...contentResult };
  2729. await continuityEditNode(mergeState);
  2730. console.log(`[Interactive] 连贯性编辑完成: bookId=${bookId}`);
  2731. ctx.body = {
  2732. code: 0,
  2733. message: '内容生成完成',
  2734. data: { bookId, genStage: 'completed', mode: 'sync' },
  2735. };
  2736. } catch (generateError) {
  2737. console.error(`[Interactive] 内容生成失败: bookId=${bookId}`, generateError);
  2738. await prisma.book.update({
  2739. where: { id: parseInt(bookId) },
  2740. data: { genStage: 'failed', errorMsg: generateError instanceof Error ? generateError.message : '生成失败' },
  2741. });
  2742. ctx.status = 500;
  2743. ctx.body = { code: 1, message: generateError instanceof Error ? generateError.message : '生成失败' };
  2744. }
  2745. } catch (error) {
  2746. console.error('[Interactive] generate 失败:', error);
  2747. ctx.status = 500;
  2748. ctx.body = { code: 1, message: error instanceof Error ? error.message : '生成失败' };
  2749. }
  2750. });
  2751. export default router;