Engineering Long-Context Writing Agents: Practices and Cost Optimization

    Long-form content generation with large language models often fails not because of weak single-inference capability, but because of missing engineering across the full pipeline—from style modeling and task orchestration to long-document state management, cache optimization, and quality evaluation. This article outlines a layered architecture for writing agents, drawn from a real case that produced an ~800,000-character novel draft consuming ~50 million tokens with an 85% cache hit rate. It covers the five key engineering challenges, a six-layer reference architecture, style profiling, skill orchestration, long-context state management, cache and cost optimization strategies, and a quality evaluation framework combining automated checks with human review.

    1. Restating the Problem: The Hard Part Is Usually the Long-Pipeline Writing Engineering, Not the Model

    When teams apply large language models to generate long novels, technical documentation, or branded content, the common first reaction is “the model isn’t good enough”: impressive openings, drifting middles, tangled character relationships in later chapters; inconsistent style; costs that scale rapidly with length; and unpredictable manual rework. But if you break the problem down, single-inference capability is only one link in the chain. What actually determines the experience is the complete engineering pipeline: material collection, style modeling, task orchestration, long-document state management, and quality evaluation.

    The original practice scenario can be abstracted as follows: integrate a large model into a general-purpose intelligent coding tool, analyze the logic of existing writing skill modules, and build new skills for web novel generation; then import years of personal public Q&A posts and articles into a local knowledge base so the model learns the reply characteristics; finally, generate an ~800,000-character novel draft, consuming roughly 50 million tokens in total, about 85% of which came from cache hits. This case shows that long-form generation is not something you accomplish by “writing one prompt”—it requires decomposing writing into reusable, observable, and optimizable capability units.

    2. Key Challenges: Five Engineering Difficulties in Long-Form Writing Agents

    2.1 Style Consistency Cannot Be Maintained by a Single Prompt

    Style is not simply a “lively tone” or “serious register.” It consists of quantifiable features: sentence length distribution, paragraph rhythm, narrative point of view, preferred rhetorical devices, dialogue density, and the pacing of information release. If you only write a few style descriptions into the system prompt, the model gradually regresses to generic expression as the context rolls forward. A more robust approach is to first build a “style profile,” then split it into stable constraints and dynamic examples: stable constraints go into the system-level prefix, while dynamic examples are injected per chapter task.

    2.2 Skill Modules Need Orchestration, Not Stacking

    The writing process naturally includes outline planning, character state maintenance, scene expansion, dialogue generation, consistency checking, and style revision. Cramming all requirements into a single prompt makes the model drop balls; relying entirely on manual step-by-step operation is inefficient. The solution is to abstract writing capabilities into skill modules, each with defined inputs, outputs, constraints, and failure fallback strategies, invoked by an orchestration layer via task cards.

    2.3 Long-Context Management Cannot Rely on “Stuffing the Window”

    800,000 characters far exceed a single context window. A common mistake is letting the running summary grow ever longer, which still loses key settings. A more effective approach is maintaining layered state: a global settings table, a character relationship table, rolling chapter summaries, the current scene task card, and a forbidden-list. Each generation injects only the state relevant to the current chapter, not the full history.

    2.4 Cache Hit Rate Determines the Cost-Effectiveness of Long-Form Generation

    Long-form generation involves massive repeated prefixes: system instructions, style constraints, worldbuilding settings, character cards, and writing standards. Recomputing this stable content on every request significantly increases cost. Through stable prefixes, layered caching, and batching, you can raise the cache hit rate. The 85% cache hit in the case study was no accident—it was the result of separating “stable content” from “dynamic tasks.”

    2.5 Quality Evaluation Must Combine Automation with Human Spot-Checks

    Long-form generation can’t be judged only by whether a single chapter reads smoothly. You must also check for character breakdown, setting conflicts, pacing drag, and style drift. Build automated checks plus a human spot-check set: automation handles high-frequency hard constraints, while human review covers aesthetic and narrative quality. Together they form an iterative closed loop.

    3. Reference Architecture: A Layered Pipeline from Materials to Final Draft

    The system should be split into six layers:

    1. Materials and knowledge layer: stores historical texts, setting documents, character cards, chapter outlines, and the forbidden-list. Materials must be cleaned, deduplicated, and sanitized, with source and version information preserved.
    2. Style profile layer: extracts statistical features, structural features, language preferences, and banned expressions from historical texts, producing a profile file that can be injected into prompts.
    3. Skill orchestration layer: defines skill modules such as outline generation, chapter drafting, consistency checking, and style revision, along with their dependency relationships.
    4. Generation execution layer: assembles prompts, calls the model, handles retries, and records token consumption and cache hits.
    5. Quality and review layer: runs rule checks, model-based review, and human spot-checks, producing revision suggestions.
    6. Observability and cost layer: logs input length, output length, cache hits, latency, and failure reasons for every call, forming a cost dashboard.

    When deploying in the cloud, you can route material archiving, generation logs, and metrics to general-purpose object storage, logging services, and monitoring/alerting capabilities—for example, the general categories offered by Baidu AI Cloud—but the approach described here does not depend on any specific vendor’s APIs.

    4. Style Profiling: Decomposing “Who It Sounds Like” into Executable Features

    A style profile should include at least four categories of information:

    • Statistical features: average sentence length, paragraph length, dialogue ratio, first-person vs. third-person ratio, punctuation rhythm.
    • Structural features: opening style, where conflicts appear, chapter-ending hook types, scene-switch frequency.
    • Language preferences: high-frequency verbs, metaphor density, degree of colloquialism, description-to-narration ratio.
    • Forbidden list: clichés to avoid, excessive sentimentality, specific verbal tics, expressions that conflict with the setting.

    When building the profile, don’t dump large volumes of original text into the prompt. Cluster, summarize, and sample first. Place the stable profile in the system-level prefix, and select example passages dynamically by chapter type. This preserves style while improving cache reuse.

    5. Skill Orchestration: Defining Reusable Writing Capabilities in Pseudocode

    Writing skill modules should have explicit contracts. Here is a pseudocode sketch:

    1. writing_ability:
    2. name: chapter_draft
    3. inputs:
    4. - global_setting
    5. - character_state
    6. - chapter_task_card
    7. - style_profile
    8. - rolling_summary
    9. - forbidden_list
    10. steps:
    11. - validate_inputs
    12. - build_stable_prefix(global_setting, style_profile, forbidden_list)
    13. - build_dynamic_context(character_state, chapter_task_card, rolling_summary)
    14. - call_model_with_cache_prefix()
    15. - run_consistency_check()
    16. - if conflict: repair_and_regenerate()
    17. - style_rewrite_if_needed()
    18. outputs:
    19. - chapter_text
    20. - new_rolling_summary
    21. - state_patch
    22. - quality_report

    The key points: separate the stable prefix from the dynamic context; after each generation, output a state patch and a rolling summary; when a consistency check fails, regenerate only the conflicting passages rather than rewriting the entire chapter.

    6. The Long-Form Generation Workflow: Outlines, Task Cards, Rolling Summaries, and State Tables

    The recommended workflow:

    1. Global outline: first generate volume-level and chapter-level outlines, clarifying the main plotline, subplots, key turning points, and chapter goals.
    2. Chapter task card: before each chapter, create a task card covering the chapter’s goals, featured characters, conflicts, information increments, and ending hook.
    3. State injection: inject the character relationship table, current timeline, unresolved foreshadowing, and forbidden contradictions.
    4. Segmented generation: generate scene by scene to avoid pacing loss from overly long single outputs.
    5. Consistency check: verify character names, ability settings, timeline, geographic relationships, and foreshadowing status.
    6. Rolling summary: after each chapter, generate a summary and state patch for use by subsequent chapters.
    7. Human spot-checks: sample chapters at a set ratio, record issue types, and feed them back into the forbidden list or skill rules.

    The ~800,000-character draft in the case study demonstrates that this workflow can support large-scale content production—provided the state tables and rolling summaries are continuously maintained. Otherwise, quality degrades rapidly in later chapters.

    7. Caching and Cost Optimization: The Stable Prefix Is Core

    Long-form generation cost is determined jointly by input tokens, output tokens, cache hits, and retry counts. The optimization principle: stable content goes first and never changes; dynamic content goes last and stays lean; failed retries stay local. Specific measures include:

    • Fix system instructions, style profile, global settings, and the forbidden list as the stable prefix.
    • Treat chapter task cards, rolling summaries, and character state as dynamic context with controlled length.
    • Reuse prefix caching across multiple revisions of the same chapter.
    • Track cache hit rate, average input length, retry rate, and per-chapter cost.
    • Analyze low-hit-rate tasks; the cause is usually timestamps, random ordering, or frequently changing fields mixed into the prefix.

    In the practice case, ~50 million tokens consumed with an 85% cache hit rate shows that long-form generation is not necessarily expensive—the key is whether the engineering organizes reusable content well.

    8. Quality Evaluation: Automated Checks and Human Spot-Checks Together

    Automated checks cover hard constraints: wrong character names, setting conflicts, chapter word count targets, banned words, and missed foreshadowing. Model-based review covers soft quality: pacing, dialogue naturalness, scene impact. Human spot-checks build a small, high-quality regression set—rerun it after every skill or prompt adjustment to avoid “fix one thing, break another.”

    9. Implementation Checklist

    • Do material cleaning and style profiling before attempting long-form generation.
    • Break writing into skill modules with defined inputs, outputs, and failure fallbacks.
    • Separate stable prefixes from dynamic context; prioritize raising cache hits.
    • Maintain the global settings table, character state table, and rolling summaries.
    • Establish three quality gates: automated checks, model review, and human spot-checks.
    • Use a cost dashboard to continuously monitor token consumption, cache hits, and retry rates.

    10. Conclusion

    The feeling that “the model is hard to use” usually stems from a missing long-pipeline writing engineering effort: no style profile, no skill orchestration, no long-document state management, no cache optimization, no evaluation loop. Treat the LLM writing agent as an engineering system rather than a single-prompt trick, and you can move 800,000-character-scale content generation from “occasionally usable” to “reliably deliverable.” General cloud environments such as Baidu AI Cloud can carry the foundational capabilities—material archiving, logging, and monitoring—but the real differentiation comes from the design and continuous iteration of the writing workflow itself.