Перейти к содержанию

Prompts

prompts — секция конфигурации, определяющая пользовательские промпты (команды), вызываемые из окна чата через /. Промпты позволяют переиспользовать часто используемые инструкции и рабочие процессы.

Структура

prompts:
  - name: review
    description: Review code for bugs
    prompt: Review the selected code for bugs and improvements
  - name: test
    description: Write unit tests
    prompt: Write comprehensive unit tests for the selected code

Свойства промпта

Свойство Тип Обязательность Описание
name string Да Имя промпта (используется для вызова через /)
description string Нет Описание, отображаемое в UI
prompt string Да Текст промпта (инструкция для LLM)

Форматы промптов

Простой промпт

Базовый формат с текстовой инструкцией:

prompts:
  - name: explain
    description: Explain the code
    prompt: Explain what the selected code does in simple terms

Многострочный промпт

Используйте | для многострочных инструкций:

prompts:
  - name: check
    description: Check for mistakes
    prompt: |
      Please review the highlighted code and check for:
        - Syntax errors
        - Logic errors
        - Security vulnerabilities
        - Performance issues
        - Code style violations

      Provide specific suggestions for improvement.

Промпт с переменной input

Используйте {{{ input }}} для подстановки пользовательского ввода:

prompts:
  - name: refactor
    description: Refactor code
    prompt: |
      Refactor the following code to improve {{{ aspect }}}:

      {{{ input }}}

      Provide the refactored code with explanations.

Промпт с использованием Prompt Files (v2)

Prompt Files v2 поддерживают продвинутый синтаксис с переменными и контекстом:

prompts:
  - name: document
    description: Add documentation
    prompt: |
      ---
      description: Add comprehensive documentation to the code
      ---

      Add JSDoc/TSDoc comments to the following code:

      {{ code }}

      Include:
      - @param for each parameter
      - @returns for return value
      - @throws for potential errors

Пакетное определение (uses)

Можно использовать готовые пакеты промптов:

prompts:
  - uses: best-practices/code-review
    with:
      language: typescript
  - uses: company-standards/documentation
    override:
      description: Add company-standard documentation
Свойство Тип Описание
uses string Slug пакета: owner/package
with Record<string, string> Переменные окружения для пакета
override Partial<Prompt> Переопределения для промпта из пакета

Примеры конфигураций

Для код-ревью

prompts:
  - name: review
    description: Review code for bugs
    prompt: |
      Review the selected code for:
        - Bugs and errors
        - Security vulnerabilities
        - Performance issues
        - Code quality

      Provide specific, actionable feedback.

  - name: security
    description: Security audit
    prompt: |
      Perform a security audit of the selected code:
        - Check for SQL injection vulnerabilities
        - Check for XSS vulnerabilities
        - Check for authentication/authorization issues
        - Check for data validation issues

      List all findings with severity levels.

Для написания тестов

prompts:
  - name: test
    description: Write unit tests
    prompt: |
      Write comprehensive unit tests for the selected code using Jest.

      Include:
        - Happy path tests
        - Edge case tests
        - Error handling tests

      Follow AAA pattern (Arrange, Act, Assert).

  - name: e2e
    description: Write E2E tests
    prompt: |
      Write end-to-end tests for the following functionality using {{{ framework }}}:

      {{{ input }}}

      Cover the complete user workflow.

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

prompts:
  - name: doc
    description: Add documentation
    prompt: |
      Add comprehensive documentation to the code:
        - JSDoc/TSDoc comments for functions
        - Inline comments for complex logic
        - README updates if needed

  - name: readme
    description: Update README
    prompt: |
      Update the README.md file to include:
        - Project overview
        - Installation instructions
        - Usage examples
        - API documentation
        - Contributing guidelines

Для рефакторинга

prompts:
  - name: refactor
    description: Refactor code
    prompt: |
      Refactor the following code to improve:
        - Readability
        - Maintainability
        - Performance

      Apply SOLID principles and design patterns where appropriate.

  - name: optimize
    description: Optimize performance
    prompt: |
      Analyze and optimize the performance of this code:
        - Identify bottlenecks
        - Suggest algorithmic improvements
        - Reduce memory usage
        - Minimize unnecessary operations

Для работы с данными

