write_novel.py
1 #!/usr/bin/env python 2 # -*- coding: utf-8 -*- 3 """ 4 @Time : 2024/2/1 12:01 5 @Author : alexanderwu 6 @File : write_novel.py 7 """ 8 import asyncio 9 from typing import List 10 11 from pydantic import BaseModel, Field 12 13 from metagpt.actions.action_node import ActionNode 14 from metagpt.llm import LLM 15 16 17 class Chapter(BaseModel): 18 name: str = Field(default="Chapter 1", description="The name of the chapter.") 19 content: str = Field(default="...", description="The content of the chapter. No more than 1000 words.") 20 21 22 class Chapters(BaseModel): 23 chapters: List[Chapter] = Field( 24 default=[ 25 {"name": "Chapter 1", "content": "..."}, 26 {"name": "Chapter 2", "content": "..."}, 27 {"name": "Chapter 3", "content": "..."}, 28 ], 29 description="The chapters of the novel.", 30 ) 31 32 33 class Novel(BaseModel): 34 name: str = Field(default="The Lord of the Rings", description="The name of the novel.") 35 user_group: str = Field(default="...", description="The user group of the novel.") 36 outlines: List[str] = Field( 37 default=["Chapter 1: ...", "Chapter 2: ...", "Chapter 3: ..."], 38 description="The outlines of the novel. No more than 10 chapters.", 39 ) 40 background: str = Field(default="...", description="The background of the novel.") 41 character_names: List[str] = Field(default=["Frodo", "Gandalf", "Sauron"], description="The characters.") 42 conflict: str = Field(default="...", description="The conflict of the characters.") 43 plot: str = Field(default="...", description="The plot of the novel.") 44 ending: str = Field(default="...", description="The ending of the novel.") 45 46 47 async def generate_novel(): 48 instruction = ( 49 "Write a novel named 'Reborn in Skyrim'. " 50 "Fill the empty nodes with your own ideas. Be creative! Use your own words!" 51 "I will tip you $100,000 if you write a good novel." 52 ) 53 novel_node = await ActionNode.from_pydantic(Novel).fill(req=instruction, llm=LLM()) 54 chap_node = await ActionNode.from_pydantic(Chapters).fill( 55 req=f"### instruction\n{instruction}\n### novel\n{novel_node.content}", llm=LLM() 56 ) 57 print(chap_node.instruct_content) 58 59 60 asyncio.run(generate_novel())