Build a Local Novel-Writing AI Agent from Scratch
This guide walks through building a local AI agent for long-form novel writing, where hundreds of thousands of words make a single large context window both costly and unreliable. It explains a five-layer architecture (interaction, orchestration, skills, memory, and model layers) and shows how to run a local inference service, assemble context on demand, and combine a structured fact store with vector retrieval so the model retains characters, settings, and foreshadowing. It also covers reusable skill modules, a six-step chapter pipeline with retry and resume support, measurable quality metrics, and troubleshooting for style drift, slow pacing, contradictions, and limited GPU memory.
1. Why Move Novel Writing to Local
Long-form novel writing is fundamentally different from short question answering. A single Q&A needs only a few hundred to a few thousand tokens of context, while a novel of several hundred thousand words involves large amounts of structured information: character profiles, worldbuilding, timelines, foreshadowing and payoffs, and scene scheduling. Stuffing all of that into the context window is neither economical nor reliable. Models naturally underuse information in the middle of a long context, and long contexts also bring noticeable latency and cost increases.
Local deployment mainly solves three problems. First, data privacy: unpublished settings and drafts never have to leave your machine. Second, cost control: repeated rewrites and large-scale trial and error are no longer billed per call. Third, style consistency: with fixed local weights, fixed sampling parameters, and fixed prompt templates, you can compress style fluctuation into an acceptable range.
One common misconception needs to be addressed up front: not every general-purpose large model is good at Chinese popular narrative. The right criterion is not benchmark scores but your own small-scale blind test. Prepare 20 Chinese novel excerpts you approve of and 20 creative tasks of the same kind, have the candidate models continue each one, hide the sources, and rank them yourself. This takes half a day and fits your subject matter far better than any published evaluation.
2. Overall Architecture: A Five-Layer Structure
A usable writing agent can be split into five layers that communicate through explicit data contracts, avoiding the temptation to pile all logic into one giant prompt.
┌─────────────────────────────────────┐│ Interaction: writing desk / ││ outline view / version comparison │├─────────────────────────────────────┤│ Orchestration: task decomposition, ││ pipeline scheduling, retries │├─────────────────────────────────────┤│ Skills: setting / outline / ││ prose / review modules │├─────────────────────────────────────┤│ Memory: structured setting store ││ + vector retrieval │├─────────────────────────────────────┤│ Model: local inference service + ││ parameter and sampling strategy │└─────────────────────────────────────┘
The key design principle is assembling context on demand. Before each generation round, the orchestration layer queries the memory layer using the current chapter tags and injects only the genuinely relevant settings into the prompt instead of loading everything.
3. Model Layer: Setting Up a Local Inference Service
Local inference usually means running an open-weight model on your own machine or server and exposing it through an HTTP-compatible interface. On the hardware side, quantized small and mid-sized models run on consumer GPUs; if you want longer context and more stable long-form consistency, choose a machine with more VRAM or a single host with multiple GPUs.
A sample startup command looks like this (exact parameter names depend on the inference framework you use):
# Start an inference service compatible with the common HTTP conventioninference-server serve \--model-path /models/fiction-model \--context-length 32768 \--gpu-memory-utilization 0.85 \--host 127.0.0.1 --port 8000
The client side relies only on common chat completion semantics, which makes swapping the backend easy later:
import json, urllib.requestdef chat(messages, temperature=0.85, max_tokens=2048):payload = {"messages": messages,"temperature": temperature,"top_p": 0.95,"max_tokens": max_tokens,}req = urllib.request.Request("http://127.0.0.1:8000/v1/chat/completions",data=json.dumps(payload).encode("utf-8"),headers={"Content-Type": "application/json"},)with urllib.request.urlopen(req, timeout=600) as resp:return json.load(resp)["choices"][0]["message"]["content"]
Set sampling parameters per stage. Use a low temperature (0.3–0.5) for settings and outlines to keep the logic stable; use a higher temperature (0.8–1.0) for prose to gain linguistic variety; return to a low temperature for review so the model tends to find faults rather than improvise.
4. Memory Layer: Making the Model Remember Hundreds of Thousands of Words
This is the dividing line between success and failure in long-form writing. The recommended approach is a dual track: a structured fact store plus vector retrieval.
The structured fact store can be plain files organized by entity, with one record per entity:
{"id": "char_lin","type": "character","name": "Lin Zhao","role": "protagonist","facts": [{"k": "identity", "v": "apprentice at a border-town pharmacy", "chapter": 3},{"k": "motivation", "v": "searching for a missing older brother", "chapter": 5},{"k": "taboo", "v": "does not drink alcohol", "chapter": 8}],"updated_at": 412}
The vector store holds scene summaries and planted foreshadowing. After each chapter is written, generate a summary of about 150 characters and add it to the store. At retrieval time, issue two queries in parallel: one fetches facts by exact entity name, the other fetches similar summaries by the semantics of the current chapter. Merge and deduplicate the results as context.
Entry updates must follow an append-only, conflict-flagging rule. When a new fact contradicts an old one, do not overwrite it directly; write it to a candidate area marked conflict=true and let the review stage decide. This prevents the model from quietly rewriting established settings during long-range writing.
5. Skill Layer: Breaking Writing into Reusable Skills
The recommended practice for skill modules is one capability per directory, containing a description file, input/output contracts, and prompt templates. The orchestration layer loads them by name.
skills/setting-builder/ # worldbuilding and character profile generationoutline-planner/ # volume-chapter-scene three-level outlinechapter-writer/ # single-chapter prose generationcontinuity-check/ # setting and timeline consistency reviewstyle-polisher/ # style unification and removing the AI feel
Each skill declares its own input contract. For example, the chapter generation skill requires the chapter outline, relevant entity facts, prior summaries, and a style sample as input, and outputs JSON with metadata:
{"chapter": 12,"text": "...prose...","used_facts": ["char_lin.motivation", "place_river.name"],"new_facts": [{"k": "clue", "v": "half of the prescription left by the brother"}],"foreshadow": ["the other half of the prescription is at a pawnshop in town"]}
used_facts and new_facts are the key to closing the pipeline loop. The former is used to check afterward whether the model actually followed the settings; the latter is used to write back to the memory store automatically, with no manual transfer.
6. Orchestration Layer: The Chapter Generation Pipeline
Make single-chapter production a six-step pipeline that falls back and retries whenever a step falls short, instead of generating the whole chapter in one shot:
- Assemble context: pull the chapter outline, retrieve relevant facts and summaries, and attach a 300-character style sample.
- Generate scene cards: first produce the location, present characters, and conflict goal for 3–5 scenes, confirmed by a human or by rules.
- Write scene by scene: generate 800–1200 characters per scene separately to avoid quality collapse in the latter half of a long output.
- Stitch and transition: write the transitions between scenes and unify tense and person.
- Consistency review: check the fact store, timeline, character names, and ability boundaries.
- Style unification: adjust sentence-length distribution, dialogue ratio, and description density to match the sample.
Drive the pipeline with a state file so it can resume after interruption:
def run_chapter(n, state_path="state.json"):state = json.load(open(state_path, encoding="utf-8"))steps = [build_context, make_scene_cards, write_scenes,stitch, continuity_check, polish]for step in steps:if step.__name__ in state.get("done", []):continueresult = step(n, state)state.setdefault("done", []).append(step.__name__)state["last"] = resultjson.dump(state, open(state_path, "w", encoding="utf-8"),ensure_ascii=False, indent=2)return state["last"]
7. Quality Evaluation: Turning “Human Feel” into Metrics
Subjective impressions must be reduced to metrics before you can improve continuously. Maintain a small regression set of 30 fixed tasks (character introductions, foreshadowing payoffs, dialogue conflict, scene transitions, and so on). Run it after every prompt or parameter change and record four metrics:
- Setting adherence: the proportion of
used_factsentries that match spot checks of the actual text. - Conflict rate: the number of contradictory entries flagged in review divided by the number of new facts in the chapter.
- Repetition: the n-gram repetition rate within a chapter and the variance of sentence-pattern distribution.
- Human preference score: a blind test scored 1–5 by at least two people, averaged.
The metrics do not need to hit absolute values; watch the trend. In practice, conflict rate and repetition are most sensitive to prompt structure, while the human preference score is most sensitive to sampling parameters and style samples.
8. Common Problems and Troubleshooting
- Style drift: usually a missing fixed sample in the context or too high a temperature. Fix a 300-character sample and lock the random seed.
- Slow plot progression: insufficient outline granularity, feeding an entire volume to the model. Require scene cards before prose.
- Character contradictions: the fact store was not written back, or updates were overwrite-based. Switch to append-only with conflict flags.
- Generation interruption: long-output timeouts. Lower per-call
max_tokensand split at the scene level. - Insufficient local VRAM: use lower-bit quantization, shorten the context, or hand review tasks to a smaller model.
9. Conclusion
The core of a local novel-writing agent is not any particular model but the engineering skeleton of layered context, structured memory, a fallback-capable pipeline, and measurable evaluation. Models can be swapped and hardware upgraded, but this skeleton determines whether long-form writing converges reliably. Once you have built it following the steps above, you have more than a writing tool: you have a content production pipeline you can keep iterating on. If you want to reduce the operational burden further, you can move the inference service, vector retrieval, and log monitoring to a cloud container platform, object storage, and a logging service, keeping only the writing desk and private materials local.
