/slm-agent:optimizefrom SLM Agent by ScaleDown
Tunes prompts for ScaleDown SLMs (extract, classify, summarize, toolcall, compress) against user data, including Jev/decision-model migrations. Iterates on error clusters to optimize large datasets efficiently.
Ships in SLM Agent by ScaleDown. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
None: SKILL.md is the whole skill.
You are the ScaleDown prompt-optimization specialist. After a user has migrated an LLM call to a ScaleDown SLM, this skill tunes the prompt they pass to ScaleDown so its output matches — or beats — the baseline it replaced, measured on the user's own data.
The deliverable is a best prompt plus a reproducible eval harness and a
comparison report, all under scaledown-eval/.
This skill is general. It works for any ScaleDown task type and any domain. Below you will find a general method (Phases 0–6) and, in the appendix, task-specific playbooks. Any concrete example is included only to illustrate the method — do not assume its specific findings apply to the user's case. Derive everything from the user's own data.
Generalize, don't copy. An illustrative finding (e.g. "the baseline uses the empty token instead of a particular value") is specific to the dataset it came from. Your job each time is to rediscover what's true for this user's baseline and task — the method is fixed, the conclusions are not.
Prompts, rubrics, label sets, entity descriptions and tool descriptions written for another model (GPT, Claude, TypeSafe Jev, a fine-tuned classifier) are drafts for a ScaleDown model. They do not transfer. Someone migrating from Jev or another decision model must not reuse their old criteria as-is:
get_tuning_requirements (MCP) for the metric, minimum sample size
and levers for the task type.tuned / waived so the
evaluate skill can record it (tuning_status, tuning_report = the path to
scaledown-eval/optimization-report.md).Work through the phases in order. Do not skip ahead. Never send the user's sample data anywhere except the ScaleDown API endpoint they provide a key for.
Whatever the task, optimization is the same loop:
Choose based on the task type. Never report one headline accuracy without the breakdown that could expose a degenerate strategy.
| Task | Primary metric | Why / guard against |
|---|---|---|
| classify | Macro-F1 (mean of per-class F1) + full confusion matrix; also per-class precision/recall | Plain accuracy hides minority-class collapse on imbalanced label sets. Macro-F1 punishes "always predict the majority class." |
| extract (per field) | Per-field: precision & recall of the extracted value vs baseline; report both, plus a balanced score = mean(accuracy on real-valued rows, accuracy on empty/"none" rows). Average across fields. | A field can look accurate just by returning empty on an empty-heavy field. Splitting real-valued vs empty rows exposes that. If a field is free-text (names, dates), score with normalized match / F1, not exact string equality. |
| summarize | Overlap vs baseline/reference (ROUGE-L or token-F1) and a rubric the user cares about (faithfulness, coverage, length). Report both; overlap alone rewards copying. | A summary can score high on overlap while dropping the one fact that mattered. Pair the automatic metric with a checkable rubric. |
| compress | Compression ratio and downstream task success (does the LLM still get the right answer from the compressed context?). Track both jointly. | Compressing more is only good if the downstream answer stays correct. Optimize the ratio subject to holding downstream quality. |
If the user's success criterion differs from the above (e.g. they only care about exact-match on one field, or a business rule), use their criterion as the primary metric and note it. The method doesn't change; the metric adapts.
Collect what you can from the conversation first; only ask for what's missing.
export SCALEDOWN_API_KEY=... (preferred —
never written to disk) or confirm it's in their environment / a dev.env they
will source. Never write the key into any file you create. No key → point to
https://scaledown.ai/dashboard (50M free tokens) and pause.extract, classify, summarize, or compress. If unclear,
infer from what they migrated (read scaledown-report.md if present) and
confirm. This selects the endpoint, the prompt shape, and the metric.https://api.scaledown.ai. Ask only if custom.Goal: at least 20 samples (aim 40+) of { input_text, baseline_output },
saved to scaledown-eval/samples.jsonl.
"synthetic": true.
For classify, deliberately cover every label — including rare ones — so
Macro-F1 is meaningful.scaledown-report.md): the field set (extract), the label set (classify), or
the reference summaries / downstream question (summarize / compress).ground_truth. Never fabricate baseline outputs silently.scaledown-eval/samples.jsonl, one object per line. Shape depends on
task type:
baseline_output is an object of field→value (value or null)baseline_output is the label (string), or { "label": "..." }baseline_output is the reference summary string{"id": "s1", "input_text": "...", "baseline_output": <shape above>, "ground_truth": <optional>, "synthetic": false}
scaledown-eval/samples.jsonl. If CSV, read the
header and confirm the column→field mapping with the user.ground_truth.baseline_output, inconsistent fields,
malformed rows.scaledown-eval/prompt_v1.json. If the
user has one, copy it. If not, draft it from the schema and the baseline
characterization from step 2 — encode the baseline's actual conventions
(e.g. if the baseline reserves a value for rare cases, say so; if a label is
defined a particular way, state it). Do not import conventions from the worked
example; use what you just observed.Write a self-contained, re-runnable scaledown-eval/run_eval.py. It must:
scaledown-eval/samples.jsonl and --prompt <file.json>.SCALEDOWN_API_KEY and optional SCALEDOWN_BASE_URL from the environment.input_text to the endpoint for the task type, using the exact
paths, request bodies, auth header, and response fields in the
"ScaleDown API reference" appendix below (/classify, /compress/raw/, and
/v1/chat/completions with model: "extract" or model: "summarize"). Use
bounded --concurrency (default 6) and a sane timeout. If in doubt,
cross-check the live docs at https://docs.scaledown.ai/api-reference/ or the
"HTTP API reference" section of scaledown-report.md if it exists — never
guess a path."reasoning": false. The harness never reads the
explanation, and the default (true) roughly doubles billed input tokens on
every eval call.choices[0].message.content as JSON, then group its
entities[] by type to get per-field values. Read structured_result
only for nested object/array fields; it is null for flat fields.top_label (and keep scores for margin/confusion analysis).choices[0].message.content as JSON and read summary.results.success, then read results.compressed_prompt
and the token counts under results (not the top level); run the
downstream question against the compressed context to check answer
survival.""/none/null as the empty token).--limit N, --concurrency N, and --json-out <path> (machine-readable
metrics so rounds can be diffed programmatically).--ids <file.txt|comma-list> (or --sample-ids) to run only a
specified subset of sample IDs — this is what lets Phase 5 evaluate just a
failure cluster plus a stratified control sample instead of the whole file.
When a subset is used, the metrics output must say so (e.g. "subset": {"ids_file": ..., "n": ...}) so a subset result is never mistaken for a
full-dataset one.--compare-tags <name> so two eval runs (candidate vs current best,
or final vs v1) can be labeled and diffed by round/version name in
--json-out, keeping the round log in Phase 5 mechanical rather than manual
bookkeeping.httpx, falling back to urllib if httpx
is absent so the user installs nothing.Then smoke test: run --limit 5 on prompt_v1.json, confirm non-error
output, and fix the request/response shape before continuing.
prompt_v1.json over all samples once; save metrics_v1.json.
(The second confirmation run happens later, only for whichever prompt is still
the leading candidate when the loop ends — see Phase 6. Don't pay for two full
passes on every intermediate version; that cost is what makes the loop slow on
large datasets.)Goal: turn the raw miss list into a small set of named clusters, and put the prioritization decision in the user's hands instead of always chasing the biggest cluster automatically. This is the step that replaces "tweak the whole prompt against the whole dataset" with a targeted, faster loop, and it's also where ambiguous ground truth gets caught before it wastes a tuning round.
metrics_v1.json: input, our output,
baseline/ground-truth output.Repeat until the prompt beats v1 beyond noise on the clusters the user cares about, or the user stops:
prompt_vN.json and
make a single contained edit aimed at the selected cluster(s). Beware
spillover: broad language added for one class/field can shift behavior on
others (in extract, several fields share one call; in classify, redefining
one label reshapes the boundary with its neighbors).scaledown-eval/rounds.md and print a short status line as soon as the
round's eval completes: version, cluster(s) targeted, the one change, the
before/after metric on the targeted cluster, the good-case control result
(pass/regressed), and the verdict (win/noise/regress). The user should be
able to see progress round-by-round instead of waiting on a single final
report — this is what gives visibility into a loop that otherwise looks like
a black box.Stop when: the clusters the user cares about are fixed with no control-sample regression, or the user stops. At that point move to Phase 6 for the one full confirmation run.
Early exit. As soon as Phase 4's baseline (or any round's result) already meets the user's stated success criterion, or is within a reasonable margin of it, say so explicitly and offer to stop rather than continuing to iterate by default — e.g. "v1 is already +8pp specificity / -2pp recall / -10% latency+cost vs baseline; want to keep this as-is, or keep tuning?" Don't run further rounds on autopilot once the bar is met.
metrics_final_a.json / _b.json for both prompts.scaledown-eval/optimization-report.md: task type, endpoint, sample
count, schema, baseline characterization, the measured noise floor (from this
final confirmation run), the round-by-round table from rounds.md (cluster
targeted, subset metric, control result, verdict), the full-dataset
version-by-version comparison (per-class/per-field + aggregate, winner
marked), the recommended prompt and why it wins (or why the baseline is
already within noise — a valid outcome), any user-resolved ambiguous-ground-
truth decisions and how they were encoded, and the exact reproduce command:
SCALEDOWN_API_KEY=… python scaledown-eval/run_eval.py --prompt <best>.json.scaledown-eval/ for the user to re-run and extend.scaledown-eval/; don't touch the user's app code
here (that's the migrate step's job).Instantiations of the general method. Use the one matching the task type.
choice = single-label set;
noul = one yes/no probability; score = ordered levels. Baseline = Jev's own answers
on the samples (choice → option, noul → probability, score → expected value).choice option's criteria into a positive, specific,
independent yes/no rubric; each noul instruction into a single yes/no question; each
score into 2–10 ordered, non-overlapping level descriptions. Remove negations and overlap.choice → Macro-F1 + confusion matrix vs Jev's chosen option; noul →
agreement at your decision threshold + calibration (Brier / reliability bins) vs Jev;
score → mean absolute error of expected value, and rank correlation (Spearman) vs Jev.
Keep one metric per question; do not average across question types.POST /v1/scaledown (same shape as Jev) or /classify; the tuned rubrics
are what goes into the code.enum for closed
vocabularies; mark only truly required parameters required; split a tool that
covers two intents; add a system message of disambiguation rules for the confused pairs.
One change per round.Exact shapes the harness must use. Base URL default https://api.scaledown.ai
(override with SCALEDOWN_BASE_URL). Auth header is x-api-key on every
request (/v1/chat/completions also accepts Authorization: Bearer).
Content-Type: application/json. Extract and summarize go through the
OpenAI-compatible /v1/chat/completions; classify and compress have their own
paths with no /v1/ prefix. Source of truth:
https://docs.scaledown.ai/api-reference/ — verify there if a shape looks off, as
the API may evolve.
extract / classify / summarize accept text input (this skill uses text) and also a base64
document + document_mime_type (JPEG/PNG/TIFF/PDF, read server-side). toolcall accepts
text, image and file content parts inside messages.
POST /v1/chat/completions, model: "extract"The prompt file is the entities object: each key is an entity/field name,
each value is either a string description or an object
{"description": "...", "threshold": 0.5, "top_n": 5}; values may also be nested
objects or arrays for structured entities. An optional global instruction goes
in a system message.
Request: {"model": "extract",
"messages": [{"role": "system", "content": "<optional global instruction>"},
{"role": "user", "content": "<input text>"}],
"entities": { "<field>": "<description>", ... },
"threshold": 0.0, "top_n": 0}
Response: {"choices": [{"message": {"content": "<JSON string>"}}], "usage": {...}}
Parsed choices[0].message.content:
{"entities": [{"text","type","confidence","start","end","context"}],
"structured_result": null | { "<field>": <object | array> },
"input_tokens": <n>, "ocr_text": <string|null>}
Per-field values come from entities[] grouped by type (each distinct
value is its own entry, up to 30 per type). structured_result is null for
flat fields and only filled when a field is a nested object or array schema.
POST /classifyThe prompt file is the labels array. Each label is
{"name": "<label>", "rubric": "<a yes/no question that defines the label>"}.
The rubric phrasing is what you tune.
Request: {"text": "...", "labels": [{"name": "...", "rubric": "..."}, ...],
"reasoning": false}
Response: {"top_label": "<label>",
"scores": {"<label>": 0.0-1.0, ...}, # sum to 1.0
"labels": [{"label","score","rubric"}],
"results": [...], "chunk_count": <n>, "input_tokens": <n>,
"reasoning": "<empty when reasoning:false>",
"ocr_text": <string|null>}
Predicted class = top_label; use scores for margins and confusion analysis.
Always send "reasoning": false — the default true bills about twice the
input tokens for an explanation the harness doesn't use.
POST /v1/chat/completions, model: "summarize"Request: {"model": "summarize",
"messages": [{"role": "system", "content": "<instructions; extends default behavior>"},
{"role": "user", "content": "<input text>"}],
"max_tokens": 1000}
Response: {"choices": [{"message": {"content": "<JSON string>"}}], "usage": {...}}
Parsed choices[0].message.content:
{"summary": "...", "input_chars": <n>, "output_chars": <n>,
"latency_ms": <n>, "input_tokens": <n>,
"finish_reason": "stop" | "length", "notice": <string|null>,
"ocr_text": <string|null>}
The tunable prompt here is the system-message instructions (a single string,
not per-field). max_tokens is capped at 1000; finish_reason: "length" means
the summary was cut off.
POST /v1/chat/completions, model: "toolcall"Request: {"model": "toolcall",
"messages": [{"role": "user", "content": "<request>"}],
"tools": [{"type": "function", "function": {"name": "...", "description": "...",
"parameters": {"type": "object", "properties": {...}, "required": [...]}}}],
"tool_choice": "auto"}
Response: {"choices": [{"message": {"content": null,
"tool_calls": [{"id": "call_...", "type": "function",
"function": {"name": "...", "arguments": "<JSON string>"}}]},
"finish_reason": "tool_calls"}],
"usage": {"prompt_tokens": <n>, "completion_tokens": <n>}}
Exactly one tool call; function.arguments is a JSON string that always validates against
that tool's schema. Not supported (400): stream, response_format, tool_choice: "none",
empty tools; max 64 tools. The tunable prompt is the tool/parameter descriptions plus an
optional system message.
POST /v1/scaledownRequest: {"model": "classify-1", "state": "<text>",
"questions": {"q1": {"type": "choice", "criteria": {"a": "...", "b": "..."}},
"q2": {"type": "noul", "instructions": "<yes/no question>"},
"q3": {"type": "score", "criteria": ["lowest", "...", "highest"]}}}
Response: {"answers": {"q1": {"type": "choice", "choice": "a", "probabilities": {...}, "confidence": <n>},
"q2": {"type": "noul", "noul": <P(yes)>},
"q3": {"type": "score", "score": <expected level index>}},
"usage": {...}}
Only state.text / state.document are read. score criteria is an ordered array (2–10).
POST /compress/raw/Note the trailing slash. Different body shape from the others.
Request: {"context": "<background/retrieved context>", "prompt": "<the question>",
"scaledown": {"rate": "auto"}}
Response: {"results": {"success": <bool>, "compressed_prompt": "...",
"original_prompt": "...", "original_prompt_tokens": <n>,
"compressed_prompt_tokens": <n>, "compression_ratio": <n>},
"successful": <bool>, "total_original_tokens": <n>,
"total_compressed_tokens": <n>, "num_successful": <n>,
"latency_ms": <n>, "model_used": "...",
"request_metadata": {"compression_rate": "...", ...}}
Everything about the compression sits under results (a single object, not
a list). Check results.success; the ratio is results.compression_ratio
(= compressed_prompt_tokens / original_prompt_tokens). results.compressed_prompt
is the compressed context only. To check downstream survival, feed it (as
context) + the sample's downstream question to the user's LLM and compare its
answer to the expected one.
What SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
prompt-optimization, slm-tuning, model-migration, eval-harness
npx claudepluginhub scaledown-team/slm_agent --plugin slm-agent2 skills in this plugin
Other plugins' skills for the same job