Generate a coherent book draft from a title and a writing brief, with a planned chapter structure, continuity between sections, and a Markdown manuscript you can edit. Works for nonfiction and fiction.
The generator uses the OpenAI Responses API and structured outputs. It plans the book before writing, divides long chapters into manageable sections, validates chapter counts and section lengths, and saves progress after each accepted section. Failed, refused, empty, or truncated responses are never treated as finished prose.
Requires Python 3.10 or newer and an OpenAI API account with access to the selected model.
git clone https://github.com/DevilsNerve/PythonOpenAIBookGenerator.git
cd PythonOpenAIBookGenerator
python -m venv .venv
source .venv/bin/activate
python -m pip install -r requirements.txt
export OPENAI_API_KEY="your-api-key"On Windows PowerShell, activate with .venv\Scripts\Activate.ps1 and set the key
with $env:OPENAI_API_KEY="your-api-key".
Keep credentials in the environment, not in book.py. .env files are ignored by
Git but are not loaded automatically. The default model is gpt-6-astra;
change it with --model or OPENAI_MODEL. The selected model must support the
Responses API and JSON Schema structured outputs. Check model access for your
account before a large run. See the official OpenAI model guidance
and structured output documentation.
python book.py "The Future of Technology" \
--theme "A practical exploration of how AI, energy, and biotechnology could change everyday life. Distinguish established facts from speculation." \
--chapters 5 \
--words-per-chapter 2000 \
--audience "curious adult readers without a technical background" \
--style "Concrete examples, accessible explanations, and an optimistic but critical voice" \
--output books/future.mdFor a novel:
python book.py "The Last Lighthouse" \
--kind fiction \
--theme "An aging lighthouse keeper and her estranged daughter uncover why their coastal town has vanished from every map. Resolve their relationship and the mystery." \
--chapters 12 \
--words-per-chapter 2500 \
--style "Atmospheric mystery, close third person, restrained dialogue" \
--output books/lighthouse.mdWithout --output, the filename is a safe version of the title in the current
directory. The Markdown includes a linked contents page, chapter headings, and
section headings for long nonfiction chapters or scene breaks for fiction.
The original Python entry point still works:
from book import write_book
path = write_book(
"My AI Generated Book",
"The Future of Technology",
num_chapters=5,
words_per_chapter=2000,
output_path="books/future.md",
)
print(path)New books default to 10 chapters and at least 1000 prose words per chapter. Supported ranges are 1–50 chapters and 50–10000 words per chapter. Word counts use whitespace-separated words containing letters or numbers; they are not suitable as linguistic word counts for languages without spaces. Length is a minimum, not an exact count: completed sentences and paragraphs are retained. Short sections are regenerated with feedback, with at most three attempts per stage; the script never pads or abruptly slices prose to meet a count.
Run python book.py --help for all options, including --language, --model,
--quiet, and network/request limits.
Press Ctrl+C to stop. To continue:
python book.py --output books/future.md --resumeOr from Python:
from book import write_book
path = write_book(output_path="books/future.md", resume=True)A book consists of:
future.md: the readable manuscript, clearly marked as in progress until all sections are complete.future.md.state.json: the specification, outline, accepted prose, cumulative continuity notes, request count, reported token usage, and recovery checksums.future.md.lock: an operating-system lock preventing two generators from writing the same book simultaneously. The empty lock file can remain after exit; its presence alone does not mean another process is running.
Keep the checkpoint beside its manuscript. Resume uses the saved settings and
model, even if OPENAI_MODEL changes. Any explicitly supplied book settings must
match the checkpoint. Completed sections are reused; only the unfinished request
may need to be repeated. A finished book can be re-exported from its checkpoint
without an API key or any new API requests.
Output and checkpoints are written using temporary files and atomic replacement. Resume also recovers an interruption between a checkpoint write and its Markdown write. Existing manuscripts are never silently overwritten: a new run requires a new path, and resume refuses to overwrite a manually edited manuscript. Copy or move that edited file elsewhere before resuming. Keep independent backups; the checkpoint contains the manuscript and is not an independent backup.
There is no endless generation loop or unconditional delay between successful calls. Transient connection failures, rate limits, and server errors use the SDK's bounded retry/backoff behavior. Authentication and other permanent API errors stop with an actionable message.
Each chapter is divided into ceil(words_per_chapter / 800) sections. A successful
first-pass run needs one outline request plus one request per section. For
example, five 2000-word chapters need 16 logical requests before any
validation retries. The default lifetime budget is three times that number.
python book.py --output books/future.md --resume \
--max-requests 60 \
--max-output-tokens 32768 \
--max-retries 2 \
--timeout 120--max-requestscaps logical requests across the book's whole checkpoint history, including unsuccessful and interrupted requests. Raise it deliberately when resuming after exhaustion.--max-retriescontrols SDK retries within each logical request, default 2. Actual HTTP attempts can therefore exceed--max-requests; set retries to 0 if each logical request must have only one HTTP attempt.--max-output-tokenscaps output per request, default 16384, including reasoning tokens. Increase it if an outline or section is incomplete because of the token limit, especially for large outlines or reasoning models.--timeoutsets the SDK timeout in seconds, default 120. It is not a deadline for generating the whole book, and retries can extend the elapsed time.
API calls cost money according to the selected model and actual input/output usage. Request and token caps are not a dollar budget. Rejected generations can be billable; usage reported in the checkpoint excludes unreported usage from interrupted calls or failed HTTP attempts. Configure account spending controls as needed. Check your key/model access for authentication or permission errors; check API quota and billing before resuming after rate-limit errors.
The output is a draft. The outline, continuity notes, and revision prompts help consistency, but they do not prove factual accuracy or literary quality. Review facts, citations, plot continuity, and prose before publication; this script does not perform independent research or fact checking.
python -m pip install -r requirements-dev.txt
python -m pytest -q
ruff check book.py tests
ruff format --check book.py testsTests run offline without an API key or charges. They exercise the real OpenAI SDK with simulated HTTP responses, plus the actual CLI against a local HTTP server. Coverage includes successful generation, continuity prompts, malformed responses, short/duplicate sections, refusals, truncation, SDK retries, request budgets, interruption, recovery after write failures, manual-edit protection, filename safety, concurrent writers, and invalid configuration. These tests do not establish live model availability or the quality of a generated book.
Generated books belong in books/ (ignored by Git). Checkpoints, locks, virtual
environments, and local credentials are also ignored. No GitHub Actions workflows
are configured; the checks above run locally.