К основному содержанию
скилл CX Codex

prompt-optimize — скилл для Claude Code: что делает и как установить

Скилл prompt-optimize для Claude Code итеративно улучшает готовый промпт по команде оценки и сохраняет только правки, повышающие метрику.

MIT ★ 185 обновлён 2026-06-30

Установить в Claude Code · Через маркетплейс плагинов Все способы и платформы ↓
/plugin marketplace add gaasher/Agent-Loop-Skills
/plugin install agent-loops@agent-loop-skills
Открыть на GitHub

Что делает prompt-optimize

Скилл запускает эволюционный цикл оптимизации существующего промпта. На каждом шаге агент анализирует слабые места формулировки и делает одну точечную правку: добавляет контекст, примеры, правила-ограничители или декомпозирует шаги. Затем он вызывает вашу команду оценки (<eval_cmd>), считывает оценку с последней строки вывода и сверяет её с прошлым результатом. Если метрика выросла, правка сохраняется, а при откате агент возвращает лучший снимок из каталога ./sandbox.

Процесс продолжается до достижения целевого балла, лимита шагов (по умолчанию 10) или плато по числу безуспешных попыток. Скрипты и тесты скилл не трогает, используя команду оценки исключительно как независимый оракул.

Без готовой команды оценки запустить оптимизацию не выйдет: скилл не придумывает промпты с нуля и не калибрует веса моделей. Для работы требуется, чтобы команда возвращала число либо JSON со свойством score в последней строке.

Какие задачи решает

  • повысить точность существующего системного промпта по внешней метрике
  • автоматически перебирать формулировки инструкций без ручного отката неудачных правок
  • найти узкие места в промпте с опорой на числовой скор и текстовый фидбек тестов
  • зафиксировать историю экспериментов и снимков промпта в отдельном журнале

Примеры запросов агенту

  • Оптимизируй промпт в prompts/extractor.txt, запуская для проверки python eval.py
  • Улучши системный промпт agent.md до скора 0.95 с помощью бенчмарка npm test -- --eval
  • Запусти цикл оптимизации prompt.txt с лимитом в 15 итераций и командой pytest tests/eval_accuracy.py

Как установить prompt-optimize

1Через маркетплейс плагинов

/plugin marketplace add gaasher/Agent-Loop-Skills
/plugin install agent-loops@agent-loop-skills

Команда ставит плагин agent-loops целиком, со всеми его скиллами

2Через Skills CLI (Vercel)

npx skills add gaasher/Agent-Loop-Skills --skill prompt-optimize -a claude-code

3Вручную: положить файлы

~/.claude/skills/prompt-optimize/SKILL.md

Папка скилла целиком; для одного проекта — .claude/skills/prompt-optimize/

По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов

Вопросы о prompt-optimize

Как установить prompt-optimize в Claude Code?

Подключите репозиторий каталога командой /plugin marketplace add gaasher/Agent-Loop-Skills, после чего инсталлируйте пакет вызовом /plugin install agent-loops@agent-loop-skills.

Что делает скилл prompt-optimize?

Он автоматически шлифует текстовый промпт короткими правками, проверяя каждую на вашей команде тестирования. Изменения принимаются только при росте итогового балла.

В каком формате команда проверки должна возвращать результат?

Команда <eval_cmd> обязана вывести на последней строке обычное число или JSON-объект вида {"score": <number>, "feedback": "..."}.

Исходный текст

SKILL.md · MIT
---
name: prompt-optimize
description: >
  Use when the user has a prompt that feeds a system they can already score, and wants that prompt
  automatically improved to raise the score against their own evaluation command. Makes one targeted
  quality edit per iteration — clarity, context, specificity, structure, examples, decomposition,
  guardrails — re-runs the user's eval to measure the metric, and keeps the edit only if the metric
  improves, else reverts; loops to a target, plateau, or budget. The metric is whatever the user's
  eval command prints (task accuracy, an LLM-judge score, a pass rate, a tool-call success rate); the
  loop is metric-agnostic and never edits the eval. Not for writing a prompt from scratch, not for
  tuning model weights or hyperparameters, and not for one-off manual prompt edits without a score.
metadata:
  version: "0.1.0"
---

# Prompt Optimize Loop

An **evolutionary optimizer for a prompt** (OpenEvolve / AlphaEvolve-style). The artifact is a prompt
that feeds the user's system; the feedback signal is a **scalar metric printed by the user's own
evaluation command**. Each iteration proposes one quality-focused edit, re-runs the eval, and keeps
the edit only if the metric improves — evolving the prompt toward higher scores. The eval is a
black-box oracle the loop runs but never edits, so the optimization tracks what actually matters
rather than gaming a number.

## When to use

Use this when the user has a prompt and a command that scores the system using it, and wants the
prompt improved to raise that score. Default to diagnosing the prompt's biggest current weakness each
round and applying the one operator that addresses it; if the eval feedback points elsewhere, follow
the feedback. Not for authoring a prompt from nothing, tuning weights/hyperparameters, or making a
single manual edit with no score to compare against.

