/
Вопросы и ответы
/
Промт-инжиниринг
/

Промпты для генерации документации

Промпты для генерации документации

9 часов назад

Никита Вихров

Ответы

0

Промпты для генерации документации

Документацию никто не любит писать — и именно поэтому её нет или она устарела. ИИ закрывает рутину: docstrings, README, описания API. Остаётся только проверить.


Docstrings по коду

from anthropic import Anthropic
import ast

client = Anthropic()


def generate_docstring(function_code: str, style: str = "google") -> str:
    styles = {
        "google": "Google Style Python Docstrings",
        "numpy": "NumPy/SciPy Docstrings",
        "sphinx": "reStructuredText для Sphinx",
    }

    response = client.messages.create(
        model="claude-opus-4-5",
        max_tokens=512,
        system=f"""Пишешь docstring в стиле {styles[style]}.
Анализируй код и описывай: что делает функция, параметры, возвращаемое значение, исключения.
Возвращай только docstring в тройных кавычках, без лишнего текста.""",
        messages=[{
            "role": "user",
            "content": f"Напиши docstring для этой функции:\n\n```python\n{function_code}\n```"
        }]
    )
    return response.content[0].text


# Применяем ко всем функциям без docstring
def add_docstrings_to_file(filepath: str) -> str:
    with open(filepath) as f:
        source = f.read()

    tree = ast.parse(source)
    lines = source.split("\n")
    insertions = []  # (line_number, docstring)

    for node in ast.walk(tree):
        if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
            # Пропускаем если docstring уже есть
            if (node.body and isinstance(node.body[0], ast.Expr)
                    and isinstance(node.body[0].value, ast.Constant)):
                continue

            func_lines = lines[node.lineno - 1:node.end_lineno]
            func_code = "\n".join(func_lines)
            docstring = generate_docstring(func_code)
            indent = "    " * (node.col_offset // 4 + 1)

            insertions.append((node.body[0].lineno - 1, indent + docstring))

    # Вставляем docstrings снизу вверх чтобы не сбить индексы
    for line_num, docstring in sorted(insertions, reverse=True):
        lines.insert(line_num, docstring)

    return "\n".join(lines)

README по проекту

import os


def collect_project_info(project_path: str) -> str:
    """Собирает информацию о проекте для передачи в LLM"""
    info = []

    # Структура директорий
    for root, dirs, files in os.walk(project_path):
        dirs[:] = [d for d in dirs if d not in ["node_modules", ".git", "__pycache__", ".venv"]]
        level = root.replace(project_path, "").count(os.sep)
        indent = "  " * level
        info.append(f"{indent}{os.path.basename(root)}/")
        for file in files[:5]:  # не больше 5 файлов на директорию
            info.append(f"{indent}  {file}")

    # package.json или pyproject.toml
    for config_file in ["package.json", "pyproject.toml", "requirements.txt"]:
        config_path = os.path.join(project_path, config_file)
        if os.path.exists(config_path):
            with open(config_path) as f:
                info.append(f"\n{config_file}:\n{f.read()[:1000]}")

    # Главный файл
    for entry in ["main.py", "app.py", "index.js", "src/index.ts"]:
        entry_path = os.path.join(project_path, entry)
        if os.path.exists(entry_path):
            with open(entry_path) as f:
                info.append(f"\n{entry} (первые 50 строк):\n" + "\n".join(f.readlines()[:50]))

    return "\n".join(info)


def generate_readme(project_path: str) -> str:
    project_info = collect_project_info(project_path)

    response = client.messages.create(
        model="claude-opus-4-5",
        max_tokens=2048,
        system="""Пишешь README.md для open-source проекта.
Структура: описание, быстрый старт, установка, использование с примерами, переменные окружения, contributing.
Тон: дружелюбный, конкретный. Примеры кода обязательны.""",
        messages=[{
            "role": "user",
            "content": f"Напиши README для этого проекта:\n\n{project_info}"
        }]
    )
    return response.content[0].text

Документация API из кода

def document_api_endpoint(route_code: str, schema_code: str = "") -> str:
    response = client.messages.create(
        model="claude-opus-4-5",
        max_tokens=1024,
        system="""Документируешь REST API эндпоинт.
Формат Markdown:
## POST /endpoint

Описание в одном предложении.

**Request body:**
| Поле | Тип | Обязательное | Описание |

**Response 200:**
```json
{пример}

Ошибки: | Код | Когда возникает |""", messages=[{ "role": "user", "content": f"Задокументируй эндпоинт:\n\npython\n{route_code}\n\n\nСхемы:\npython\n{schema_code}\n" }] ) return response.content[0].text

--- **Автообновление при изменении кода** ```python import hashlib import json from pathlib import Path def get_file_hash(filepath: str) -> str: return hashlib.md5(open(filepath, "rb").read()).hexdigest() def update_docs_if_changed(source_file: str, doc_file: str): hash_file = doc_file + ".hash" current_hash = get_file_hash(source_file) # Проверяем изменился ли исходник if Path(hash_file).exists(): saved_hash = open(hash_file).read() if saved_hash == current_hash: print(f"Пропускаем {source_file} — не изменился") return print(f"Обновляем документацию для {source_file}...") with open(source_file) as f: code = f.read() # Генерируем документацию response = client.messages.create( model="claude-haiku-4-5", # дешевле для рутины max_tokens=1024, system="Обнови документацию для этого модуля. Markdown формат.", messages=[{"role": "user", "content": code}] ) # Сохраняем документацию и хэш open(doc_file, "w").write(response.content[0].text) open(hash_file, "w").write(current_hash) print(f"✅ {doc_file} обновлён")

На курсе «ИИ для разработчиков» на Хекслете разбирают как встроить ИИ в реальный рабочий процесс: от автогенерации документации до полного AI-ориентированного workflow.

9 часов назад

Никита Вихров

+7 800 100 22 47

бесплатно по РФ

+7 495 085 21 62

бесплатно по Москве

108813 г. Москва, вн.тер.г. поселение Московский,
г. Московский, ул. Солнечная, д. 3А, стр. 1, помещ. 20Б/3
ОГРН 1217300010476
ИНН 7325174845