chapter.ts 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. import { HumanMessage, SystemMessage } from 'langchain/schema'
  2. import { StructuredOutputParser } from 'langchain/output_parsers'
  3. import { z } from 'zod'
  4. import { uploadUml } from './upload'
  5. import { LLMTools } from './types'
  6. async function _genChapters(tools: LLMTools, major: string, title: string, desc: string) {
  7. const { llm, usage, conversation } = tools
  8. const scheme = StructuredOutputParser.fromZodSchema(
  9. z.array(
  10. z.object({
  11. chapterName: z.string().describe('章节名称'),
  12. sections: z.array(
  13. z.object({
  14. sectionName: z.string().describe('小节名称')
  15. })
  16. )
  17. })
  18. )
  19. )
  20. const { chain } = conversation(
  21. `你是一个擅长写${major}专业毕业论文的专家,你的任务是帮我完成我的论文。
  22. 你要根据我的要求,帮我完成我的论文`,
  23. 100
  24. )
  25. // await chain.call({
  26. // input: `我们一步一步来完成。
  27. // 首先我们要拟定一个论文的大纲。
  28. // 我们先不着急确定,先想一想一般${major}专业的毕业论文的大纲是怎样的呢`
  29. // })
  30. await chain.call({
  31. input: `我的论文标题是${title},
  32. 请你帮我拟定一个论文的大纲。
  33. 请注意:拟订的大纲不要过于笼统,结构要清晰,要与论文主题贴切`
  34. })
  35. const { response } = await chain.call({
  36. input: `------
  37. ${scheme.getFormatInstructions()}
  38. ------
  39. 好的根据以上内容我们来确定一个更加详细的论文的大纲(你的回答关系到我的工作和职业生涯,请认真一点,注意JSON格式):`
  40. })
  41. return await scheme.parse(response)
  42. }
  43. function formatChapters(chapters: any[]) {
  44. chapters.forEach((item: any) => {
  45. if (item.chapterName) {
  46. item.title = item.chapterName
  47. } else {
  48. item.title = item.sectionName
  49. }
  50. if (item.sections) {
  51. item.children = item.sections
  52. }
  53. delete item.sections
  54. delete item.chapterName
  55. delete item.chapterDesc
  56. delete item.sectionName
  57. delete item.sectionDesc
  58. if (item.children) {
  59. formatChapters(item.children)
  60. }
  61. })
  62. return chapters
  63. }
  64. export async function genChapters(tools: LLMTools, major, title, desc) {
  65. const pRetry = (await eval("import('p-retry')")).default
  66. const chapters = await pRetry(() => _genChapters(tools, major, title, desc), {
  67. retries: 5,
  68. onFailedAttempt: (e) => console.log(e.stack)
  69. })
  70. // await Promise.all(
  71. // chapters.map((i, index) => {
  72. // return pRetry(() => genSections(major, tools, title, desc, chapters, index), { retries: 5 })
  73. // })
  74. // )
  75. return formatChapters(chapters)
  76. }