Repository navigation
Prompts and Context Budgets
Checked against v0.7.6 on November 13, 2026.
This page covers how a prompt becomes a model call, how the reply is validated, what happens when validation fails, how much context each tier gets, and which switch turns thinking off on which backend. It is for people who change prompts, schemas or the LLM client. For the process layout, see Architecture overview.
Kestrel never sends anything to a third party on the user's behalf, and that includes model calls. A hosted backend is reachable only through the opt-in paths described in kestrel/llm/client.py (LLMClient.complete): an operator-confirmed Tier 3 escalation, or Hosted mode after the operator has acknowledged the disclosure.
Every prompt is a Markdown file in kestrel/llm/prompts/, named after its version string with the slash turned into a dot (triage/v2 is triage.v2.md). kestrel/llm/prompts.py loads it by version and never from inline strings.
A file has YAML front matter, then a ## SYSTEM section and a ## USER section:
---
id: P1
version: triage/v2
tier: tier1
temperature: 0.0
max_tokens: 300
repair_max_tokens: 600
---
## SYSTEM
{GLOBAL_RULES}
...
## USER
{PROFILE_COMPACT}
...
load_prompt() returns a PromptSpec with the id, version, tier, temperature, max_tokens, system and user text, the Pydantic model for the reply, and two optional hints. reasoning is a hint for hosted reasoning models (resume_assess, resume_outline, resume_role, variant_suggest, interview_questions, title_suggest and org_summary set it). repair_max_tokens is the output budget for the repair call after a looping reply. {GLOBAL_RULES} in the system text is replaced with _global_rules.md, which tells the model to return one JSON object, never invent a field, and express doubt through the confidence fields.
The registry is SCHEMA_BY_VERSION in kestrel/llm/schemas.py. It maps 40 version strings to Pydantic models, and PromptSpec.model_cls comes from it. A prompt file with no entry there has no schema and cannot run.
| ID | Version | Tier | max_tokens |
|---|---|---|---|
| P1, P1C |
triage/v2, triage_consulting/v2
|
tier1 | 300, 350 |
| P2, P2C |
evaluate/v3, evaluate_consulting/v3
|
tier2 | 4000 |
| P3 | doc_select/v1 |
docsel | 1500 |
| P4, P4C |
cover/v3, engagement_outline/v3
|
tier3 | 1200, 2500 |
| P5, P6, P11 |
research/v1, contacts/v1, negotiate/v1
|
tier3 | 2000, 2000, 2500 |
| P7a, P7b, P7c |
resume_outline/v1, resume_role/v1, variant_suggest/v1
|
docsel | 3000, 3000, 1500 |
| P8, P9, P12, P13 |
story_consolidate/v1, mock_critique/v1, analytics_summary/v1, resume_assess/v1
|
tier2 | 3000, 1500, 1200, 2500 |
| P10 | trigger_classify/v1 |
trigger | 600 |
| P14, P15, P16 |
interview_questions/v1, title_suggest/v1, org_summary/v1
|
tier2 | 2500, 1500, 900 |
| P17 | follow_up/v1 |
tier3 | 800 |
P14 writes the likely interview questions when a role is marked Applied, P15 proposes target titles for the operator to accept or dismiss, P16 writes the sourced company summary, and P17 drafts a follow-up note for the operator to review and copy. P4 writes a cover letter or engagement outline in the first person (cover/v3 and engagement_outline/v3). The older versions stay in the registry for stored rows. The callers read the current version from a small map: pipeline/tier1.py and pipeline/tier2.py hold {"employment": "triage/v2", ...} and {"employment": "evaluate/v2", ...} for both tracks.
The registry also keeps three v1 entries whose files are still shipped: triage/v1, triage_consulting/v1 and evaluate/v1. They are no longer called by the pipeline. The comment in kestrel/llm/schemas.py says they stay runnable so Model check can compare a model against the version before the current one, and because an older evaluation row names its prompt version. evaluate_consulting/v1 is not kept: P2C v2 added a required field the old output lacks.
The max_tokens values come from each file's front matter. The prompt's own value wins over the tier default in settings.yml. Under Hosted mode the tier's configured budget acts as a floor beneath the prompt's (LLMClient.complete).
PROMPTS.md in the repository describes every prompt and schema in prose. If it disagrees with the prompt files, the spec wins by project rule, but check the code first and fix whichever is wrong.
PROMPTS.md requires a version bump for any change to prompt text. Add foo.v2.md, register "foo/v2" in SCHEMA_BY_VERSION, and point the caller at the new version. Leave the v1 file alone so older evaluations still name a prompt that exists. There is no separate PROMPT_VERSIONS table.
kestrel/pipeline/context.py fills the {placeholders} in the user template. render_user() handles {if COND:} section markers and the per-signal loop, then substitutes values. build_tier1_values() and build_tier2_values() produce the maps for the triage and evaluation prompts. The pieces that matter for size are:
-
profile_compact()andprofile_full(), which render the operator's profile for Tier 1 and Tier 2. -
few_shot_block(), which renders the prior-evaluations block (see below). -
comp_intel_summary(), which returns a corpus line only when at least five observations exist (_MIN_COMP_CORPUS = 5) and always statesn. -
normalize_description(), which collapses whitespace runs and blank-line runs before slicing. It never removes or reorders words.
kestrel/llm/guard.py is the only way a prompt's reply reaches the rest of the system. Three rules from CLAUDE.md govern it: structured output or failure, never regex-parse a response, never crash a run on a parse failure.
json_schema_for() builds the request schema from the Pydantic model and normalize_schema() makes it safe for constrained decoding. It removes title and default, unwraps a single-element allOf, and turns ["X","null"] or anyOf: [X, null] into plain X with the field dropped from required. Hosted strict endpoints get a second pass, strict_schema(), which marks every property required and sets additionalProperties: false. Array bounds (minItems, maxItems) are stripped for every hosted request except OpenRouter models whose ids start with openai/ or google/ (keeps_array_bounds()), because Anthropic models reject them with HTTP 400.
Bounds the grammar cannot enforce are applied after parsing. In kestrel/llm/schemas.py, _truncate(n) shortens an over-long string and _clamp(lo, hi) pulls a number into range, and _cap(n) and _dedupe_cap trim lists. Over-long values are cut, not rejected, so a wordy reply does not cost a repair call.
The JSON mode depends on the backend (request_json_mode() and build_request_body()):
| Mode | Request | Reply parsing |
|---|---|---|
schema |
response_format of type json_schema
|
Strict: the reply must be the object alone |
json_object |
response_format of type json_object, schema appended to the system message |
Strict |
prompt |
No response_format, schema and a "reply with only that JSON object" rule in the system message |
Lenient: outermost braces are located |
The Responses and Messages protocols always count as schema for this purpose. The leniency in extract_json() is a defensive locate for stray prose, never field parsing. The repair attempt is always lenient.
Thinking spans (<think> or <thinking>) are stripped from every reply before parsing, whatever the backend claims to do.
P3 is the one prompt that cannot use the default schema. run_guarded() raises ValueError if asked to run P3DocSelect without an explicit schema. run_doc_select() builds a schema per document master through build_doc_select_schema() in kestrel/llm/docselect.py, giving every slot an explicit enum of its real variant keys, plus "hide" for optional slots. A hallucinated variant key is then impossible to emit on a backend with a grammar. On a backend without one, validate_doc_selection() checks the reply against the live catalog and a bad key becomes a failed result, never a silent default. Empty enums are refused at build time because they would make the grammar unsatisfiable.
This is hard rule 2 in CLAUDE.md: the model selects, it never invents. Every bullet that reaches a PDF is the operator's own text.
run_guarded() makes at most two model calls per prompt.
- The first call runs with the prompt's temperature and
max_tokens. If the reply parses and validates, the result is returned. - If it fails, one repair call runs at temperature 0. The conversation is the original messages, then the failed reply as an assistant turn, then a user turn quoting the error and asking for a single corrected JSON object.
- If the repair also fails, the call is quarantined:
GuardResult(ok=False, quarantined=True, repaired=True)with the raw reply and the error.
The function never raises past its caller. Failures fall into three groups:
| Failure | Result | What happens next |
|---|---|---|
| Invalid JSON or schema mismatch | One repair, then quarantine | Row in quarantine
|
Generation loop (one string repeated more than 20 times in one array, 60 for resume_* prompts) |
One repair that names the looping field, runs with reasoning off and at repair_max_tokens
|
Quarantine if it loops again |
Provider refusal, or cap hit inside the Messages protocol (ModelDeclined) |
No repair, quarantine at once | Row in quarantine
|
| Transport error (timeout, 5xx, refused connection) |
ok=False, quarantined=False
|
The worker retries the task |
A reply that stops at the output cap with the budget spent on reasoning gets one extra re-ask with reasoning off, when the provider takes that switch and the operator set no effort of their own (reasoning_exhausted() in kestrel/llm/client.py).
GuardResult.egressed records whether the payload reached the provider. Only a connect-phase failure counts as "never left". Tier 3 reads this field so a confirmed escalation is not re-sent.
make_quarantine_hook() in kestrel/pipeline/_shared.py adds a Quarantine row to the same SQLAlchemy session the handler commits, so the row and the stage change are atomic. The row holds the opportunity id, tier, model, the full prompt (capped at 20,000 characters), the raw response (also capped), the error (capped at 4,000) and attempts=2. A hosted send that is refused before leaving the machine is also a quarantine row, with attempts=0. The UI lists these under Failed scoring (kestrel/web/pages/runs_detail.py).
Hard rule 4 says uncertainty escalates and never rejects.
- Tier 1 (
kestrel/pipeline/tier1.py): a quarantined call is promoted. The stage becomest1_pass, the verdictkeep,forced_byist1_quarantine_promoted, and a Tier 2 task is queued. A reply with confidence belowpipeline.tier1_min_confidence(0.6 insettings.yml) is forced tokeepand markedlow_confidence_forced_keep. - Tier 2 (
kestrel/pipeline/tier2.py): a quarantined call sets the stage toquarantinedand records the reason. A "Score again" on a role that already has a score keeps its earlier stage, and the failed attempt is tagged with a[score againprefix so Failed scoring can list it separately.
Ollama's OpenAI-compatible endpoint cannot set num_ctx per request, and the model default is far below what Kestrel sends. Overlong input is cut with no error. Kestrel therefore bakes the window into derived models named kestrel-<tier>, created from a Modelfile with PARAMETER num_ctx (kestrel/llm/profiles.py, kestrel/resources/config/models.yml). kestrel models build runs ollama create for each packaged Modelfile.
| Tier | num_ctx |
Default max_tokens
|
Notes |
|---|---|---|---|
| tier1 | 4096 | 300 | Head of the description, at most 1200 tokens |
| tier2 | 16384 | 4000 | Middle-elided description, at most max_jd_tokens (6000) |
| tier3 | 20480 | 6000 | Local model for the tier3-labeled prompts |
| docsel | 8192 | 1500 | No job description, only the slot catalog |
The trigger tier shares the kestrel-tier1 model. The same four numbers appear in models.yml under num_ctx, and load_catalog() refuses any hardware profile that sets a value below the shipped floor.
The Tier 3 escalation to a hosted frontier model is separate. It reuses the Tier 2 evaluation prompt against the frontier tier and sizes the description to the hosted model's own window through jd_budget() in kestrel/pipeline/_shared.py: the window, minus 6,000 tokens of prompt overhead and the output budget, less a 15% margin for tokenizer mismatch, clamped to the Hosted mode ceiling.
evaluate/v3 and evaluate_consulting/v3 add one placeholder, {OPERATOR_CORRECTIONS}, to the user template between the full profile and the few-shot examples. The system prompts and schemas are the v2 ones. The block is empty unless the operator has corrections that bear on this role (Learning loop internals), and with it empty the rendered prompt is the v2 prompt byte for byte, so adding the version moves no score. When present it is one block that states the operator's own facts, one quoted line per requirement. Each value is collapsed to a single line, double quotes become single quotes and braces become parentheses, so a note can never close the quotes, start a new line or name a template placeholder. At most 20 lines go in, newest first, with each requirement text and note cut to 200 characters, and the block stays within its own token allowance, dropping the oldest lines first. tests/test_prompt_budgets.py covers the block at its maximum size.
A local Tier 2 prompt is measured after it is rendered. If it is over what the tier's window holds (the preflight requirement, less the reply budget, the template overhead and a 3 percent margin kept free for the gap between cl100k_base and the local model's own tokenizer), the description is cut further, by what it actually holds rather than by its cap, and measured again. If the prompt is still over after the description is cut as far as it goes, because the profile, narrative and notes leave no room, it is not sent. handle_t2 in kestrel/pipeline/tier2.py records a refusal row in quarantine with the reason, attempts 0 because nothing was sent, and the role shows under Needs attention as "Too long for your local model". A role that already had a score keeps it. Retry scores the role once the profile is shorter or the model's window is larger. Ollama would otherwise cut an over-long prompt without an error and the score would be quietly wrong. Hosted tiers are sized by jd_budget() and do not take this path.
Token counts use cl100k_base through count_tokens in kestrel/ingest/tokens.py.
- Tier 1 keeps the head.
tier1_description()cuts atTIER1_HEAD_TOKENS(1200) and appends a truncation marker only when it actually cut. The marker's tokens come out of the 1200. - Tier 2 keeps both ends.
truncate_middle()splits the budget two thirds to the head and one third to the tail and puts an elision marker between them. Text that already fits is returned unchanged.
kestrel doctor compares each local derived model against a per-tier requirement in kestrel/doctor.py. required_num_ctx() is input_budget(tier) + max_tokens + 200. With shipped settings that works out to about 2,500 for tier1, 15,200 for tier2, 17,700 for tier3 and 5,700 for docsel. A single global threshold would be wrong, since tier1 has no reason to meet tier2's number. The doctor also runs a needle test: it fills the largest budget for each model, plants a random code at the top, and fails if the model cannot repeat it. Metadata can report a larger window than the model actually uses, so /api/show alone is not enough. A needle timeout is a warning, not a failure, because a cold model load looks the same as a short window.
Measured token tables are in docs/PROMPT_BUDGETS.md. It covers the fixture, before and after numbers for each trim, the max_jd_tokens values to set for 8,192-, 12,288- and 16,384-token windows, and the regeneration command. tests/test_prompt_budgets.py asserts that every rendered prompt leaves at least 25 percent of its window free.
Thinking is disabled per backend, and a wrong switch is silently ignored, so it shows up as a large token bill rather than an error. BackendConfig.thinking_control in kestrel/config.py selects the form, and build_request_body() applies it:
thinking_control |
Request field | Used for |
|---|---|---|
reasoning_effort |
reasoning_effort: "none" |
Ollama (the shipped local backend) |
chat_template_kwargs |
chat_template_kwargs: {"enable_thinking": false} |
oMLX and vLLM, added by the operator |
none |
nothing | Hosted backends, where effort is set separately |
Hosted providers differ in how they take the switch:
- OpenRouter:
hosted.reasoning_effortin settings is sent asreasoning: {effort}and always wins. Otherwise anonehint becomesreasoning: {effort: "none"}when the model's recorded capabilities say reasoning is optional, andreasoning: {enabled: false}when they do not. The second form is not verified to stop thinking, so the guard does not shrink a repair budget on its strength (_reasoning_off_verified()). - OpenAI direct:
reasoning_effortis sent for the o-series and gpt-5 families only, andtemperatureis dropped for them. - Anthropic direct: no sampling parameters are sent, and effort goes in
output_config.effortwhen it is a value the API accepts. - OpenModel Messages and Responses protocols: nothing is sent for thinking.
Hosted Tier 1 has its own default. With hosted.tier1_reasoning_off on, triage asks an OpenRouter reasoning model for no reasoning on the first attempt, but only when the model record proves it is allowed (default_reasoning_hint()).
kestrel doctor checks the local case two ways. The thinking probe sends reasoning_effort: "none" and warns if a <think span comes back. The schema probe sends a tiny json_schema request the same way the pipeline does and fails, as a blocking error, when the model ignores response_format and answers in prose.
Two Ollama environment variables also affect throughput. OLLAMA_NUM_PARALLEL must be at least the configured concurrency or requests serialize, and OLLAMA_KEEP_ALIVE should be generous so tier models are not reloaded between batches. Both are doctor checks.
Start here
Interfaces
Extending Kestrel
How it works
- Prompts and context budgets
- Document engine
- Learning loop internals
- Analytics internals
- Task queue and concurrency
- Database schema
Shipping and safety
- Packaging and releases
- Preflight and diagnostics
- Security and privacy model
- Outbound calls
- Benchmarking
Workarounds and Troubleshooting