How to beginner · 3 min read

How to use AI to write documentation

Quick answer
Use an LLM like gpt-4o via the OpenAI API to generate documentation by providing clear prompts describing the code or feature. Automate this by sending code snippets or feature descriptions as input and receive structured documentation text in response.

PREREQUISITES

  • Python 3.8+
  • OpenAI API key (free tier works)
  • pip install openai>=1.0

Setup

Install the OpenAI Python SDK and set your API key as an environment variable to authenticate requests.

bash
pip install openai>=1.0

Step by step

Use the OpenAI gpt-4o model to generate documentation by sending a prompt describing your code or feature. The model returns a clear, formatted explanation suitable for docs.

python
import os
from openai import OpenAI

client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])

code_snippet = '''
def add(a, b):
    """Add two numbers and return the result."""
    return a + b
'''

prompt = f"""Write clear documentation for the following Python function:\n{code_snippet}"""

response = client.chat.completions.create(
    model="gpt-4o",
    messages=[{"role": "user", "content": prompt}]
)
documentation = response.choices[0].message.content
print(documentation)
output
Adds two numbers and returns their sum.

Parameters:
- a (int or float): The first number.
- b (int or float): The second number.

Returns:
- int or float: The sum of a and b.

Common variations

You can use different models like claude-3-5-sonnet-20241022 for more detailed explanations or switch to async calls for integration in web apps. Streaming responses allow real-time doc generation.

python
import os
import anthropic

client = anthropic.Anthropic(api_key=os.environ["ANTHROPIC_API_KEY"])

code_snippet = '''
def multiply(x, y):
    """Multiply two numbers."""
    return x * y
'''

prompt = f"Write detailed documentation for this function:\n{code_snippet}"

message = client.messages.create(
    model="claude-3-5-sonnet-20241022",
    max_tokens=512,
    system="You are a helpful assistant.",
    messages=[{"role": "user", "content": prompt}]
)
print(message.content[0].text)
output
Multiplies two numbers and returns the product.

Parameters:
- x (int or float): The first number.
- y (int or float): The second number.

Returns:
- int or float: The product of x and y.

Troubleshooting

If the generated documentation is too vague or off-topic, refine your prompt to be more specific or include examples. Ensure your API key is valid and environment variables are set correctly to avoid authentication errors.

Key Takeaways

  • Use clear, descriptive prompts to get precise documentation from AI models.
  • Automate documentation generation by integrating AI calls in your development workflow.
  • Choose models like gpt-4o or claude-3-5-sonnet-20241022 based on your detail and style needs.
Verified 2026-04 · gpt-4o, claude-3-5-sonnet-20241022
Verify ↗