Documentation Best Practices with AI
AI can significantly accelerate documentation creation while maintaining quality. This guide covers best practices for AI-assisted documentation.
When to Use AI for Documentation
✅ Excellent Use Cases
- API documentation generation
- README file creation
- Code comment generation
- Tutorial and guide writing
- Migration guide creation
- Changelog generation
⚠️ Use with Review
- Architecture documentation (needs validation)
- User-facing documentation (needs UX review)
- Legal or compliance docs (needs expert review)
- Marketing content (needs brand alignment)
Documentation Types
1. API Documentation
Generate comprehensive API docs from code:
typescript
async function generateAPIDoc(code: string): Promise<string> {
const prompt = `
Generate comprehensive API documentation for this code.
**Include:**
- Function/method description
- Parameters (name, type, description, required/optional)
- Return value (type and description)
- Exceptions/errors that may be thrown
- Usage examples (2-3 realistic examples)
- Notes about edge cases or important behaviors
**Format:** Markdown with code blocks
Code:
${code}
`;
const response = await llm.complete({
model: 'claude-3-5-sonnet-20241022',
messages: [{ role: 'user', content: prompt }],
});
return response.content;
}Example output structure:
markdown
## `functionName(param1, param2)`
Brief description of what the function does.
### Parameters
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| param1 | string | Yes | Description |
| param2 | number | No | Description (default: 0) |
### Returns
`Promise<ResultType>` - Description of return value
### Throws
- `ValidationError` - When parameters are invalid
- `NetworkError` - When API call fails
### Examples
```typescript
// Example 1: Basic usage
const result = await functionName('value', 42);
// Example 2: With error handling
try {
const result = await functionName('value');
} catch (error) {
console.error('Failed:', error);
}Notes
- Important behavior to note
- Performance considerations
### 2. README Generation
Create comprehensive README files:
```typescript
interface ProjectInfo {
name: string;
description: string;
techStack: string[];
features: string[];
repository: string;
}
async function generateREADME(info: ProjectInfo): Promise<string> {
const prompt = `
Generate a professional README.md for this project.
**Project Details:**
- Name: ${info.name}
- Description: ${info.description}
- Tech Stack: ${info.techStack.join(', ')}
- Key Features: ${info.features.join(', ')}
**Include these sections:**
1. Project title and badges
2. Description
3. Features
4. Installation
5. Usage with examples
6. Configuration
7. API documentation (if applicable)
8. Contributing guidelines
9. License
10. Contact/Support
Make it professional, clear, and beginner-friendly.
`;
const response = await llm.complete({
model: 'claude-3-5-sonnet-20241022',
messages: [{ role: 'user', content: prompt }],
});
return response.content;
}3. Code Comments
Generate meaningful code comments:
typescript
async function generateComments(code: string): Promise<string> {
const prompt = `
Add comprehensive JSDoc comments to this code.
**Guidelines:**
- Explain the "why", not just the "what"
- Document complex logic
- Include @param, @returns, @throws tags
- Add usage examples for public APIs
- Keep comments concise but informative
Code:
${code}
`;
const response = await llm.complete({
model: 'claude-3-5-sonnet-20241022',
messages: [{ role: 'user', content: prompt }],
});
return response.content;
}4. Tutorial Creation
Generate step-by-step tutorials:
typescript
async function generateTutorial(topic: string, audience: string): Promise<string> {
const prompt = `
Create a comprehensive tutorial on: ${topic}
**Target Audience:** ${audience}
**Structure:**
1. Introduction
- What you'll learn
- Prerequisites
2. Step-by-step guide
- Clear, numbered steps
- Code examples
- Explanations
3. Common issues and solutions
4. Next steps
Use a friendly, educational tone. Include realistic code examples.
`;
const response = await llm.complete({
model: 'claude-3-5-sonnet-20241022',
messages: [{ role: 'user', content: prompt }],
});
return response.content;
}Best Practices
1. Provide Context
Give AI sufficient context:
typescript
const prompt = `
Generate documentation for this authentication module.
**Context:**
- Part of a larger e-commerce platform
- Users: Backend developers
- Authentication method: JWT tokens
- Related: UserService, TokenService
**Requirements:**
- Enterprise-grade documentation
- Include security considerations
- Provide migration guide from v1
Code:
${code}
`;2. Specify Format and Style
Be explicit about format:
Generate API documentation in OpenAPI 3.0 format.
**Style requirements:**
- Use sentence case for headings
- Include realistic examples
- Add "Deprecated" sections where applicable
- Follow our API documentation standards (attached)3. Include Examples
AI generates better docs with example context:
Document this API endpoint.
**Example of the style we want:**
[Paste example from existing docs]
Now document this new endpoint following the same style:
${endpoint}4. Iterative Refinement
Refine documentation through multiple passes:
typescript
async function refineDocumentation(
initialDocs: string,
improvements: string[]
): Promise<string> {
let docs = initialDocs;
for (const improvement of improvements) {
const prompt = `
Improve this documentation by: ${improvement}
Current documentation:
${docs}
Provide the refined version.
`;
const response = await llm.complete({
model: 'claude-3-5-sonnet-20241022',
messages: [{ role: 'user', content: prompt }],
});
docs = response.content;
}
return docs;
}
// Usage
let docs = await generateAPIDoc(code);
docs = await refineDocumentation(docs, [
'Add more realistic examples',
'Improve clarity for beginners',
'Add troubleshooting section',
]);5. Maintain Consistency
Use templates for consistency:
typescript
class DocumentationGenerator {
private template: string;
constructor(template: string) {
this.template = template;
}
async generate(subject: any): Promise<string> {
const prompt = `
Generate documentation following this template:
${this.template}
For this subject:
${JSON.stringify(subject, null, 2)}
Maintain the same structure, style, and tone.
`;
const response = await llm.complete({
model: 'claude-3-5-sonnet-20241022',
messages: [{ role: 'user', content: prompt }],
});
return response.content;
}
}Documentation Checklist
Before Generating
- [ ] Understand the audience
- [ ] Gather all necessary context
- [ ] Review existing documentation style
- [ ] Prepare code/API details
- [ ] Define required sections
During Generation
- [ ] Provide clear, specific prompts
- [ ] Include examples of desired output
- [ ] Request specific format
- [ ] Iterate on output
- [ ] Ask for multiple versions if needed
After Generation
- [ ] Review for accuracy - Verify technical correctness
- [ ] Test examples - Ensure code examples work
- [ ] Check completeness - All sections covered
- [ ] Verify clarity - Understandable by target audience
- [ ] Ensure consistency - Matches existing docs style
- [ ] Update regularly - Keep in sync with code
Specialized Documentation
Migration Guides
typescript
async function generateMigrationGuide(
oldVersion: string,
newVersion: string,
changes: string[]
): Promise<string> {
const prompt = `
Generate a migration guide from v${oldVersion} to v${newVersion}.
**Breaking Changes:**
${changes.join('\n')}
**Include:**
1. Overview of changes
2. Step-by-step migration instructions
3. Before/after code examples
4. Common migration issues
5. FAQ section
Make it actionable and clear.
`;
const response = await llm.complete({
model: 'claude-3-5-sonnet-20241022',
messages: [{ role: 'user', content: prompt }],
});
return response.content;
}Changelog Generation
typescript
async function generateChangelog(
commits: Commit[],
version: string
): Promise<string> {
const prompt = `
Generate a changelog for version ${version}.
**Commits:**
${commits.map(c => `- ${c.message} (${c.author})`).join('\n')}
**Format:**
## [${version}] - ${new Date().toISOString().split('T')[0]}
### Added
- New features
### Changed
- Modifications to existing features
### Fixed
- Bug fixes
### Deprecated
- Soon-to-be removed features
Group commits logically and use clear, user-friendly language.
`;
const response = await llm.complete({
model: 'claude-3-5-sonnet-20241022',
messages: [{ role: 'user', content: prompt }],
});
return response.content;
}Architecture Documentation
typescript
async function documentArchitecture(
components: Component[],
relationships: Relationship[]
): Promise<string> {
const prompt = `
Generate architecture documentation.
**Components:**
${JSON.stringify(components, null, 2)}
**Relationships:**
${JSON.stringify(relationships, null, 2)}
**Include:**
1. System overview
2. Component descriptions
3. Data flow diagrams (in Mermaid format)
4. Key design decisions
5. Technology choices and rationale
6. Scalability considerations
7. Security architecture
Use clear, technical language suitable for senior developers.
`;
const response = await llm.complete({
model: 'claude-3-5-sonnet-20241022',
messages: [{ role: 'user', content: prompt }],
});
return response.content;
}Maintaining Documentation
Automation Strategy
typescript
// GitHub Action to update docs on code changes
interface DocUpdateConfig {
triggers: string[]; // Files to watch
docFiles: string[]; // Docs to update
reviewRequired: boolean;
}
async function updateDocsOnChange(
changedFiles: string[],
config: DocUpdateConfig
): Promise<void> {
const relevantChanges = changedFiles.filter(file =>
config.triggers.some(pattern => file.match(pattern))
);
if (relevantChanges.length === 0) return;
for (const docFile of config.docFiles) {
const updatedDoc = await regenerateDoc(docFile, relevantChanges);
if (config.reviewRequired) {
await createPRForDocUpdate(docFile, updatedDoc);
} else {
await commitDocUpdate(docFile, updatedDoc);
}
}
}Version Control for Docs
typescript
interface DocVersion {
version: string;
content: string;
generatedAt: Date;
sourceCodeHash: string;
}
class VersionedDocumentation {
private versions: Map<string, DocVersion[]> = new Map();
async generate(
docId: string,
code: string,
version: string
): Promise<string> {
const content = await generateDoc(code);
const hash = hashCode(code);
const docVersion: DocVersion = {
version,
content,
generatedAt: new Date(),
sourceCodeHash: hash,
};
if (!this.versions.has(docId)) {
this.versions.set(docId, []);
}
this.versions.get(docId)!.push(docVersion);
return content;
}
getVersion(docId: string, version: string): DocVersion | undefined {
return this.versions.get(docId)?.find(v => v.version === version);
}
}Quality Assurance
Documentation Review Checklist
markdown
## Documentation Review
**Technical Accuracy**
- [ ] All code examples are correct
- [ ] API signatures are accurate
- [ ] Examples can be run successfully
- [ ] No outdated information
**Completeness**
- [ ] All public APIs documented
- [ ] Examples cover common use cases
- [ ] Error cases documented
- [ ] Prerequisites listed
**Clarity**
- [ ] Appropriate for target audience
- [ ] Technical terms explained
- [ ] Logical flow and structure
- [ ] No ambiguous statements
**Consistency**
- [ ] Matches existing documentation style
- [ ] Terminology is consistent
- [ ] Format follows standards
- [ ] Voice and tone appropriate
**Maintenance**
- [ ] Version information included
- [ ] Last updated date present
- [ ] Deprecation warnings if applicable
- [ ] Links to related docsAutomated Quality Checks
typescript
async function checkDocQuality(docs: string): Promise<QualityReport> {
const checks = [
checkCodeExamples(docs),
checkLinks(docs),
checkSpelling(docs),
checkReadability(docs),
];
const results = await Promise.all(checks);
return {
score: calculateScore(results),
issues: results.flatMap(r => r.issues),
suggestions: results.flatMap(r => r.suggestions),
};
}Integration Examples
CI/CD Pipeline
yaml
name: Update Documentation
on:
push:
paths:
- 'src/**/*.ts'
- 'docs/**/*.md'
jobs:
update-docs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Generate API Docs
env:
ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
run: npm run generate-docs
- name: Check for changes
id: changes
run: |
git diff --quiet docs/ || echo "::set-output name=changed::true"
- name: Create PR
if: steps.changes.outputs.changed
uses: peter-evans/create-pull-request@v4
with:
title: "docs: Update generated documentation"
body: "Auto-generated documentation updates"
branch: docs/auto-updateResources
Remember: AI-generated documentation is a starting point. Always review, validate, and refine to ensure accuracy and quality.