Automating Documentation: Using Python and Claude API to Clean Up Tech Debt

Artificial Intelligence tutorial - IT technology blog
Artificial Intelligence tutorial - IT technology blog

The Fear Called “Documentation”

You’ve just finished 500 lines of complex logic, and every feature runs smoothly. But when you look back at a bunch of empty functions without a single line of comments, a sense of dread sets in. Writing documentation is often seen as a boring “side task.” However, if you return to modify code after 3 months or hand it over to a colleague without documentation, the price will be hours spent re-reading every line of old logic.

Good documentation skills are often the boundary between a professional Senior and a coder who just finishes tasks. Instead of manually typing every args or returns parameter, why not let AI handle these repetitive tasks?

Overview of Current Documentation Methods

Before diving into the code, let’s look at how developers typically maintain documentation.

1. Manual Writing

This is the most traditional way. You manually type docstrings for each function and update the README.md. This ensures high accuracy but is extremely time-consuming. In Sprints, this is usually the first part to be skipped, resulting in accumulating “technical debt.”

2. Static Documentation Tools (Sphinx, Swagger)

These tools scan code and extract existing comments to generate documentation websites. The advantage is high consistency. However, the fatal flaw is that they only present what you’ve already written. If you’re lazy about writing comments from the start, Sphinx or Swagger can’t help you explain the code logic.

3. AI Applications (Claude API, OpenAI API)

This is currently the most optimal direction. AI doesn’t just read code; it understands the developer’s intent. It can re-explain logic in natural language, write installation guides based on imported libraries, and even suggest practical usage examples.

Why Claude 3.5 Sonnet is the Top Choice for Code?

After real-world testing on complex Python projects, I prefer the Claude API for three specific reasons:

  • Strong logical reasoning: Claude 3.5 Sonnet experiences fewer “hallucinations” when explaining nested logic structures.
  • Huge Context Window: With the ability to process up to 200,000 tokens, you can feed in entire modules consisting of multiple files so the AI understands the big picture.
  • Professional technical tone: The output is usually concise, focused, and adheres well to standards like Google Style or Numpy Style.

Building an Auto Documentation Tool

We will write a small Python script to automatically scan code files, then use the Claude API to add docstrings and create a README file.

Step 1: Environment Setup

You need to get an API Key at the Anthropic Console. Then, install the official library:

pip install anthropic python-dotenv

Step 2: Reading Source Code with Pathlib

Using pathlib will help your script run smoothly on both Windows and Linux.

import os
from pathlib import Path
from anthropic import Anthropic
from dotenv import load_dotenv

load_dotenv()
client = Anthropic(api_key=os.getenv("ANTHROPIC_API_KEY"))

def read_source_code(file_path):
    path = Path(file_path)
    return path.read_text(encoding="utf-8")

Step 3: Optimal Prompt Structure

To prevent the AI from rambling, the prompt needs to be strictly designed. Don’t just ask it to “write documentation”; set specific constraints.

def generate_documentation(code_content):
    prompt = f"""
    You are a senior software engineer. Please analyze the following source code:
    
    {code_content}
    
    Requirements:
    1. Add standard Google Style docstrings to all classes and functions.
    2. Clearly explain input parameters and return values.
    3. Keep the code logic intact, only add comments.
    4. Return the complete code block format.
    """
    
    response = client.messages.create(
        model="claude-3-5-sonnet-20240620",
        max_tokens=4000,
        messages=[{"role": "user", "content": prompt}]
    )
    return response.content[0].text

Step 4: Execution and Saving Results

The script will write the AI-refined content into a new file for easy comparison.

def main():
    target_file = "core_logic.py"
    print(f"[*] Analyzing: {target_file}")
    
    raw_code = read_source_code(target_file)
    documented_code = generate_documentation(raw_code)
    
    output_path = Path(f"documented_{target_file}")
    output_path.write_text(documented_code, encoding="utf-8")
    
    print(f"[+] Success! Documentation is ready at {output_path}")

if __name__ == "__main__":
    main()

Evaluating Real-world Effectiveness

After applying this workflow to an internal project with about 50 functions, I noticed significant changes.

Key Advantages

  • Time savings: A task that used to take 2 hours a week now takes less than 2 minutes.
  • Consistency: All docstrings in the project follow a single format, making lookups extremely easy.
  • Onboarding Support: New members can immediately understand the purpose of complex functions without bothering the original author.

Security and Cost Considerations

  • Data Control: Avoid sending files containing Secret Keys or customer information to the API. Use environment variables to filter out sensitive data first.
  • Review is Mandatory: AI sometimes misunderstands specific business logic. You must always double-check before merging into the main branch.
  • Cost: With Claude 3.5 Sonnet, the cost to process 1,000 lines of code is only a few cents, which is very cheap compared to the value of the time saved.

Conclusion

Building an Auto Documentation tool is not difficult; the biggest barrier is changing the work mindset. When you view documentation as part of the automation process rather than a burden, the quality of your product will rise to a new level.

If you are managing an open-source repo or working in an Agile team, try integrating this script into your CI/CD. Your colleagues will surely be surprised by the meticulousness and professionalism in every line of your code!

Share: