← Back to cookbooks

Intermediate · 3-6 hours

Auto-Generating Documentation with AI

Auto-generate and maintain API docs, READMEs, and technical documentation with AI agents.

Last reviewed Feb 27, 2026

Overview

Documentation is the part of software development that most often gets skipped, left stale, or written poorly. AI agents are changing this by generating, maintaining, and keeping documentation in sync with code automatically. Key tools covered: Mintlify, Claude Code, DocAgent, ReadMe, Fern, GitBook Audience: Developers and technical writers who want accurate, up-to-date documentation without the manual overhead.


DocAgent: Multi-Agent Documentation System

DocAgent is a research system from ACL 2025 that demonstrates what's possible when documentation generation is treated as a multi-agent orchestration problem.

The Five-Agent Architecture

Agent Role
Orchestrator Decomposes repo into documentation tasks, manages dependencies, sequences work
Reader Reads source files, understands code structure, extracts intent
Searcher Retrieves related documentation, examples, and context from the codebase
Writer Generates documentation from code + context + retrieved examples
Verifier Checks generated docs for accuracy, completeness, and factual correctness

Topological Code Processing

DocAgent processes the codebase in dependency order — lower-level utilities are documented before the higher-level modules that use them. This means the Writer agent always has context about what a function's dependencies do when writing docs for that function.

Results

DocAgent achieved a 59% average reduction in documentation time compared to human-only documentation across the ACL 2025 benchmark codebases, with quality scores comparable to expert-written documentation.


Auto-Generating READMEs with AI

A great README is the first thing a new developer sees. AI can generate a professional README in seconds from your codebase.

The Core Prompt

Generate a comprehensive README.md for this project.

Include:
1. Project name + one-line description
2. Badges (build status, coverage, version, license)
3. Table of contents
4. Features list (extract from the codebase)
5. Prerequisites
6. Installation instructions (step by step, tested commands)
7. Configuration (all environment variables with descriptions and defaults)
8. Usage examples (real, working code examples)
9. API reference (all public endpoints or exports)
10. Development setup
11. Testing instructions
12. Deployment guide
13. Contributing guidelines
14. License

Tone: Professional but approachable.
Assume the reader is a developer unfamiliar with this project.

README Template That AI Fills In

# [PROJECT_NAME]

[ONE_LINE_DESCRIPTION]

[![Build](CI_BADGE)] [![Coverage](COVERAGE_BADGE)] [![License](LICENSE_BADGE)]

## What it does
[2-3 sentence explanation of the problem this solves]

## Quick Start
[MINIMAL_WORKING_EXAMPLE]

## Features
- [FEATURE_1]
- [FEATURE_2]

## Installation
[STEP_BY_STEP]

## Configuration
| Variable | Description | Default |
|----------|-------------|--------|
| [VAR] | [DESC] | [DEFAULT] |

## Usage
[EXAMPLES]

## API Reference
[AUTO_GENERATED]

## Contributing
[GUIDELINES]

## License
[LICENSE]

Best Practices for AI-Generated READMEs

  • Always test the installation commands — AI may hallucinate package names or steps
  • Verify code examples run — paste them into a fresh environment
  • Add your project's actual badges — AI uses placeholders
  • Update the contributing section with your real PR process

API Documentation with AI

Generate OpenAPI Specs from Code

Analyze this Express.js router file and generate a complete OpenAPI 3.1 spec.

For each endpoint, extract:
- Method, path, summary, description
- Path parameters, query parameters, request body
- All response codes (200, 400, 401, 404, 500) with schemas
- Authentication requirements
- Rate limiting notes (from comments/middleware)

Output: valid openapi.yaml

Router file:
[PASTE ROUTER CODE]

Auto-Generate API Reference Docs

Using this OpenAPI spec, generate API reference documentation in Markdown format.

For each endpoint include:
- Short description and use case
- Authentication requirements
- Full request example (curl + JavaScript fetch)
- Response examples for success and common errors
- Notes on edge cases or gotchas

Style: Match Stripe's API documentation — clear, example-heavy, developer-friendly.

OpenAPI spec: [PASTE SPEC]

Keeping Docs in Sync with Code Changes

I'm making the following changes to the API:
[PASTE GIT DIFF]

Update the API documentation to reflect these changes:
1. Mark any deprecated endpoints
2. Add documentation for new endpoints
3. Update changed request/response schemas
4. Update the changelog
5. Flag any breaking changes prominently