## Setup

Resolve bindings interactively. If `loop.run.yaml` exists in the working dir, load it, confirm the
values in one line, and skip to the loop. Otherwise: on Claude Code (the `AskUserQuestion` tool is
available) infer a likely value for each binding and present it as the recommended option; on other
hosts ask each as a quoted plain-text prompt. Then write `loop.run.yaml` (format:
`examples/run.example.yaml`) and confirm the values before creating any other files.

| binding | meaning | default | how to infer |
|---|---|---|---|
| `<prompt_file>` | the prompt to optimize — the artifact the loop evolves | — | scan the working dir for the prompt/template file the eval reads |
| `<eval_cmd>` | **required.** Command that scores the current `<prompt_file>`; prints the metric (see output convention below). Treated as a black box — never edited | — | ask the user; look for `eval`/`score`/`bench` scripts |
| `<objective>` | `maximize` or `minimize`, plus one line on what the metric measures | `maximize` | ask the user |
| `<target>` | optional score at which to stop early | — | ask the user; else leave unbound |
| `<sandbox_root>` | where prompt snapshots + ledger live | `./sandbox` | — |
| `<budget>` | max iterations | 10 | — |
| `<patience>` | stop after N consecutive non-improving iterations (plateau) | 3 | — |

**Eval output convention.** `<eval_cmd>` must print, on its **last line**, either a JSON object
`{"score": <number>, "feedback": "<optional notes/errors>", ...any extra metrics...}` or a bare
number. Higher is better unless `<objective>` is `minimize`. The `feedback` field, when present, is
the richest signal — read it like AlphaEvolve's artifacts side-channel to decide the next edit.

**Eval runs in the user's environment.** `<eval_cmd>` may call an inference endpoint or any tooling the
user has installed; the loop just shells out and reads the last line. If instead the prompt is executed
by *you* (interactive development with no separate endpoint), first run the current prompt over the
user's eval inputs to produce outputs, write them where `<eval_cmd>` reads, then run `<eval_cmd>` to
score them.

## The loop

Copy this checklist and tick items off:
- [ ] Iteration 0 — baseline: run `<eval_cmd>` on `<prompt_file>`, record its score as the current best, snapshot the prompt.
- [ ] Diagnose the prompt's single biggest weakness from the latest score, the eval feedback, and the history.
- [ ] Apply one targeted edit (one operator from the toolkit) to `<prompt_file>`.
- [ ] Measure: re-run `<eval_cmd>` and read the new score from its last line.
- [ ] Keep if the metric improves (require a margin if the eval is stochastic), else revert to the best snapshot.
- [ ] Append a ledger row; if stuck, branch from an earlier high-scoring variant; stop on `<target>`, plateau (`<patience>`), or `<budget>`.

**Iteration 0 — baseline.** Run `<eval_cmd>`, record its score as the best, snapshot `<prompt_file>`
to `<sandbox_root>/iter0/`, and start the history (`{iter, edit, score, feedback}` per row).

**Then, until stop (target, plateau, or budget):**

1. **Diagnose.** From the latest score, the `<eval_cmd>` feedback, and recent history, name the
   prompt's single biggest current weakness — the one thing most likely holding the metric back.
2. **Make one targeted edit** — pick the toolkit operator that addresses that weakness:
   - **Clarity** — remove ambiguity, contradictions, and vague wording.
   - **Context** — supply missing domain knowledge, definitions, or background the task needs.
   - **Specificity** — make instructions concrete; pin down the output format; define what "good" is.
   - **Structure** — order the prompt into steps/sections; add a short checklist.
   - **Examples** — add one or two demonstrations of the desired input → output.
   - **Decomposition** — split a complex instruction into explicit ordered sub-steps.
   - **Guardrails** — state edge cases and what to avoid.

   One change per iteration, so its effect on the metric is attributable.
3. **Measure.** Snapshot the edited prompt to `<sandbox_root>/iter<N>/`, run `<eval_cmd>`, and read the
   new score off the last line.
4. **Keep or revert.** **Keep** if the metric improves per `<objective>` (if the eval is stochastic,
   require a small margin so noise alone does not drive a keep); otherwise **revert** `<prompt_file>`
   to the previous best snapshot. Append `{edit, score, feedback}` to the history either way.
5. **Escape local optima.** If the score has not improved for a couple of iterations, stop making tiny
   tweaks — branch from an earlier high-scoring snapshot, or try a bolder restructuring (a different
   decomposition, a fresh set of examples). Diversity beats grinding the same local hill.

When stopping, restore the **best** prompt to `<prompt_file>` and report the score trajectory, which
edits moved the metric (and which did not), and the final prompt.

## Ledger

