Prompt and Context Engineering
Keep long-running session context lean and on track (compaction, tool-result clearing, subagents, memory, fresh sessions), revise prompts to close gaps that regression evals expose, enforce structured output with defensive parsing, and ground answers in documents with citations.
- Context Management for Long-Running Sessions: compaction, tool-output pruning, subagent isolation, when to start a fresh session
- Prompt Revision: instruction clarity, system vs user placement, zero-, single-, or multi-shot examples, output constraints, input sanitization
- Structured Output and Defensive Parsing: strict schemas, validation, defensive parsing
- Grounding and Source Citation: answering 'not found'; full context vs retrieval
Domain overview
Domain 6 makes up 15% of the CCDV-F exam (about 10 of 70 items) and covers four skills:
- Context Management for Long-Running Sessions: analyzing context bloat or drift and selecting the technique that restores intended behavior: compaction, tool-output pruning, subagent isolation, or starting a fresh session.
- Prompt Revision: revising a prompt to close the gap between intended and actual output that regression evals have exposed, and keeping it closed.
- Structured Output and Defensive Parsing: structured outputs with strict schemas, response validation, and defensive parsing of free text.
- Grounding and Source Citation: requests that stay grounded in the supplied documents, cite their sources, return "not found" when the documents do not contain the answer, and choosing between putting the full document set in context and retrieval.
Items often describe a symptom and ask which technique addresses the actual cause.
(Sources: CCDV-F Exam Guide, Domain 6; Claude Certification exam prep: CCDV-F Prep Course — Production-Grade Prompting, Agents & Tool Use)
Context management for long-running sessions
Bloat, drift, and context rot
Context is everything Claude sees in a turn: system prompt, history, tool definitions, tool results, files, thinking. You pay for it on every request, and when the window is full the request fails. Context rot sets in before you hit the ceiling: the more tokens, the worse the model recalls details buried deep inside, and the higher the prefill latency. The goal is not to cram everything in but to put in exactly what is needed.
The toolkit
| Tool | Acts on | Trade-off | Solves |
|---|---|---|---|
| Just-in-time context | What gets loaded | Extra tool calls | Not preloading what isn't needed yet |
| Compaction | The whole conversation | Lossy summary; rare details can be lost | Any kind of bloat within a session |
| Tool-result clearing | Old tool results | Must call the tool again if the data is needed again | Bloat from tool output |
| Memory tool | External, cross-session storage | Costs tool calls; only as good as what the agent chooses to write | Keeping knowledge across sessions |
| Subagent | Its own context for a subtask | Only gets a summary back | Isolating noisy exploration |
Server-side compaction summarizes older turns into a single block when input exceeds a threshold:
client.beta.messages.create(
betas=["compact-2026-01-12"], model="claude-opus-5", max_tokens=1024,
context_management={"edits": [{"type": "compact_20260112"}]},
messages=messages)
The default trigger is 150K tokens (minimum 50K). instructions replaces the default summarization prompt, so use it to keep what the agent needs (architecture decisions, open questions, specific numbers). There is also pause_after_compaction.
Context editing (clear_tool_uses_20250919, beta context-management-2025-06-27) replaces old tool results with a placeholder but keeps the tool_use record, so the model knows it called the tool. Parameters: trigger (default 100K), keep (default 3 tool uses), clear_at_least, exclude_tools, clear_tool_inputs. Each clearing breaks the prompt cache, so clear rarely and clear a lot each time (clear_at_least). Anthropic's measurements: on short sessions, context editing increased cost by 73%; on long sessions, compaction cut cost by 32% and pruning by 39%.
Client-side pruning (replacing search results longer than 2,000 characters with a one-line excerpt at task boundaries) must not be used on Claude Fable 5.x, Opus 5.5, Sonnet 5.5, Haiku 5.5. On models with preserved thinking, editing an old tool result invalidates every later thinking block and the request may fail. Use server-side compaction or context editing instead. For the same reason: pass thinking blocks back unchanged and don't edit earlier turns.
The memory tool (memory_20250818) lets Claude read and write a memory directory through tool calls (view, create, str_replace, insert, delete, rename). You implement the storage backend yourself. When you combine it with clearing, set exclude_tools: ["memory"] so the agent doesn't lose track of what it just wrote. You need to control sensitive data, stale memories, and path traversal.
| Workload characteristic… | Try first | Watch for |
|---|---|---|
| Sessions spanning several days | Memory tool | Stale memories when facts change |
| Large tool results that can be fetched again | Clearing | Agent re-reading exactly what was just cleared |
| Context is mostly conversation | Compaction | Specific numbers lost in the summary |
| Tool results that are hard to retrieve again (ephemeral APIs, uploads) | Compaction instead of clearing | Fidelity of the summary |
| Sessions that always stay far from the ceiling | Skip compaction | Unnecessary loss |
Subagent isolation
A subagent runs in its own context window and returns only a summary to the main thread: the main thread records only the question and the answer, not the 15 files that were read. Decision rule: does the intermediate work matter to the main thread? If not (research, codebase exploration, code review with fresh eyes, work that needs its own system prompt), delegate it to a subagent. Anti-patterns: "expert" subagents that only change the persona name, sequential pipelines where each step depends on the previous step's findings (information is lost in the handoff), and test-running subagents that only report "tests failed", losing the output needed for debugging.
When to start a fresh session
- Switching to a new task: use
/clearinstead of dragging the old conversation along, to avoid bias. If you are continuing the same feature, use/compact. Anything that must be remembered across sessions goes in CLAUDE.md. - Session has drifted: starting a fresh session with a clearer prompt is often faster than steering the old one.
- Review: a fresh session or a subagent has no "stake" in how the code was written, so it catches errors better.
- Tasks spanning many context windows: compaction is not enough. An effective harness uses an initializer agent to create a feature list,
claude-progress.txt, a startup script, and an initial git commit. Each later session works on one feature, commits with a description, and updates the progress file. A new session starts by reading the progress file and git log, then runs a basic end-to-end test.
Exam trap
"The agent works for hours, so turning on compaction is enough" is wrong. Compaction is lossy, and the agent can still try to do too much at once or declare completion early. You need durable state outside the context (feature list, progress file, git) so a new session can pick up where the work left off.
Key point
Compaction compresses the whole conversation. Clearing removes only tool results (keeping the tool-call record). Memory moves information outside the window. Subagents isolate exploration. Client-side pruning is not allowed on models with preserved thinking.
(Sources: Anthropic Academy: Claude Platform 101 — Context management; Claude Cookbooks: Tool use — Context Engineering for AI Agents: Memory vs. Compaction vs. Tool Clearing; Claude Docs: Optimizing for cost and intelligence; Anthropic Academy: Introduction to subagents — Using subagents effectively; Anthropic Academy: Claude Code 101 — Context management; Anthropic Engineering: Effective harnesses for long-running agents)
Prompt revision
Standard process: an eval exposes a gap, you diagnose the cause in the prompt, make one change, rerun the full eval (not just the failing cases), then add the failing cases to the suite and gate merges with a smoke eval. "Keeping it closed" means the fixed gap becomes a regression test.
Clear, specific, structured
- Clear and direct: the first sentence starts with an action verb that states the task directly. In the course example this raised the eval score from 2.32 to 3.92. Specific: adding guidance on output qualities and steps raised it further to 7.86.
- The colleague test: if you hand the prompt to a colleague who has never seen the application and they are confused, Claude will be too. Add three parts: context (what the output is for, where it goes, who reads it), output format (length, Markdown or not), constraints (what must be kept or left out). Write context as facts, and format and constraints as instructions with the reason. Before polishing the wording, supply the missing facts.
- XML tags separate data from instructions (
<document>,<transcript>). You can ask for output inside tags (<thinking>,<final_answer>) so it is easy to extract.
System or user placement
- System prompt: role and general background that apply to the whole conversation.
- User turn: data and the specific task. With long documents, put the documents first and the instructions and question after them.
- Don't put your own instructions in a tool result: Claude treats tool content as untrusted data and may ignore it. Send instructions in a user turn after the
tool_result, or use a mid-conversation system message on models that support it (this also preserves the cache).
Zero-, one-, and multi-shot
Examples help most for corner cases, complex formats, tone, and ambiguous input. Wrap examples in <sample_input>/<ideal_output>, explain why the output is ideal, pick them from the highest-scoring eval outputs, and include the cases that often fail. Use multi-shot when you need to cover several kinds of edge case.
Output constraints and edge cases
- Spell out how to handle missing data, for example return the JSON
{"status": "INSUFFICIENT_DATA"}instead of letting the model make things up. The Evals course shows that adding a rule for reports with no risk section (returnnull) took Haiku 4.5 from 84% to 100%. - Prefill has been removed: Claude 4.6 and later return 400 if the request ends with a prefilled assistant message. Replace it with structured outputs (
output_config.format) or instructions in the system prompt.
Input sanitization
- Harmlessness screen: use a lightweight model (Claude Haiku 5.5) with structured outputs to classify input before it reaches the main flow. If the screen returns
stop_reason: "refusal", there is no verdict; treat the input as suspicious. - Input validation: filter known injection patterns.
- Third-party content goes only in
tool_result, never in the system prompt or the user's text. State where the content came from, JSON-encode untrusted strings so an attacker cannot "close the tag" and break out, screen tool output too, and apply least privilege.
| Gap the eval exposes | Preferred fix |
|---|---|
| Generic output, missing points | Add context, constraints, and specific guidance |
| Fails on a group of hard cases (sarcasm, missing sections) | Multi-shot examples for exactly that group, with explanations |
| Model makes things up when data is missing | Explicit rule for the missing case: null or INSUFFICIENT_DATA |
| Format breaks the parser | Structured outputs instead of asking for "JSON only" |
| Follows instructions embedded in documents | Put the content in tool_result, JSON-encode it, screen it |
Scenario example
A dental app sends appointment reminder texts, but Claude returns Markdown (** shows up raw on phones), sensitive procedure names appear on the lock screen, and "[phone number]" is left blank. The right fix is to add context (this is an SMS, nobody reviews it, other people may see the lock screen), format (plain text, short), and constraints (don't name procedures, no medical advice), plus the real facts (clinic name, phone number). Switching to a stronger model cannot add facts that are missing.
Exam trap
"Add examples to the system prompt and fix it straight in production" is not enough. You must rerun the full eval to make sure the fix doesn't break other cases, and add the failing cases to the suite so the gap doesn't reopen.
(Sources: Anthropic Academy: Building with the Claude API — Structured data, Being clear and direct, Being specific, Structure with XML tags, Providing examples; Anthropic Academy tutorial: Write a prompt your app can ship; Anthropic Courses (GitHub): Real world prompting; Claude Docs: Claude API errors; Claude Docs: Mitigate jailbreaks and prompt injections)
Structured output and defensive parsing
Two schema-enforcement mechanisms
resp = client.messages.create(
model="claude-haiku-5-5", max_tokens=1024, messages=msgs,
output_config={"format": {"type": "json_schema", "schema": Invoice.model_json_schema()}})
- Structured outputs (
output_config.format): the response is only JSON that matches the schema, with no preamble and no retries for parse errors. The first request with a new schema is slower because the API compiles the schema into a grammar; grammars are cached for 24 hours after last use. Keep schemas stable. Changing the output format also breaks the prompt cache. - Strict tool use (
"strict": truenext toname,input_schema): tool call inputs match the schema thanks to grammar-constrained sampling. Every object must have"additionalProperties": false. Generate the schema from the validator (Pydanticmodel_json_schema(), Zod) so schema and validator never drift apart. In the Meridian example, the validator rejected 79/100 tool calls with strict off and a hand-written schema, and none with strict on and a generated schema.
Limits to remember
| Limit | Consequence |
|---|---|
minimum, maximum, minLength, maxLength |
400 error: check them in the validator and state the constraint in the description |
Up to 20 strict tools, 24 optional parameters, 16 anyOf/type-array parameters per request |
Counted across the whole request (nullable fields generate anyOf) |
| PHI | Don't put it in property names, enum, const, pattern |
tool_choice any/tool |
400 error on Fable 5.1/5.2, Opus 5.5, Sonnet 5.5: leave it at auto |
| Output can still deviate from the schema | On refusal, on truncation at max_tokens, when enum strings change case |
Key point
A strict schema does not replace validation. Always check stop_reason (refusal, max_tokens), validate with the same Pydantic or Zod class, and allow null for facts the input doesn't contain. Strict mode only enforces shape; it cannot create facts the request never supplied.
Defensive parsing of free text
When you must accept free text (for example, you need citations, which can't be combined with structured outputs), ask for clear delimiters and parse with checks:
m = re.search(r"<answer>(.*?)</answer>", text, re.S) # or between ```json and ```
if resp.stop_reason != "end_turn" or not m:
return fallback() # don't guess
data = Invoice.model_validate_json(m.group(1)) # on error, retry or route to a human reviewer
Never eval() model output. If validation fails, retry a bounded number of times or route to a human reviewer; don't let broken data flow downstream.
Exam trap
"Add 'return only valid JSON' to the prompt" does not protect downstream code. The strongest answer is usually structured outputs (or strict tool use) plus validation and stop_reason handling.
(Sources: Anthropic Academy: Tool use with the Messages API — Strict tool use; Claude Cookbooks: Latency Optimization on the Claude API; Claude Cookbooks: Misc)
Grounding and source citation
Building a grounded request
- Put the documents in tags at the top of the prompt and the question at the end. Instruction: use only the information in the documents, not general knowledge.
- Allow "I don't know" with a fixed sentence, for example "Not found in the documents", so the application can detect it.
- Long documents (> 20k tokens): ask the model to extract verbatim quotes first and then answer based on those quotes. If no relevant quote is found, it should say so.
- Cite and retract: every claim must have a citation; if none can be found, retract the claim.
Citations API
- Set
citations: {"enabled": true}on all documents or none in a request. - Plain text and PDFs are chunked into sentences. Text returns character indexes (0-indexed, end exclusive). PDFs return page numbers (1-indexed). Custom content uses the blocks you supply as-is, with no further chunking, and returns block indexes.
cited_textdoes not count toward output tokens (nor toward input when sent back).titleandcontextare passed to the model but are not cited.- You can cache documents with
cache_control. - Combining citations with
output_config.formatreturns a 400 error. A prompt that only asks for JSON still runs, but may return almost no citations. If you need structured data with citations: ask for one field per line asname: value, parse it in code, and check that each field has a value and at least one citation, because the API does not guarantee this. - For RAG, return
search_resultblocks (source,title,content) from a tool or in the user message. Search result citations are off by default, and every search result in a request must use the same setting. Citations returnsearch_result_locationwithsearch_result_index.
Full context or retrieval
| Criterion | Full set in context (cached) | Retrieval (RAG / tool) |
|---|---|---|
| Size | Under about 200,000 tokens (about 500 pages) | Larger than the window, or too costly |
| Cost and latency | Caching cuts latency by more than 2× and cost by up to 90% | Pay only for the relevant passages |
| Freshness | Every content change rewrites the prefix | Fetches the latest version at query time |
| How often it's needed | Most requests need it | Rarely needed; put it behind a tool (just-in-time) |
For RAG: chunk, combine embeddings and BM25, fuse the rankings, take the top-K. Contextual Retrieval (adding context to each chunk before indexing) cuts failed retrievals by 49% (5.7% → 2.9%), and by 67% with reranking (→ 1.9%). The one-time cost is $1.02 per million document tokens thanks to prompt caching. Data tables that need calculation should be uploaded through the Files API and handled with code execution instead of pasted into the prompt.
Scenario example
An HR policy assistant has 120 pages of rules (under 200K tokens), updated quarterly, and nearly every question needs them. The sensible approach is to put the whole set in the prompt with a cache breakpoint at the end of the documents, enable citations, and allow the answer "Not found in the documents". By contrast, a library of 40,000 support articles that changes daily needs retrieval through a tool that returns search_result blocks, because the whole set doesn't fit in the window and freshness matters more than caching.
Key point
Grounding has four pieces: documents in tags placed before the question, an instruction to use only the documents, a "not found" escape hatch, and verifiable citations. Citations can't be combined with structured outputs.
(Sources: Claude Docs: Citations; Claude Docs: Search results; Claude Docs: Reduce hallucinations; Anthropic Engineering: Contextual retrieval in AI systems; Anthropic Academy: Claude Platform 101 — Context management)
Quick summary
- Context is everything Claude sees. A full window makes requests fail, and context rot sets in even before it fills.
- Compaction (
compact_20260112, default trigger 150K, minimum 50K) compresses the whole conversation.instructionsreplaces the default summarization prompt. - Context editing with
clear_tool_usesreplaces old tool results and keeps thetool_userecord. Each clearing breaks the cache, so clear in batches withclear_at_least. - No client-side pruning on Fable 5.x, Opus 5.5, Sonnet 5.5, Haiku 5.5. Pass thinking blocks back unchanged.
- The memory tool persists across sessions; you implement the backend. Use
exclude_tools: ["memory"]when combining it with clearing. - Use a subagent when the intermediate work doesn't matter to the main thread. Avoid "expert" subagents, sequential pipelines, and test-running subagents.
- New task:
/clear; same feature:/compact. Multi-session tasks need a feature list, a progress file, and git, because compaction is not enough. - Prompt revision: context, format, and constraints with reasons. XML-wrapped examples with explanations. Rerun the full eval and add failing cases to the suite.
- Don't put your own instructions in tool results. Untrusted content goes only in
tool_result, JSON-encoded. - Prefill returns 400 from Claude 4.6 on. Replace it with structured outputs or system instructions.
output_config.formatjson_schema, orstrict: truewithadditionalProperties: false. Generate schemas from Pydantic/Zod.- Schemas don't support min/max/minLength/maxLength. You must still validate because of refusals,
max_tokens, and enum case changes. - Citations are enabled on all documents or none.
cited_textcosts no tokens. Combining them with structured outputs returns 400, so use one field per line and parse. - Under about 200K tokens and needed often: put the full documents in the prompt with caching. Large, fast-changing, or rarely needed: use retrieval. Contextual Retrieval cuts failed retrievals by 49% (67% with reranking).