Переменные в промптах¶
Переменные позволяют делать промпты гибкими и переиспользуемыми, подставляя динамические значения в текст инструкции.
Типы переменных¶
| Переменная | Поддерживается | Синтаксис | Описание |
|---|---|---|---|
{{{ input }}} |
✅ Да | {{{ input }}} |
Текст после команды /name |
{{{ code }}} |
✅ Да (v2) | {{ code }} |
Выделенный код (Prompt Files v2) |
{{{ file }}} |
✅ Да (v2) | {{ file }} |
Текущий файл (Prompt Files v2) |
{{{ custom }}} |
⚠️ Ограниченно | {{{ name }}} |
Пользовательские переменные (не работают в YAML) |
{{{ input }}} — основная переменная¶
Что это?¶
{{{ input }}} — это единственная полностью поддерживаемая переменная в YAML-промптах. Она автоматически заменяется на текст, который пользователь ввёл после команды.
Как работает?¶
Примеры использования:
| Команда в чате | Что подставляется в {{{ input }}} |
|---|---|
/explain |
Пустая строка "" |
/explain this function |
"this function" |
/explain how recursion works here |
"how recursion works here" |
Практические примеры¶
Пример 1: Промпт с вопросом¶
prompts:
- name: fix
description: Fix code issue
prompt: |
Fix the following issue:
**Problem:** {{{ input }}}
**Code:**
{{ code }}
Provide the corrected code with explanations.
Использование:
→ В промпт подставится:
Пример 2: Промпт с контекстом¶
prompts:
- name: improve
description: Improve code
prompt: |
Improve the code based on the following requirements:
**Requirements:** {{{ input }}}
**Current code:**
{{ code }}
Provide the improved version with explanations of changes.
Использование:
Пример 3: Промпт без input¶
Если переменная {{{ input }}} не используется, весь текст после команды игнорируется:
prompts:
- name: lint
description: Check code quality
prompt: |
Analyze the code quality and suggest improvements:
- Code style
- Best practices
- Potential bugs
**Code:**
{{ code }}
Использование:
Переменные в Prompt Files v2¶
Prompt Files v2 (отдельные файлы .prompt) используют Handlebars и поддерживают более продвинутую работу с переменными.
Синтаксис Handlebars¶
| Синтаксис | Описание |
|---|---|
{{ variable }} |
Простая переменная |
{{#if variable}}...{{/if}} |
Условное отображение |
{{#unless variable}}...{{/unless}} |
Отрицательное условие |
{{#each array}}...{{/each}} |
Цикл по массиву |
{{> partial }} |
Частичный шаблон |
Пример 1: Условное отображение¶
---
name: test
description: Write unit tests
---
{{#if framework}}
Write unit tests using **{{ framework }}**:
{{else}}
Write unit tests:
{{/if}}
Code to test:
{{ code }}
Ограничение: Переменные вроде framework нельзя передать напрямую через UI. Они остаются как текст или требуют дополнительного механизма.
Пример 2: Несколько условий¶
---
name: generate
description: Generate code
---
{{#if language}}
Generate {{ language }} code:
{{else}}
Generate code:
{{/if}}
{{#if requirements}}
Requirements:
{{ requirements }}
{{/if}}
{{#if input}}
Additional context:
{{ input }}
{{/if}}
Пример 3: Циклы¶
---
name: checklist
description: Generate checklist
---
Review the code for:
{{#each items}}
- [ ] {{ this }}
{{/each}}
Code:
{{ code }}
Пользовательские переменные в YAML¶
⚠️ Текущие ограничения¶
В YAML-промптах пользовательские переменные (кроме {{{ input }}}) не работают автоматически:
# ❌ НЕ работает
prompts:
- name: test
description: Write tests
prompt: |
Write tests using {{{ framework }}}:
{{ code }}
Проблема: При использовании /test Jest переменная {{{ framework }}} не заменится на "Jest". Весь текст "Jest" попадёт в {{{ input }}}.
Рабочие альтернативы¶
Альтернатива 1: Только {{{ input }}}¶
prompts:
- name: test
description: Write tests
prompt: |
Write unit tests based on the following specification:
**Specification:** {{{ input }}}
**Code:**
{{ code }}
Использование:
Альтернатива 2: Несколько промптов¶
prompts:
- name: test-jest
description: Write Jest tests
prompt: |
Write unit tests using Jest:
{{ code }}
- name: test-mocha
description: Write Mocha tests
prompt: |
Write unit tests using Mocha:
{{ code }}
- name: test-vitest
description: Write Vitest tests
prompt: |
Write unit tests using Vitest:
{{ code }}
Использование:
Альтернатива 3: Prompt Files v2¶
Создайте файл .koda/prompts/test.prompt:
---
name: test
description: Write unit tests
---
{{#if framework}}
Write unit tests using **{{ framework }}**:
{{else}}
Write unit tests:
{{/if}}
{{ code }}
В config.yaml:
Специальные переменные контекста¶
Эти переменные работают только в Prompt Files v2:
{{ code }} — выделенный код¶
---
name: refactor
description: Refactor code
---
Refactor the following code to improve readability:
{{ code }}
Provide the refactored version with explanations.
{{ file }} — текущий файл¶
---
name: analyze
description: Analyze file
---
Analyze the structure of this file:
{{ file }}
Suggest improvements for:
- Code organization
- Naming conventions
- Error handling
{{ input }} — ввод пользователя (Handlebars)¶
---
name: explain
description: Explain code
---
Explain the following code {{#if input}}with focus on {{ input }}{{else}}in detail{{/if}}:
{{ code }}
Сравнение YAML и Prompt Files v2¶
| Возможность | YAML | Prompt Files v2 |
|---|---|---|
{{{ input }}} |
✅ Да | ✅ Да ({{ input }}) |
{{ code }} |
⚠️ Зависит от контекста | ✅ Да |
{{ file }} |
❌ Нет | ✅ Да |
Условия (if) |
❌ Нет | ✅ Да |
Циклы (each) |
❌ Нет | ✅ Да |
Части (partial) |
❌ Нет | ✅ Да |
| Пользовательские переменные | ❌ Нет | ⚠️ Ограниченно |
Практические рекомендации¶
✅ Хорошие практики¶
1. Используйте {{{ input }}} для гибкости:
prompts:
- name: optimize
description: Optimize code
prompt: |
Optimize the code based on these requirements:
**Requirements:** {{{ input }}}
**Code:**
{{ code }}
2. Документируйте ожидаемый ввод:
prompts:
- name: generate
description: Generate code
prompt: |
Generate code based on the specification.
**Specification format:**
- Language: (e.g., Python, TypeScript)
- Framework: (e.g., React, Django)
- Requirements: (list of features)
**Your specification:** {{{ input }}}
3. Создавайте специализированные промпты:
prompts:
# Общие промпты
- name: review
description: General code review
prompt: &review_prompt |
Review the code for:
- Bugs
- Security issues
- Performance
- Best practices
{{ code }}
# Специализированные варианты
- name: review-security
description: Security-focused review
prompt: |
<<: *review_prompt
Focus especially on security vulnerabilities.
❌ Чего избегать¶
1. Не надейтесь на пользовательские переменные в YAML:
2. Не делайте промпты слишком сложными:
# ❌ Слишком сложно
prompts:
- name: complex
prompt: |
If {{{ condition1 }}} then {{{ action1 }}}
else if {{{ condition2 }}} then {{{ action2 }}}
else {{{ default }}}
3. Не забывайте про {{{ input }}}:
# ❌ Input игнорируется
prompts:
- name: fix
prompt: Fix the code
# ✅ Input используется
prompts:
- name: fix
prompt: |
Fix the following issue: {{{ input }}}
{{ code }}
Отладка переменных¶
Проверка подстановки¶
Добавьте вывод переменной для отладки:
prompts:
- name: debug
description: Debug variable substitution
prompt: |
DEBUG: input = "{{{ input }}}"
Now process the input...
Использование:
→ Выведет:
Проверка контекста¶
Для Prompt Files v2 можно вывести доступные переменные:
---
name: debug-vars
description: Debug available variables
---
**Available variables:**
- input: {{ input }}
- code: {{ code }}
- file: {{ file }}
**Context:**
{{ code }}
Примеры готовых промптов¶
Для разработки¶
prompts:
- name: feature
description: Implement feature
prompt: |
Implement the following feature:
**Description:** {{{ input }}}
**Requirements:**
- Follow existing code style
- Add tests
- Update documentation
**Code:**
{{ code }}
- name: bugfix
description: Fix bug
prompt: |
Fix the following bug:
**Bug description:** {{{ input }}}
**Expected behavior:** (describe what should happen)
**Actual behavior:** (describe what actually happens)
**Code:**
{{ code }}
Для документации¶
prompts:
- name: comment
description: Add comments
prompt: |
Add comprehensive comments to the code:
**Focus areas:** {{{ input }}}
**Guidelines:**
- Explain complex logic
- Add @param and @returns
- Document edge cases
**Code:**
{{ code }}
- name: docs
description: Write documentation
prompt: |
Write documentation for:
**Topic:** {{{ input }}}
**Include:**
- Overview
- Installation
- Usage examples
- API reference
Для тестирования¶
prompts:
- name: test
description: Write tests
prompt: |
Write comprehensive tests:
**Test framework:** {{{ input }}}
**Test types:**
- Unit tests
- Integration tests
- Edge cases
**Code:**
{{ code }}
- name: coverage
description: Improve test coverage
prompt: |
Analyze test coverage and suggest missing tests:
**Focus:** {{{ input }}}
**Code:**
{{ code }}
**Existing tests:**
{{ tests }}
См. также¶
- Prompt Files — файлы промптов
- Rules — системные правила