`<sandbox_root>/ledger.tsv`, tab-separated, never commas in the text. Header:
```
iter	score	status	edit
```
`status` ∈ {`baseline`, `keep`, `revert`}. Example (metric = task accuracy, maximize):
```
iter	score	status	edit
0	0.42	baseline	original prompt
1	0.61	keep	specificity: define each output label and the exact output format
2	0.61	revert	examples: add 3 few-shot demos — no metric gain
3	0.78	keep	context: add the domain rules the task assumes but never states
```
Report the **best** iteration, not necessarily the last.

## Constraints
- **The metric is the user's.** Never edit `<eval_cmd>`, its data, or its scoring — that games the
  number instead of improving the prompt, and the eval is the only ground truth the loop has.
- **Optimize the prompt only, and preserve the task's intent.** Improve *how* the task is instructed,
  not *what* is being asked; do not tailor the prompt to exploit eval quirks that would break real use.
- **One edit per iteration**, and compare the *metric* by re-running the full `<eval_cmd>`, not a single
  sample, so each score delta is attributable to that one edit.
- **Report the best variant, not the last.** The sandbox is self-contained — no `../` escapes.
- Do not pause the loop to ask whether to continue; run until target, plateau, or budget.

## Stops
- **Target** — the score reaches `<target>` (if set).
- **Plateau** — no iteration improved the best for `<patience>` consecutive rounds (every non-improving
  iteration counts toward patience; a keep resets it).
- **Budget** — `<budget>` iterations reached.

© gaasher · MIT · gaasher/Agent-Loop-Skills

Похожие скиллы

Все скиллы по теме «ИИ и ML» →
skill-optimizer mcollina Скилл skill-optimizer для Claude Code помогает настроить инструкции других скиллов и проверить, как модели им следуют. Запускается при правке скилл-паков, разборе регрессий и подготовке критериев выпуска. CX Codex +1 1 400установок prompt-optimizer getsentry Скилл prompt-optimizer для Claude Code переписывает системные и агентские промпты по тестовым случаям вместо вкуса. Стабилизирует нестабильное поведение промпта через эвалы и итеративную оптимизацию. CX Codex +1 2 500установок skill-autoresearch akillness Скилл skill-autoresearch прогоняет правки скиллов, промптов и SOP через замороженный локальный бенчмарк: одна правка за прогон, затем оставить или откатить. CX Codex +1 323установок llm-application-dev-prompt-optimize sickn33 Скилл llm-application-dev-prompt-optimize переводит черновые инструкции в готовые промпты через цепочки рассуждений и проверки на регрессию. Помогает контролировать задержку и стоимость ответов модели. CX Codex +1 1установок dspy-optimize-anything OmidZamani Скилл dspy-optimize-anything настраивает эволюционную оптимизацию текстовых артефактов через библиотеку GEPA. Подходит для улучшения кода, промптов, архитектур агентов и SVG с опорой на диагностику. CX Codex +1 ★ 125звёзд репо prompt-engineer-toolkit borghei Скилл prompt-engineer-toolkit для Claude Code проверяет производственные промпты и оценивает результаты тестов. Он помогает сравнивать версии, искать регрессии и проверять изменения перед выпуском. CX Codex +1 106установок

Из того же набора26

Весь набор →
literature-search Скилл literature-search ищет научные статьи через Semantic Scholar и arXiv, обходит граф цитирований и достаёт полные тексты без внешних библиотек. CX Codex +1 ★ 185звёзд репо data-analysis Скилл data-analysis исследует набор данных через проверяемые гипотезы и собирает отчёт с подтверждёнными числами. Запускайте его для открытого анализа, а не для поиска причины уже известной ошибки. CX Codex +1 ★ 185звёзд репо red-team Скилл red-team находит слабые места в фильтрах контента, классификаторах и API методом состязательного тестирования — генерирует атакующие вводы и собирает каталог отказов. CX Codex +1 ★ 185звёзд репо anomaly-investigation Скилл anomaly-investigation ищет причину уже замеченного скачка, падения или выброса в данных. Он проверяет версии по очереди и фиксирует подтверждение в журнале расследования. CX Codex +1 ★ 185звёзд репо power-analysis Скилл power-analysis для Claude Code рассчитывает размер выборки для двухгруппового сравнения и помогает подготовить пререгистрацию. Включается при планировании A/B-теста, простого RCT или оценки двух моделей до сбора данных. CX Codex +1 ★ 185звёзд репо claim-verify Скилл claim-verify проверяет числовые утверждения из черновика отчёта по исходным данным. Находит расхождения, тестирует выводы на выбросы и уточняет формулировки перед публикацией. CX Codex +1 ★ 185звёзд репо literature-survey Скилл literature-survey для Claude Code строит обзор исследований в виде матрицы источников и утверждений. Он подключается для поиска согласий, противоречий и пробелов по вопросу. CX Codex +1 ★ 185звёзд репо optimize-loop Скилл optimize-loop гоняет цикл правок с жёстким гейтом корректности и метрикой, которую надо снизить: рефакторинг модуля под зелёные тесты или ускорение SQL-запроса с тем же набором строк. CX Codex +1 ★ 185звёзд репо

Спонсоры проекта

Компании, которые помогают держать аналитику открытой