문서 자동화가 필요한 이유
코드는 빠르게 변하지만 문서는 항상 뒤처집니다. LLM은 코드를 읽고 최신 문서를 생성하거나 업데이트할 수 있습니다.
flowchart LR Code[소스 코드] --> LLM[LLM] LLM --> Docstring[docstring 생성] LLM --> README[README 업데이트] LLM --> API[OpenAPI 스펙] LLM --> Tutorial[튜토리얼 생성] Git[git diff] --> LLM
Python Docstring 자동 생성
import ast
import anthropic
client = anthropic.Anthropic()
def add_docstrings(source_code: str) -> str:
response = client.messages.create(
model="claude-sonnet-4-6-20251001",
max_tokens=4096,
system='''Python 함수와 클래스에 Google 스타일 docstring을 추가하세요.
형식:
'''한 줄 요약.
Args:
param1 (type): 설명.
param2 (type): 설명.
Returns:
type: 설명.
Raises:
ExceptionType: 발생 조건.
Example:
>>> result = func(1, 2)
>>> print(result)
3
'''
- 이미 docstring이 있는 함수는 수정하지 마세요
- 타입 정보가 있으면 활용하세요''',
messages=[{
"role": "user",
"content": f"다음 Python 코드에 docstring을 추가해주세요:
```python
{source_code}
```"
}]
)
return response.content[0].text
# 전체 파일 처리
import os
from pathlib import Path
def process_directory(src_dir: str):
for py_file in Path(src_dir).rglob("*.py"):
if "test_" in py_file.name:
continue
with open(py_file) as f:
code = f.read()
# docstring 없는 함수가 있을 때만 처리
tree = ast.parse(code)
missing = [n for n in ast.walk(tree)
if isinstance(n, (ast.FunctionDef, ast.AsyncFunctionDef))
and not (n.body and isinstance(n.body[0], ast.Expr)
and isinstance(n.body[0].value, ast.Constant))]
if missing:
documented = add_docstrings(code)
with open(py_file, "w") as f:
f.write(documented)
print(f"✅ {py_file}")
OpenAPI 스펙 자동 생성
def generate_openapi_spec(fastapi_code: str) -> dict:
response = client.messages.create(
model="claude-sonnet-4-6-20251001",
max_tokens=4096,
system="FastAPI 라우터 코드를 분석해서 OpenAPI 3.0 YAML 스펙을 생성하세요.",
messages=[{
"role": "user",
"content": f"OpenAPI 스펙 생성:
```python
{fastapi_code}
```"
}]
)
import yaml
return yaml.safe_load(response.content[0].text)
# FastAPI는 자동 생성되지만, 설명이 빈약할 때 보강
def enhance_openapi_descriptions(spec: dict) -> dict:
response = client.messages.create(
model="claude-sonnet-4-6-20251001",
max_tokens=2048,
messages=[{
"role": "user",
"content": f'''다음 OpenAPI 스펙의 description 필드를 개선해줘.
각 엔드포인트의 목적, 사용 예시, 에러 케이스를 포함해서.
현재 스펙:
{yaml.dump(spec, allow_unicode=True)}'''
}]
)
return yaml.safe_load(response.content[0].text)
README 자동 생성 및 업데이트
def generate_readme(repo_path: str) -> str:
# 코드 구조 분석
structure = []
for root, dirs, files in os.walk(repo_path):
dirs[:] = [d for d in dirs if not d.startswith('.') and d != '__pycache__']
level = root.replace(repo_path, '').count(os.sep)
structure.append(f"{' ' * level}{os.path.basename(root)}/")
for file in files[:5]: # 파일 최대 5개만
structure.append(f"{' ' * (level+1)}{file}")
# 주요 파일 내용
main_files = []
for pattern in ["main.py", "app.py", "index.ts", "package.json"]:
for f in Path(repo_path).rglob(pattern):
with open(f) as fp:
main_files.append(f"#
## {f}
\`\`\`
" + fp.read()
[:500] + "
\`\`\`")
break
response = client.messages.create(
model="claude-sonnet-4-6-20251001",
max_tokens=4096,
system='''프로젝트 README.md를 작성하세요.
포함할 항목:
- 프로젝트 설명 (2-3문장)
- 주요 기능 (bullet)
- 설치 방법
- 빠른 시작 예제
- 환경변수 목록
- API 문서 링크 (있는 경우)
- 라이센스''',
messages=[{
"role": "user",
"content": f'''프로젝트 구조:
{chr(10).join(structure[:50])}
주요 파일:
{chr(10).join(main_files)}'''
}]
)
return response.content[0].text
Git Commit → Changelog 자동화
import subprocess
def generate_changelog_entry(since_tag: str = "HEAD~10") -> str:
# 최근 커밋 목록
result = subprocess.run(
["git", "log", since_tag, "--pretty=format:%h %s", "--no-merges"],
capture_output=True, text=True
)
commits = result.stdout.strip()
# 변경된 파일
result2 = subprocess.run(
["git", "diff", since_tag, "--stat"],
capture_output=True, text=True
)
response = client.messages.create(
model="claude-haiku-4-5-20251001", # 간단한 작업은 저렴한 모델로
max_tokens=1024,
messages=[{
"role": "user",
"content": f'''다음 git 커밋들을 Keep a Changelog 형식으로 정리해줘:
커밋 목록:
{commits}
변경 파일:
{result2.stdout[:2000]}'''
}]
)
return response.content[0].text
# 매주 자동 실행 (cron)
changelog = generate_changelog_entry("v1.2.0")
with open("CHANGELOG.md", "a") as f:
f.write(f"
## [Unreleased] - {datetime.now().strftime('%Y-%m-%d')}
")
f.write(changelog)
CI/CD 통합
# .github/workflows/docs.yml
name: Auto Documentation
on:
push:
branches: [main]
paths: ['src/**/*.py', 'src/**/*.ts']
jobs:
update-docs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Generate/Update Docs
env:
ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
run: |
python scripts/auto_docs.py --check-missing-docstrings
python scripts/update_readme.py
- name: Commit docs update
run: |
git config user.name "docs-bot"
git add docs/ README.md
git diff --staged --quiet || git commit -m "docs: auto-update documentation"
git push
문서 자동화의 핵심은 '완벽한 문서 생성'이 아니라 '항상 최신 상태 유지'입니다. AI 초안 → 개발자 검토 → 머지 흐름으로 운영하세요.





