TL;DR
Generating accurate code documentation across large repositories is difficult because LLMs often hallucinate dependencies and exceed context windows. DocAgent solves this by establishing a dependency-aware topological ordering—documenting leaf dependencies first—and deploying a collaborative team of specialized agents (Reader, Searcher, Writer, Verifier, and Orchestrator) to incrementally construct documentation. Across diverse Python codebases, DocAgent dramatically improves documentation completeness, helpfulness, and factual truthfulness compared to standard chat and fill-in-the-middle baselines.
What Problem Does This Paper Address?
Code documentation is vital for software maintenance and AI-assisted programming, yet developers rarely write enough of it. An empirical analysis by the authors revealed that in 164 top-starred Python repositories created in 2025, only 27.28% of documentable functions, classes, and methods had docstrings, with over 60% averaging 30 words or fewer.
Existing LLM approaches (such as inline Fill-In-the-Middle tools and conversational chat models) fall short in repository-level documentation. They routinely:
- Omit critical structural components (parameters, return types, exceptions).
- Lack high-level context and design rationale.
- Hallucinate non-existent classes, functions, or external APIs.
These shortcomings stem from three core bottlenecks: isolating relevant context across large codebases, managing deep dependency chains that exceed LLM context windows, and the lack of scalable, multi-faceted evaluation metrics beyond naive n-gram matching (e.g., BLEU, ROUGE).
Methods
DocAgent splits the documentation process into two distinct stages:
-
The Navigator (Dependency DAG & Topological Ordering): Using Abstract Syntax Tree (AST) parsing, the Navigator maps out function/method calls, class inheritance, attribute accesses, and imports across the entire repository into a Directed Acyclic Graph (DAG) (handling dependency cycles with Tarjan's algorithm). It determines a topological traversal order using a "Dependencies First" rule: components are documented only after their dependencies are documented. As a result, documenting any component only requires the newly generated summaries of its direct one-hop dependencies, preventing context-window explosions.
-
Specialized Multi-Agent Generation:
- Reader: Analyzes the target code to determine if internal dependencies, usage call sites, or external domain knowledge are needed, issuing structured XML retrieval requests.
- Searcher: Retrieves internal AST context and queries an external search tool (for recent libraries, algorithms, or concepts), cycling with the Reader until context is sufficient.
- Writer: Synthesizes the retrieved context and code into standard documentation sections (Summary, Args, Returns, Raises, Examples).
- Verifier: Evaluates the draft for quality, detail, and completeness, sending structured feedback back to the Writer (for formatting revisions) or Reader (for missing context).
- Orchestrator: Coordinates the agent loop and applies adaptive context truncation if token limits are approached.
- Multi-Faceted Evaluation Framework:
- Completeness: Deterministic AST and regex checks measuring whether required sections (Args, Returns, Raises, etc.) are present given the code signature.
- Helpfulness: Evaluated via an LLM-as-judge (GPT-4o) using decomposed rubrics, few-shot anchor examples, and chain-of-thought justification on a 1–5 scale.
- Truthfulness (Existence Ratio): An LLM extracts entity mentions from the docstring, which are programmatically verified against the codebase's ground-truth dependency graph: $\frac{|\text{Verified Entities}|}{|\text{Extracted Entities}|}$.
Datasets
- Empirical Study Corpus: 164 recent top-starred GitHub Python repositories (created after Jan 1, 2025, >50 stars, >50 KB).
- Evaluation Benchmark: 9 representative repositories spanning different code sizes and topological complexities, comprising 366 code components (120 functions, 178 methods, 68 classes).
- Ablation Subset: A randomly sampled subset of 50 code components used to evaluate truthfulness under different traversal strategies.
Key Insights and Ideas
- Topological Sorting Eliminates Context Bloat: Inverting the documentation order—documenting leaves and callees before callers—allows LLMs to consume clean, pre-summarized 1-hop dependency descriptions rather than messy, recursive raw source files.
- External Web Retrieval is Necessary for Modern Code: Codebases frequently implement concepts invented after a model's training cutoff (e.g., Direct Preference Optimization [DPO] implemented with a CodeLlama backbone). External search provides the mathematical intuition needed to document these components meaningfully.
- Ground-Truth Verification of LLM Hallucinations: Verifying entity names directly against static AST graphs provides an automated, objective check for repository hallucinations that typical text similarity metrics miss.
Key Results
DocAgent was evaluated using two backbones: GPT-4o mini (DA-GPT) and CodeLlama-34B (DA-CL), against standard Chat baselines and Fill-in-the-Middle CodeLlama-13B (FIM-CL).
- Completeness: DocAgent variants achieved scores of 0.934 (
DA-GPT) and 0.953 (DA-CL), significantly outperforming Chat baselines (0.815 and 0.724) and FIM (0.314). - Helpfulness (1–5 scale):
DA-GPTscored 3.88 overall (with summaries scoring 4.32), well ahead ofChat-GPT(2.95) andFIM-CL(1.51). - Truthfulness (Existence Ratio):
DA-GPTverified repository entities at 95.74%, andDA-CLreached 88.17%. In contrast,Chat-GPThovered at 61.10%, andFIM-CLhit just 45.04% (over half of its mentioned entities were hallucinations). - Ablation on Traversal Order: Replacing topological order with random processing dropped helpfulness (3.88 $\rightarrow$ 3.44) and truthfulness (94.64% $\rightarrow$ 86.75% on
DA-GPT), confirming that incremental context accumulation is vital.
Limitations and Future Work
- Static Analysis Blindspots: The current Navigator relies solely on static AST parsing, missing dynamic Python behaviors such as runtime monkey-patching or reflection.
- Language Scope: The current implementation is tailored specifically to Python codebases.
- Privacy & Proprietary Risks: Outbound external search queries may accidentally leak proprietary identifiers or algorithm details to external search APIs.
- Inference Cost: Multi-agent iterative loops and LLM-as-judge evaluation consume significant computational resources and API tokens compared to single-turn prompting.
Summary updated