Code Documentation Automation with a Multi-Round Review Pipeline
This article describes a practical pipeline for automatically generating code documentation with large language models while controlling API quota and improving accuracy. It breaks the work into structure scanning, module-level generation, cross-review, and aggregation/indexing, then discusses context splitting, file filtering, content-hash caching, and tiered model use. It also covers the diminishing returns of multiple review rounds, quality assurance and human review, key risks, and actionable practices for teams.
1. Background
Many developers hit the same bottleneck when using large language models with code: the quota consumed by a single task is quickly exhausted. A medium-sized project often contains dozens of modules and tens of thousands of lines of code. Handing the entire repository to a model at once both exceeds the context window and causes call costs to rise rapidly.
Another common problem is that a documentation draft produced in one pass may look structurally complete, but its details often do not match the code. Wrong parameter names, missing return value types, and unmentioned exception branches are easy to miss while reading, yet they can directly mislead later users.
Code documentation generation therefore faces two competing goals: controlling call costs and ensuring accuracy. If you pursue one-shot generation alone, it is difficult to satisfy both. A more reasonable approach is to split the task into smaller pieces, with clear inputs, outputs, and review criteria for each step.
2. Core Idea: Turn Documentation Generation into a Pipeline
Treat documentation generation as a pipeline rather than a single conversation. The overall process can be divided into four stages.
2.1 Structure Scanning
This stage does not generate any prose. It only extracts the project skeleton, including the directory structure, module partitioning, public interface list, dependencies, and entry files. The scan can be performed with static analysis tools or simple scripts, producing a structured inventory.
This step has a low cost, but it determines how later tasks are split. The structure inventory also serves as the basis for later review, helping determine whether the documentation covers all public interfaces.
2.2 Module-Level Generation
For each module, submit the module source code together with the relevant information from the structure inventory to the model, and ask it to generate documentation for that module. The context for each module is independent, the input size for each call is controllable, and the model can focus more easily on local logic.
The output format should be explicitly constrained during generation. For example, require five sections: Functionality, Parameters, Return Value, Exceptions, and Usage Example. A uniform format makes later aggregation and review automatable.
2.3 Cross-Review
Review is the key step for improving quality. During review, provide both the source code and the generated documentation to the model, and require an item-by-item comparison rather than a vague question such as “is this correct?”
An actionable review checklist usually includes the following:
- Whether every parameter name, type, and default value listed in the documentation matches the source declaration;
- Whether the return value type and meaning match the actual return paths;
- Whether exceptions and error codes cover the cases explicitly thrown or returned in the source code;
- Whether the example code can run under the current version and whether the calling method is correct;
- Whether the documentation contains functionality descriptions that do not exist in the source code.
Review results should be output in a structured form. For example, each issue can include its location, issue type, and suggested revision, making it easier to write the fixes back into the documentation automatically.
2.4 Aggregation and Indexing
After all module documentation has been generated and reviewed, the process enters the aggregation stage. Aggregation includes generating an overview page, a textual description of the module dependency graph, a unified glossary, and an index organized by module. The aggregation stage can use only the summary section of each module document, thereby reducing input size.
3. Specific Methods for Controlling Quota Consumption
Quota control runs through the entire pipeline and focuses mainly on the following areas.
3.1 Split Context by Module
Do not use the entire repository as context. Each call should provide only the source code of the current module and the interface declarations it directly depends on. Interface declarations usually need only function signatures and type definitions. They are much shorter than full implementations, but sufficient for the model to understand module boundaries.
3.2 Filter Irrelevant Files
Test code, build scripts, generated intermediate files, and third-party dependency directories are usually irrelevant to documentation and should be excluded during preprocessing. Keeping only business source code and necessary configuration files can significantly reduce input size.
3.3 Cache Intermediate Results
If the source code of a module has not changed, its documentation does not need to be regenerated. You can compute a content hash for each module and rerun generation and review only when the hash changes. This mechanism delivers the most obvious benefit in continuously maintained projects, because most commits modify only a few files.
3.4 Tiered Model Use
Not every step requires the strongest model. Structure scanning and format organization can be handled by scripts. Module drafts can be assigned to a lower-cost general-purpose model. The final review of difficult issues can then be handled by a more capable model. With tiering, the overall cost is usually lower than using a high-end model throughout the entire process.
Below is illustrative pipeline code showing how to connect the stages above. call_model is a placeholder function and should be replaced with the call interface of the chosen model in actual use.
from pathlib import Pathimport hashlibdef file_hash(path: Path) -> str:return hashlib.sha256(path.read_bytes()).hexdigest()def generate_doc(source: str, interface_stub: str) -> str:prompt = ("Generate module documentation from the following source code. ""Strictly use five sections: Functionality, Parameters, Return Value, ""Exceptions, and Usage Example.\n\n"f"[Dependency Interfaces]\n{interface_stub}\n\n[Source Code]\n{source}")return call_model(prompt) # Placeholder: replace with actual model calldef review_doc(source: str, doc: str, rounds: int = 2) -> str:for _ in range(rounds):prompt = ("Check the document item by item against the source code: whether ""parameters, return values, exceptions, and examples are consistent ""with the source. Output an issue list where each item contains the ""location, type, and suggested revision; if there are no issues, ""output \"None\".\n\n"f"[Source Code]\n{source}\n\n[Document]\n{doc}")issues = call_model(prompt)if issues.strip() == "None":breakdoc = call_model("Revise the document based on the issue list. Output only the full ""revised document.\n\n"f"[Issues]\n{issues}\n\n[Document]\n{doc}")return docdef build_docs(modules: dict[str, Path], cache: dict[str, str]) -> dict[str, str]:results = {}for name, path in modules.items():h = file_hash(path)if cache.get(name) == h:continue # Source code unchanged; skipsource = path.read_text(encoding="utf-8")doc = generate_doc(source, interface_stub="")results[name] = review_doc(source, doc)cache[name] = hreturn results
This code illustrates three points: the prompts have a fixed format that makes parsing easier; review has a round limit and an early-stop condition; and caching is based on content hashes to avoid repeated consumption.
4. Marginal Returns of Multi-Round Review
Adding more review rounds is a common way to improve quality, but more rounds are not always better. From practical experience, returns usually diminish.
The first review round often finds the most obvious issues, such as misspelled parameter names, missing exception branches, and outdated examples. The second round is mostly used to verify whether the fixes from the first round introduced new problems, such as a revised description conflicting with other sections. Starting from the third round, newly found issues are mostly details of wording and expression, with limited impact on accuracy.
Therefore, it is recommended to set a cap of two to three rounds for each module and stop early when two consecutive rounds find no factual issues. At the same time, keep the issue log for each round so that it is possible to trace later which changes were made by the model on its own and which were confirmed by humans.
5. Quality Assurance and Human Review
An automated pipeline cannot fully replace human review. Model-generated documentation may have three typical types of problems.
The first type is factual errors, where the documentation description is inconsistent with source code behavior. These can be partially detected through source comparison and unit tests, for example, by actually running the example code.
The second type is omission, where the documentation does not cover some public interfaces or important boundary conditions. The interface inventory produced during structure scanning can be used to automatically check coverage.
The third type is unclear expression, such as inconsistent terminology or overly general descriptions. These problems require human reading and judgment, and can also be constrained through a glossary.
It is recommended to retain line-by-line human review for key modules, such as externally exposed core interfaces and code involving security or financial logic. For internal auxiliary modules, sampling review can be used to reduce human cost.
6. Risks to Watch
Information leakage. Source code may contain keys, internal addresses, and undisclosed business details. Before submitting code to a model, scan for sensitive information and redact it, and confirm that the data usage terms of the chosen service meet the team’s compliance requirements.
Licensing and copyright. If the project references third-party code, generated documentation should not copy its copyright notices or implementation details verbatim. Original license information should be retained.
Over-reliance. Model-generated content easily appears fluent and credible, but fluency does not equal correctness. Teams should establish clear responsibility: the final owner of the documentation is still the submitter.
Version drift. Keeping documentation and code in sync is a long-term issue. Caching and hashing can help detect changes, but a documentation check should still be added to continuous integration—for example, warn when source code changes but documentation is not updated.
7. Summary and Practical Recommendations
The following executable recommendations can be drawn for code documentation generation:
- Perform structure scanning before content generation, and use the structure inventory to constrain task scope;
- Generate documentation module by module, providing only the necessary context in each call;
- Use fixed-format prompts and an item-by-item review checklist so that outputs are checkable and parseable;
- Set a round limit for review and use consecutive rounds with no factual issues as the early-stop condition;
- Cache results based on content hashes and reprocess only modules that have changed;
- Select models by task difficulty, reserving high-cost models for difficult steps;
- Retain human review for core modules and redact sensitive information.
With this pipeline, teams can stably produce structurally uniform and traceable code documentation within a limited quota. The process itself is also easy to iterate on: each newly discovered error type can be added to the review checklist, gradually improving the quality of future generations.
