Clear, practical technology insights BSOD Code Lookup · Windows Error Code Lookup · Wi-Fi Troubleshooting · PC Troubleshooting Checklist

AI Prompt Template for Accurate Source Code Documentation

Use this reusable prompt to generate docstrings, API notes, examples, exceptions, and complexity analysis while keeping claims tied to the supplied code.

Table of Contents

AI can prepare a useful first draft of source-code documentation, but only when the prompt separates observed behavior from assumptions. A model should not invent validation, exceptions, side effects, thread safety, or performance guarantees that the code does not establish.

The template below works for a function, class, module, or small group of related files. It asks for language-appropriate comments, a behavioral summary, examples, risks, and a verification checklist.

Reusable source-code documentation prompt

You are documenting existing source code for maintainers and API users.

SOURCE LANGUAGE:
[Python / JavaScript / TypeScript / Java / C# / other]

TARGET FORMAT:
[Python docstring / JSDoc / TSDoc / JavaDoc / C# XML comments / Markdown]

AUDIENCE:
[internal maintainers / public SDK users / API consumers / new team members]

CODE AND RELEVANT TYPES:
[PASTE THE CODE, TYPE DEFINITIONS, AND INTERFACES]

KNOWN CONTEXT:
[framework, runtime version, invariants, database behavior, or “not provided”]

TASK:
1. Describe only behavior supported by the supplied code and context.
2. Document each public function, method, class, and parameter.
3. State return type and meaning.
4. List exceptions or rejected inputs that are directly observable.
5. List side effects: files, database writes, network calls, logging, caches, or mutation.
6. Provide one minimal valid example using only APIs shown in the input.
7. Analyze time and space complexity. If database or network operations dominate,
   report their count separately. Mark uncertain complexity as an estimate.
8. Add “Assumptions and unknowns” for anything the code does not establish.
9. Add “Risks noticed” for correctness, security, concurrency, or data-integrity
   concerns. Do not silently rewrite the implementation.
10. Preserve names, types, and behavior. Do not invent configuration, validation,
    dependencies, exceptions, or guarantees.

OUTPUT:
A. Ready-to-paste documentation in the requested format.
B. Behavioral summary.
C. Exceptions and side effects.
D. Complexity.
E. Assumptions and unknowns.
F. Risks noticed.
G. Verification checklist.

If information is missing, write “Not established by the supplied code” and ask a
specific question. Do not fill the gap with a plausible guess.

Choose the format that matches the language

LanguageTypical inline formatGood use
PythonDocstrings in a consistent project styleModules, classes, functions, parameters, returns, and raises
JavaScriptJSDocEditor hints and generated API references
TypeScriptTSDoc or project-standard commentsSemantics not already clear from types
JavaJavaDocPublic packages, classes, methods, and contracts
C#XML documentation commentsIntelliSense and generated .NET API documentation
Any languageMarkdownArchitecture, workflows, operational notes, and examples

C# XML comments are not an appropriate default for Python. Ask for a Python docstring plus Markdown notes when documenting Python code.

Example: documenting a Django order service

Suppose the supplied code is:

from typing import List

from myapp.models import Order, OrderItem, Product


class OrderService:
    def create_order(self, user, items: List[dict]) -> Order:
        order = Order.objects.create(user=user, status="PENDING")
        total_price = 0

        for item in items:
            product = Product.objects.get(id=item["product_id"])

            if product.stock < item["quantity"]:
                raise ValueError("Not enough stock")

            product.stock -= item["quantity"]
            product.save()

            OrderItem.objects.create(
                order=order,
                product=product,
                quantity=item["quantity"],
                price=product.price,
            )
            total_price += product.price * item["quantity"]

        order.total_price = total_price
        order.save()
        return order

Use the template with these settings:

SOURCE LANGUAGE: Python
TARGET FORMAT: Python docstring plus Markdown review notes
AUDIENCE: Internal maintainers
KNOWN CONTEXT: Django models; transaction behavior is not provided

Example ready-to-paste docstring

class OrderService:
    """Creates orders and their line items from product identifiers."""

    def create_order(self, user, items: List[dict]) -> Order:
        """Create an order and decrement stock for each requested product.

        The method creates a PENDING order, retrieves each product by its
        product_id, checks the current stock value, decrements and saves
        that product, and creates an OrderItem using the product's current
        price. It then stores the accumulated total on the order.

        Args:
            user: Value assigned to Order.user. The required concrete type
                is not established by the supplied code.
            items: Dictionaries containing product_id and quantity.
                Input validation beyond direct key access and the stock check
                is not established by the supplied code.

        Returns:
            The saved Order with its total_price set.

        Raises:
            Product.DoesNotExist: If a product identifier is not found.
            KeyError: If an item lacks product_id or quantity.
            ValueError: If a requested quantity exceeds the observed stock.
            DatabaseError: A database operation may raise a Django database
                exception; exact subclasses depend on the backend and failure.

        Side Effects:
            Creates an Order and OrderItem rows and updates Product stock.
            The supplied code does not establish atomic transaction handling
            or concurrent stock protection.
        """

This documentation describes the implementation without claiming that quantities are positive, writes are atomic, or concurrent requests are safe. Those missing guarantees belong in the review notes.

Example behavioral summary

  1. Creates a pending order before validating every item.
  2. Looks up one product for each input dictionary.
  3. Raises an error if the observed stock is smaller than the requested quantity.
  4. Decrements and saves stock before creating the corresponding line item.
  5. Accumulates each product’s current price multiplied by quantity.
  6. Saves the total and returns the order after all items are processed.

Example complexity analysis

For n input items, the Python loop is O(n). The method also performs database work for each item:

  • one initial order insert;
  • one product query per item;
  • one product update per item;
  • one order-item insert per item;
  • one final order update.

That is approximately 3n + 2 database operations for a successful call, although the ORM and database configuration can affect exact queries. Auxiliary Python memory is O(1) beyond the input and ORM objects held for the current iteration.

Complexity should not be reduced to “O(n)” when network or database round trips dominate real performance.

Example risks noticed

  • Partial writes: an error after earlier items may leave an order, decremented stock, or line items unless an outer transaction exists.
  • Concurrent stock updates: two requests may read the same stock before either saves, allowing overselling.
  • Input validation: zero, negative, non-integer, or duplicate quantities are not rejected explicitly.
  • Query volume: retrieving and saving each product separately creates repeated database round trips.
  • Price timing: each line item uses the product price at the moment it is processed; the intended pricing policy is not stated.
  • Empty input: the code appears to create a zero-total order for an empty list.

These are review findings, not implementation facts to hide inside an optimistic docstring. A maintainer should decide whether to add validation, transaction.atomic(), row locking, bulk retrieval, or database constraints.

Prompt variations

Document a public API

In addition to the base template:
- Include authentication and authorization requirements only if supplied.
- Document request and response examples.
- List status codes and error schemas supported by the implementation.
- Mark rate limits, idempotency, and pagination as unknown unless shown.
- Exclude internal implementation details that public consumers do not need.

Document a command-line tool

In addition to the base template:
- Document command syntax, flags, defaults, environment variables, exit codes,
  files read or written, and three realistic examples.
- Verify each option against the parser definition.
- Do not invent installation instructions or platform support.

Document a module for maintainers

In addition to the base template:
- Explain module responsibility, dependencies, data flow, invariants, extension
  points, failure modes, and tests that protect the behavior.
- Separate current architecture from proposed improvements.
- Link every important claim to a symbol, configuration entry, or test.

Update stale documentation

Compare the existing documentation with the supplied implementation and tests.
Return a table with:
- documentation claim;
- supporting code or test;
- status: accurate, incomplete, stale, or not established;
- proposed correction.

Do not rewrite until the discrepancy table is complete.

What context to include

AI documentation improves when the model can see more than one isolated function. Supply only what is necessary, but include:

  • related types and interfaces;
  • public callers or a representative usage test;
  • validation and error definitions;
  • framework and language version;
  • configuration that changes behavior;
  • transaction or concurrency boundaries;
  • existing style rules and documentation examples.

Remove credentials, private data, and unrelated proprietary code. Use an AI service approved for the repository’s confidentiality level.

Verify generated documentation

  1. Compile or lint it. Invalid tags or indentation can break generated reference pages.
  2. Check every name. Parameter, exception, type, and configuration names must match the code.
  3. Run the examples. A plausible example may import the wrong module or omit required setup.
  4. Compare side effects. Look for database writes, file changes, network calls, mutation, logging, and caches.
  5. Trace each exception. Separate explicit raises from exceptions merely possible in dependencies.
  6. Review complexity. Count database and network operations, not only loop nesting.
  7. Check contracts. Do not document behavior that is only a proposed improvement.
  8. Ask a maintainer. The code may not reveal business rules, compatibility promises, or intended use.

Keep documentation maintainable

Put stable interface facts close to the code. Keep architecture, tutorials, deployment procedures, and operational runbooks in versioned external documents. Add documentation checks to code review, and update examples when tests or public behavior change.

The most useful AI-generated documentation is conservative. It tells readers what the code demonstrably does, exposes what is not established, and gives maintainers a short list of questions and risks to resolve.

Discussion

Reader Comments 0

Sign in with email or Google to join the discussion.