Skip to main content

Generating Documentation with AI Agents

1. Generating Function Docstrings

Property Description Example
function Name of the function to document calculateTotal
parameters List of input parameters with types and descriptions { price: number, quantity: number }
returns Type and description of return value number
description Overview of function purpose and usage Calculates total cost including tax

Example: Docstring Generation

/**
 * Calculates total cost including tax.
 * @param {Object} params - Input parameters
 * @param {number} params.price - Price per unit
 * @param {number} params.quantity - Number of units
 * @returns {number} Total cost including tax
 */
function calculateTotal({ price, quantity }) {
  const taxRate = 0.08;
  return (price * quantity) * (1 + taxRate);
}
Note: AI agents can generate docstrings based on function signatures and logic, reducing manual documentation effort.

2. Generating README Files

Feature Description Usage
ai.agent AI agent responsible for generating README content "llm-readme-generator"
template.type Template style for README generation "standard", "minimal"
output.path Output file path for generated README "./README.md"

Example: README Generation Configuration

{
  "ai": {
    "agent": "llm-readme-generator",
    "template": {
      "type": "standard"
    }
  },
  "output": {
    "path": "./README.md"
  }
}
Note: The AI agent will analyze project structure and dependencies to generate a relevant README.
Warning: Ensure that the project's package.json or pyproject.toml is properly configured for accurate content generation.
Template Type Description Features
standard Full-featured README with sections like Installation, Usage, Contributing Installation, Usage, API, Contributing, License
minimal Basic README with only essential sections Project Name, Description, Installation

README Generation Workflow

  • Scan project root for configuration files (e.g., package.json, pyproject.toml)
  • Detect project type (Node.js, Python, etc.)
  • Generate content based on detected configuration and codebase structure
  • Write to README.md or specified output path

3. Generating API Documentation

Feature Description Usage Notes
auto-doc generation Automatically generates API documentation from code comments ai-docs --generate Supports multiple languages including JavaScript, Python, and Java
doc format Output formats for documentation markdown, html, rst Defaults to markdown for easy integration with documentation sites
comment parsing How comments are interpreted for documentation jsdoc, pydoc, doxygen Supports standard comment formats for each language

Example: Generating API Docs from JSDoc Comments

/**
 * Calculates the area of a rectangle.
 * @param {number} width - The width of the rectangle
 * @param {number} height - The height of the rectangle
 * @returns {number} The area of the rectangle
 */
function calculateArea(width, height) {
  return width * height;
}

Example: Output Markdown Documentation

# calculateArea

Calculates the area of a rectangle.

## Parameters

- **width** (number) - The width of the rectangle
- **height** (number) - The height of the rectangle

## Returns

- (number) - The area of the rectangle
Note: AI agents can parse and generate documentation from code comments, reducing manual effort in maintaining API docs.

4. Generating Architecture Diagrams from Code

Example: Generating a Class Diagram with PlantUML

plantuml -t png -o ./diagrams ./src/MyClass.java
Feature Description Support
Class Diagrams Visual representation of classes and their relationships Good
Sequence Diagrams Shows interactions between objects over time Good
Component Diagrams Displays components and their dependencies Modern
Note: Requires PlantUML or similar UML tools to process code and generate diagrams.

Comparison: AI vs Manual Diagram Generation

  • AI Tools: Faster, less prone to human error, can auto-generate from code
  • Manual: More control over design, better for complex or custom diagrams

5. Keeping Documentation in Sync with Code

Approach Description Tools/Features Notes
Docstring Generation Automatically generate docstrings from code comments or function signatures autoDoc, docstring-generator Requires code parsing and semantic understanding
Inline Documentation Embed documentation directly in code using annotations or comments @doc, /** */ Improves readability and maintainability
API Documentation Sync Automatically update API docs when code changes are made Swagger, OpenAPI Ensures consistency between code and API specs
Version Control Integration Trigger documentation updates on code commits or PRs GitHub Actions, GitLab CI Enables continuous documentation updates

Example: Using GitHub Actions to Sync Docs

name: Update Docs on Code Change
on:
  push:
    branches:
      - main
jobs:
  update-docs:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2
      - name: Generate docs
        run: |
          npm run generate-docs
      - name: Commit and push changes
        run: |
          git config --local user.email "bot@example.com"
          git config --local user.name "AI Bot"
          git add .
          git commit -m "Update docs from code changes" || echo "No changes to commit"
          git push
Note: Ensure that documentation generation tools are configured to handle code changes without breaking existing docs.
Warning: Manual documentation updates can quickly become outdated if not tied to code changes.

6. Generating Changelog Entries

Field Description Example
type Category of change (feat, fix, docs, style, refactor, test, chore) feat
scope Module or component affected auth
description Concise summary of the change Add login endpoint
breaking Indicates if change breaks existing functionality true
issue Related issue number or link #123

Example: Changelog Entry Format

feat(auth): Add login endpoint

- New POST /login endpoint with JWT token generation
- Includes validation for email and password fields
- Returns 200 OK on successful login

Fixes #123

Example: Breaking Change Entry

refactor(api): Rename user endpoints

- /user/profile renamed to /profile
- /user/settings renamed to /settings
- Breaking change for existing clients

Closes #456
Note: AI agents can automatically detect changes from commit messages or PR descriptions and format them into standardized changelog entries.

7. Translating Documentation with AI

Feature Description Usage
AI-powered translation Automatically translates documentation into multiple languages using AI models translate(documentation, targetLanguage)
Context preservation Maintains technical context and terminology accuracy during translation Ensures domain-specific terms are translated correctly
Localization support Supports cultural and regional adaptations (e.g., date formats, units) translateWithLocale(documentation, locale)

Example: Translating Documentation

const translated = translate(
  "The AI agent can generate code from natural language descriptions.",
  "es"
);
console.log(translated); // "El agente de IA puede generar código a partir de descripciones en lenguaje natural."
Note: Translation quality depends on the AI model's training data and language pair support.
Warning: Manual review is recommended for technical documentation to ensure accuracy.
Language Support Status Notes
English NEW Supported Primary source language
Spanish NEW Supported High accuracy translation
French DEPRECATED Legacy support Translation may be outdated

8. Summarizing Legacy Code for Documentation

Code Element Description AI Agent Approach Output Format
Function/Method Legacy function or method with unclear purpose Parse code to identify input/output, side effects Summary in plain text with key parameters
Class Legacy class with undocumented methods Map inheritance, identify public API List of methods with brief descriptions
Module/Package Large module with unclear structure Break down into logical components Component hierarchy with purpose

Example: Summarizing a Legacy Function

function processUserData(data, options) {
  const result = [];
  for (let i = 0; i < data.length; i++) {
    const item = data[i];
    if (item.active && item.email) {
      const processed = {
        id: item.id,
        name: item.name,
        email: item.email.toLowerCase(),
        lastLogin: new Date().toISOString()
      };
      result.push(processed);
    }
  }
  return result;
}
Summary:
- Function processes user data.
- Filters for active users with email.
- Returns array of processed user objects.
- Each object includes ID, name, lowercase email, and last login timestamp.
Note: AI agents can extract and summarize code logic even when documentation is missing or outdated.
Warning: Ensure that AI-generated summaries do not inadvertently expose sensitive data or business logic.

Was this article helpful?