我直接给你一套可运行、极简、能生成《操作系统原理》的 LangGraph 代码模板。 你只要把 API Key 填进去就能跑,结构完全对应你最开始问的:
AI 先做大纲规划 → 按计划分步执行 → 循环写章节 → 统一成书
pip install langchain langgraph langchain-openai python-dotenv
import os
from typing import TypedDict, Annotated, List
from langchain_openai import ChatOpenAI
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.messages import HumanMessage
from langgraph.graph import StateGraph, END
import json
# ---------------------
# 1. 全局状态(全书共享记忆)
# ---------------------
class BookState(TypedDict):
topic: str # 书名/主题
book_outline: dict # 大纲(章节+小节)
current_chapter: int # 当前写到第几章
current_section: int # 当前写到第几节
contents: List[str] # 已写内容
finished: bool # 是否写完
# ---------------------
# 2. 大模型
# ---------------------
llm = ChatOpenAI(
model="gpt-3.5-turbo",
temperature=0.2,
api_key="你的OPENAI_API_KEY",
# base_url="https://xxx/v1" # 国内转发可填
)
# ---------------------
# 节点1:生成全书大纲(规划阶段)
# ---------------------
def generate_outline(state: BookState):
print("=== 正在生成书籍大纲 ===")
prompt = f"""
你是计算机教材作者。请为《{state['topic']}》生成结构化大纲。
要求:
- 共10章
- 每章4~6个小节
- 严格返回JSON,不要其他文字
格式:
{{
"chapters": [
{{
"chapter": 1,
"title": "章节标题",
"sections": [
{{"section": 1.1, "title": "小节标题"}},
...
]
}}
]
}}
"""
response = llm.invoke([HumanMessage(content=prompt)])
outline = json.loads(response.content.strip())
return {"book_outline": outline, "current_chapter": 1, "current_section": 0}
# ---------------------
# 节点2:写当前小节(执行阶段)
# ---------------------
def write_section(state: BookState):
outline = state["book_outline"]
chap = state["current_chapter"]
sec_idx = state["current_section"]
# 找到当前章节&小节
chapter = next(c for c in outline["chapters"] if c["chapter"] == chap)
section = chapter["sections"][sec_idx]
print(f"正在写 {chap}.{section['section']} {section['title']}")
prompt = f"""
你正在编写教材《{state['topic']}》。
章节:{chapter['title']}
小节:{section['title']}
要求:
- 本科水平,正式教材风格
- 600~800字
- 只写正文,不要标题
"""
content = llm.invoke([HumanMessage(content=prompt)]).content
return {
"contents": state["contents"] + [content],
"current_section": sec_idx + 1
}
# ---------------------
# 节点3:判断是否进入下一章 / 是否完成
# ---------------------
def route_next(state: BookState):
outline = state["book_outline"]
chap = state["current_chapter"]
sec_idx = state["current_section"]
chapter = next(c for c in outline["chapters"] if c["chapter"] == chap)
if sec_idx < len(chapter["sections"]):
return "write_section" # 继续写本节
else:
# 本章写完,下一章
next_chap = chap + 1
if next_chap > len(outline["chapters"]):
return "finish"
else:
return {"current_chapter": next_chap, "current_section": 0}
# ---------------------
# 节点4:完成并保存全书
# ---------------------
def finish_book(state: BookState):
print("=== 全书完成,正在合并内容 ===")
full_text = "\n\n".join(state["contents"])
with open("os_book.md", "w", encoding="utf-8") as f:
f.write(f"# {state['topic']}\n\n" + full_text)
return {"finished": True}
# ---------------------
# 构建 LangGraph 工作流
# ---------------------
workflow = StateGraph(BookState)
# 添加节点
workflow.add_node("generate_outline", generate_outline)
workflow.add_node("write_section", write_section)
workflow.add_node("finish_book", finish_book)
# 设置起点
workflow.set_entry_point("generate_outline")
# 边
workflow.add_edge("generate_outline", "write_section")
workflow.add_conditional_edges(
"write_section",
route_next,
{
"write_section": "write_section",
"finish": "finish_book"
}
)
workflow.add_edge("finish_book", END)
# 编译运行
app = workflow.compile()
# ---------------------
# 启动:生成《操作系统原理》
# ---------------------
if __name__ == "__main__":
result = app.invoke({
"topic": "操作系统原理",
"contents": [],
"finished": False
})
print("✅ 书籍已生成:os_book.md")
你之前问:
AI编辑器先列大纲,再做开发,是怎么实现的?
这个代码就是一模一样的逻辑:
规划阶段(generate_outline) AI 先出全书大纲 = 编程里的需求+架构+开发计划
执行阶段(write_section) 按章节一节节写 = 按任务写代码
流程控制(route_next) 自动判断:本节写完→下一节;本章写完→下一章 = 自动调度开发任务
全局状态(BookState) 保存大纲、进度、已写内容 = 项目进度管理
最终输出(finish_book) 合并成完整书籍 = 项目构建打包
只需要改一下 prompt 就行。
你现在这个写书任务:
这就是目前最标准、最稳定、生产级的官方用法。
如果你想,我可以下一步帮你:
你想继续扩展哪个?