Existing docs: [PASTE CURRENT DOCS]

Architecture Diagrams with AI

Mermaid diagrams are text-based, version-controlled, and render automatically in GitHub, Notion, and most documentation platforms — making them ideal for AI-generated architecture documentation.

System Architecture Diagram

Generate a Mermaid architecture diagram for this system:
[DESCRIBE YOUR SYSTEM: services, databases, queues, external APIs]

Include:
- All services and their roles
- Data flow between services
- External dependencies
- Database types
- Async vs sync communication (different arrow styles)

Example output:

graph TB
    Client[Web Client] --> CDN[CloudFront CDN]
    Client --> API[API Gateway]
    API --> Auth[Auth Service]
    API --> Orders[Orders Service]
    Orders --> DB[(PostgreSQL)]
    Orders --> Queue[SQS Queue]
    Queue --> Worker[Background Worker]
    Worker --> Email[SendGrid]
    Auth --> Cache[(Redis)]

Sequence Diagram

Generate a Mermaid sequence diagram for the OAuth 2.0 authorization code flow.
Include: browser, your app, auth server, resource server.
Show all redirects, token exchanges, and API calls.

Entity Relationship Diagram

Generate a Mermaid ER diagram from this database schema:
[PASTE CREATE TABLE SQL or Prisma schema]

Include: all tables, primary/foreign keys, relationship cardinalities.

Docs-as-Code Workflows

Docs-as-code means your documentation lives in the same repository as your code, is reviewed in PRs, and is deployed in CI/CD — just like the application itself.

Core Principles

  • Co-location: Docs live next to the code they describe
  • Version control: Every doc change is a commit with author, date, and message
  • Review: Doc PRs go through the same review process as code PRs
  • Automation: CI builds and validates docs on every PR

AI Monitors Code Changes and Suggests Doc Updates

# .github/workflows/docs-check.yml
name: Documentation Check

on:
  pull_request:
    paths:
      - 'src/**'
      - 'api/**'

jobs:
  doc-review:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - name: Check docs are updated
        run: |
          npx @anthropic/claude-code-action \
            --prompt "Review this PR diff. Identify any code changes that
            require documentation updates. List each file that needs updating
            and what should change. If docs are already updated, say so."
        env:
          ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}

The llms.txt Standard

llms.txt is an emerging standard for making documentation AI-discoverable. Place a /llms.txt file at your domain root:

# MyProduct

> One-sentence description of what MyProduct does.

## Documentation

- [API Reference](/docs/api): Complete API reference with examples
- [Quick Start](/docs/quickstart): Get running in 5 minutes
- [Authentication](/docs/auth): OAuth and API key setup
- [Webhooks](/docs/webhooks): Event notifications reference
- [SDKs](/docs/sdks): Official client libraries
- [Changelog](/changelog): What's changed in each version

This allows AI coding assistants to find and use your documentation without web search.


Mintlify: Auto-Pilot Documentation

Mintlify is the leading AI-powered documentation platform, used by Anthropic, Vercel, and Cursor.

Key Features

  • Repo monitoring: Mintlify watches your GitHub repo for code changes
  • Auto PR drafts: When code changes, Mintlify opens a PR to update related docs
  • 1M AI queries/month: Built-in AI assistant that answers questions using your docs
  • OpenAPI sync: Automatically updates API reference when your spec changes
  • Analytics: Shows which docs pages have high bounce rates and unanswered questions

Setup

# Install Mintlify CLI
npm install -g mintlify

# Initialize in your repo
mintlify init

# Preview locally
mintlify dev

mint.json Configuration

{
  "name": "My Product Docs",
  "logo": {
    "dark": "/logo/dark.svg",
    "light": "/logo/light.svg"
  },
  "favicon": "/favicon.svg",
  "colors": {
    "primary": "#0D9373"
  },
  "navigation": [
    {
      "group": "Get Started",
      "pages": ["introduction", "quickstart"]
    },
    {
      "group": "API Reference",
      "pages": ["api-reference/introduction", "api-reference/authentication"]
    }
  ],
  "api": {
    "baseUrl": "https://api.myproduct.com",
    "auth": {
      "method": "bearer"
    }
  }
}

Platform Comparison