prompts:
  - name: validate
    description: Validate data
    prompt: |
      Validate the data structure and check for:
        - Type consistency
        - Missing required fields
        - Invalid values
        - Data integrity issues

  - name: transform
    description: Transform data
    prompt: |
      Transform the following data structure:

      {{{ input }}}

      To the following format: {{{ target_format }}}

Переменные в промптах

Встроенные переменные

Переменная Описание Пример использования
{{{ input }}} Пользовательский ввод после команды {{{ input }}}
{{{ code }}} Выделенный код (в Prompt Files v2) {{ code }}
{{{ file }}} Текущий файл (в Prompt Files v2) {{ file }}

Пользовательские переменные

Переменные можно передавать через параметры:

prompts:
  - name: generate
    description: Generate code
    prompt: |
      Generate {{{ language }}} code for {{{ functionality }}}:

      {{{ input }}}

Взаимодействие с другими функциями

С контекст-провайдерами

Промпты могут использовать контекст-провайдеры:

prompts:
  - name: debug
    description: Debug with terminal
    prompt: |
      Analyze the terminal output and identify the issue:

      @terminal

      Suggest fixes based on the error messages.

С правилами (rules)

Промпты работают совместно с правилами:

~/.koda/config.yaml
rules:
  - Always use TypeScript
  - Write tests for new code

prompts:
  - name: implement
    description: Implement feature
    prompt: |
      Implement the following feature following project standards:

      {{{ input }}}

С моделями

Можно указать предпочтительную модель для промпта (через Prompt Files v2):

prompts:
  - name: complex-analysis
    description: Complex analysis
    prompt: |
      ---
      model: claude-3-7-sonnet
      ---

      Perform a detailed analysis of the code architecture...

Prompt Files v2

Промпты можно хранить в отдельных файлах с расширением .prompt:

Структура файла:

---
name: my-prompt
description: My custom prompt
version: 1.0.0
---

# System Instructions

You are a helpful coding assistant.

# User Input

{{{ input }}}

# Context

{{ code }}

Использование в config.yaml:

prompts:
  - uses: ./.koda/prompts/my-prompt

Рекомендации

Хорошие практики

  • Короткие имена: Используйте краткие, понятные имена для команд
  • Описательные description: Пишите понятные описания для UI
  • Структурируйте промпты: Используйте списки и заголовки для сложных инструкций
  • Документируйте переменные: Комментируйте ожидаемые переменные в промпте
  • Тестируйте: Проверяйте промпты на разных типах ввода

Чего избегать

  • Слишком длинных промптов (>2000 символов)
  • Неопределённых инструкций («сделай лучше»)
  • Жёсткой привязки к конкретному коду
  • Дублирования встроенных команд

Типовые сценарии

Daily Development

prompts:
  - name: commit
    description: Generate commit message
    prompt: |
      Generate a conventional commit message for the current changes:

      Format: <type>(<scope>): <description>

      Types: feat, fix, docs, style, refactor, test, chore

  - name: pr
    description: Create PR description
    prompt: |
      Write a pull request description including:
        - Summary of changes
        - Type of change (feat/fix/etc.)
        - Testing performed
        - Checklist for reviewers

Code Quality

prompts:
  - name: lint
    description: Check code quality
    prompt: |
      Analyze code quality and suggest improvements:
        - Code style consistency
        - Naming conventions
        - Function complexity
        - Code duplication

  - name: improve
    description: Suggest improvements
    prompt: |
      Suggest specific improvements for this code:
        - Readability
        - Maintainability
        - Extensibility
        - Error handling

Отладка промптов

Проверка синтаксиса

Убедитесь, что YAML-синтаксис корректен:

# Проверка YAML
yamllint config.yaml

Тестирование промпта

  1. Запустите команду через /name
  2. Проверьте, что ввод правильно подставляется
  3. Убедитесь, что результат соответствует ожиданиям

Логирование

Для отладки сложных промптов добавьте вывод промежуточных значений:

prompts:
  - name: debug-prompt
    description: Debug prompt
    prompt: |
      Input received: {{{ input }}}

      Now process the input...

См. также

  • Справочник YAML — полная спецификация конфигурации
  • Rules — системные правила для LLM
  • Prompt Files — продвинутые шаблоны промптов