Feature Mintlify ReadMe Fern GitBook
MCP server support Yes No Yes No
SDK generation No No Yes (7 languages) No
Auto-sync with repo Yes Partial Yes Yes
AI writing assistant Yes (1M queries/mo) Yes Limited Yes
OpenAPI import Yes Yes Yes (primary input) Yes
Versioning Yes Yes Yes Yes
Analytics Yes Yes No Yes
Pricing (base) $150/mo $99/mo $250/mo $6.7/user/mo
Best for Developer docs, API docs API docs + changelog SDK generation Internal + external docs

When to Choose Each

  • Mintlify: Best overall for developer-facing documentation. Strong AI features, clean UX.
  • ReadMe: Best when you need a changelog and community forum alongside API docs.
  • Fern: Best when SDK generation is the primary goal — generates SDKs in 7 languages from your OpenAPI spec.
  • GitBook: Best for internal knowledge bases and teams that want a Notion-like writing experience.

Keeping Docs in Sync

The Core Pattern

"Whenever I make a commit, have the agent write documentation for AI agents." This pattern treats documentation as a first-class output of every commit — not a post-shipping task.

Document the 'Why' Not Just the 'How'

AI is good at documenting what code does. It needs human input for why:

Document this function. Include:
1. What it does (you can generate this)
2. Why it exists — business context: [EXPLAIN BUSINESS REASON]
3. Why we chose this approach over alternatives: [EXPLAIN TRADEOFF]
4. Known limitations or future improvements planned: [EXPLAIN]

AI-Maintained Changelogs

Generate a user-facing changelog entry for this PR.

PR title: [TITLE]
PR description: [DESCRIPTION]
Diff summary: [PASTE KEY CHANGES]

Changelog entry should:
- Be written for end users, not developers
- Group changes as: New Features / Improvements / Bug Fixes / Breaking Changes
- Explain impact, not implementation
- Flag breaking changes prominently with migration steps

Automated Freshness Checks

# Run weekly to find stale documentation
npx @anthropic/claude-code-action \
  --prompt "Compare these documentation files against the current source code.
  Identify any docs that describe behavior that no longer exists or has changed.
  Output: list of stale docs with specific outdated claims."

Prompt Library for Documentation

1. README Generation

Generate a comprehensive README.md for this [LANGUAGE] project.
Purpose: [ONE SENTENCE]
Key features: [LIST]
Target audience: [DESCRIBE]

Include: installation, configuration (all env vars), usage examples,
API reference, contributing guide, license.
Test every command before including it.

2. API Reference Generation

Generate API reference documentation for this [REST/GraphQL/gRPC] API.
Style guide: [Stripe/Twilio/None — match their style]

For each endpoint:
- Description, authentication, parameters
- Request example (curl + language SDK)
- Response example (success + common errors)
- Rate limits if applicable

3. Architecture Diagram Generation

Generate a Mermaid [flowchart/sequence/ER] diagram for:
[DESCRIBE SYSTEM/FLOW/SCHEMA]

Include: [LIST COMPONENTS TO SHOW]
Direction: [TB/LR]
Style: group related services in subgraphs

4. Changelog Writing

Write a user-facing changelog entry for version [VERSION].
Changes: [LIST OR DIFF]

Format: [KEEP.A.CHANGELOG / GitHub Releases / custom]
Audience: [Developers / End users / Both]
Highlight: [any breaking changes or migration required]

5. Tutorial / Guide Creation

Write a step-by-step tutorial for [TASK].
Audience: [DEVELOPER EXPERIENCE LEVEL]
Goal: reader can [SPECIFIC OUTCOME] by the end.

Include: prerequisites, numbered steps, working code at each step,
common errors and how to fix them, next steps section.
Test every code snippet.

6. Inline Code Documentation

Add JSDoc/docstring documentation to all public functions and classes in this file.

For each:
- One-line description
- @param with type and description
- @returns with type and description
- @throws for known exceptions
- @example with a working code example

Do not document private/internal functions.
File: [PASTE CODE]

Common Pitfalls

Generating docs once and never updating — Stale documentation is often worse than no documentation. Set up automated freshness checks and Mintlify auto-sync from the start. Not reviewing AI-generated docs for accuracy — AI confidently documents code incorrectly, especially for complex business logic. Every generated doc needs human review before publishing. Missing the 'why' (business context) — AI can generate the 'what' and 'how' from code alone. It cannot generate the 'why' — the business reason, the historical decision, the tradeoff made. Always add context that only humans know. Not making docs discoverable for AI tools — If your docs aren't findable by AI coding assistants, developers using Cursor, Claude Code, or Copilot won't benefit from them. Implement llms.txt and consider an MCP server for your documentation.


Further Reading