Model wanders off topic
The model evaluates evidence against the right question instead of drifting to whichever detail happened to sit near a boundary.
What the AI sees matters more than how you ask
The sequel to prompt engineering: managing what information goes into the model's window and how it's structured. Organised by the Write · Select · Compress · Isolate framework, with anti-pattern → done-right examples that tie into RAG (Dify) and agents (n8n).
This chapter shows how to shape the information presented to an AI so that it stays focused on the right question and avoids drift caused by irrelevant or stale data. By learning techniques such as hypothesis placement, session summarization, targeted retrieval, and strict one‑job prompts, readers will be able to construct lean, high‑signal contexts that keep models accurate across multi‑step workflows.
Context engineering is the sequel to prompt engineering: prompting is how you word the request; context engineering is what information the model sees and how it's organised. Most agent failures come from poor context, not a weak model. The four moves: Write what matters, Select the relevant, Compress the rest, Isolate the concerns.
Because the model’s output is driven by the relevance and structure of the data within its context window, so shaping that information determines how well it can answer.
The chapter shows anti‑pattern vs. correct patterns using Dify for retrieval‑augmented generation and n8n workflows for agent‑based processing, demonstrating real‑world applications.
What you put in the window
What does the 2023 Zhang paper say about CRISPR off-target effects?
Paste the paper text (or attach the PDF) and ask: "Using only this paper, summarize what it reports about off-target effects."
Be a helpful research assistant. —or— a 2-page list of every edge case and rule.
You are a research assistant for biology students. Be concise, define jargon on first use, prefer primary sources, and say when you are unsure.
Bury the actual task in the middle of three pages of pasted material.
Instruction at the top, the data clearly tagged in the middle, and restate the ask at the end: "Remember: answer only from the text above."
Pull in the right context (RAG)
Paste all 50 paper abstracts into one prompt and ask your question.
Put the 50 papers in a Dify knowledge base; let it retrieve the 3 most relevant chunks for each question and answer from those.
Send the whole 80-page protocol manual to answer one question about centrifuge settings.
Index the manual once; retrieve only the centrifuge section at query time.
Give your n8n AI agent 20 tools "just in case".
Give it the 3 it actually needs — search papers, fetch a paper, post to chat — each with a clear, distinct name.
Load the full content of every file into the context up front.
Give the agent file paths / IDs plus a "fetch" tool; it loads a file only when it actually needs it.
More signal, fewer tokens
Re-send the entire 60-message chat on every new turn.
Keep a running summary ("decisions made, open questions") and send that plus only the last few messages.
Paste a raw web page — nav bars, ads, cookie banners, HTML — into the prompt.
Extract just the article text first (an n8n node can do this), then send that.
"More context is always better" — stuff the window to the brim with everything that might help.
Keep only high-signal tokens. A focused 4k-token context often beats a sprawling 100k one.
Separate the concerns
One mega-prompt that extracts, filters, summarizes, and formats 20 papers at once.
Four n8n nodes — extract → filter → summarize → format — each with a small, focused context.
Try to keep every intermediate result inside the live conversation.
Write intermediate findings to a file / n8n static data / a DB row, and read them back only when needed.
Answer from memory, then scroll up to re-read anything you blank on.
A short paragraph that captures the essential facts of the current conversation so the LLM can recall them without excess tokens.
You will be able to produce a one‑paragraph summary that fits within a few hundred tokens and preserves key context for future turns.
session_summary.txt for use in the next prompt.A concise paragraph that captures decisions and evidence from a multi‑turn conversation.
Compress each exchange into a concise paragraph that can be fed back to the model for the next step
A prompt that starts with a clear hypothesis and then asks the model to confirm or refute it using supplied context.
You will craft a prompt that guides the LLM toward a specific answer while keeping the request narrow.
A filtered set of documents identified by their IDs or paths that are supplied as context to the model.
Fetch and supply just the relevant files so the model answers from that exact information slice
A targeted retrieval step that selects the minimal set of external files required for answering a specific question.
You will execute a focused search and feed just those results to the LLM, reducing token waste.
retrieved_context.txt for inclusion in the next prompt.A single‑sentence statement of the central question or hypothesis that frames the model’s evaluation.
Structure prompts so the model evaluates evidence against a specific hypothesis
A prompt that tells the model to perform exactly one task and return results in a predefined JSON schema.
You will produce a prompt that forces the LLM to generate only the required answer in a machine‑readable format.
{ "refund_deadline_days": number }.{ "refund_deadline_days": 30 }).20 outcomes in all — one per recipe below.
Model wanders off topic
The model evaluates evidence against the right question instead of drifting to whichever detail happened to sit near a boundary.
Chat history is overflowing
A tight, factual summary carries forward only the decisions and evidence that matter, cutting context rot that would degrade later answers.
One overloaded prompt trying to do everything
Cleaner outputs at each stage and no confusion from a single overloaded prompt trying to juggle four goals at once.
Guidance numbers seem off from the 10‑K
A precise, document-grounded comparison of what management said versus what actually happened, without the model paraphrasing from memory or confusing figures across periods.
When the AI keeps guessing your intent
The model reasons with your principles rather than guessing at intent, and you avoid the "lost in the middle" failure that buries the real rules in verbose instructions.
Need answers from specific code files
Faster, more accurate answers because the model works with the specific slice it needs, not a haystack of tangentially-related files.
Want a clean audit of each hiring stage
Each step is auditable and easier to correct; the screening result does not pollute the question-drafting context.
Too many runbook steps showing during an incident
The active window stays focused on the current step rather than flooded with procedures that don't apply to this incident.
Need a concise candidate overview
A candidate brief that references specific achievements and angles from the candidate's real background, making it useful for a hiring-committee prep rather than a boilerplate summary.
Email chain full of forwarded headers and duplicate text
The model's summary or draft reply is grounded in the real exchange rather than confused by three copies of the same disclaimer block.
Need consistent feedback without a sprawling rubric
Consistent, principle-driven feedback without the model getting lost inside a sprawling rubric where every rule competes for attention.
Need interview questions that reflect intake notes
Screening questions that match what the client actually said they need, rather than a recycled question bank that could apply to any similar role.
Need project coherence but don’t want to replay old chat
Long projects stay coherent without burning tokens replaying history; the log is also a useful audit trail.
A focused answer citing the exact guideline clause that applies, with no patient-identifying information in the prompt and no diagnostic or treatment decision made by the model.
Need a draft that only uses my research notes
Drafts that accurately reflect your actual findings instead of a generic treatment of the topic.
Need to draft a post but not publish yet
Each stage does one thing cleanly and there's no risk of an early step accidentally queuing a post before the draft is approved.
Report begins with filler numbers
Commentary that leads with the right numbers instead of fixating on an early-page figure that happened to be near the top of the context.
Can’t recall past budget choices
The model focuses on the new data, not on re-reading old discussions that settled last quarter.
Need a source‑cited data‑room summary for an investment memo
A draft memo grounded in the actual data-room documents, with every figure traceable to a named source, rather than a generic template populated with invented figures.
When old assumptions creep into a long task
The agent acts on current ground truth and doesn't waste steps (or make mistakes) based on a config value that changed three turns ago.
Need the exact words from a sales call
Follow-up emails and talk tracks address what the prospect actually said rather than a sanitised version that lost the nuance.
Need a quick, focused outreach hook
Outreach drafts that lead with the right hook instead of a generic opener that ignores the recent context.
Ticket threads full of quoted replies
Accurate routing and faster response drafts because the model reads the live issue, not the full thread history.
Only urgency and category tags, no reply draft
The draft step never second-guesses the triage decision; the triage step is not polluted by possible-reply options that bias its classification.
Web pages full of ads and navigation bars
Clean the input before the model ever sees it. Boilerplate dilutes the signal and burns tokens. Pre-cleaning means every token the model reads is relevant.
Too much context in prompt
More context is not always better — recall degrades as the window fills. As the number of tokens grows, the model's ability to accurately recall any single fact drops. Curate, don't hoard.
Chat history gets too long
Summarize the conversation instead of re-sending all of it. Long histories hit context limits and add noise. A running summary preserves what matters in a fraction of the tokens.
Keep the conversation tidy
Persist state outside the window instead of carrying everything in the chat. External memory keeps long, multi-step tasks coherent without bloating the live context window.
One huge prompt trying to handle many papers
Split a big task so each step (or n8n node) gets a clean, focused context. Each step gets a simple context and is independently debuggable — this is context engineering's version of prompt chaining.
Loading every file wastes space
Pass identifiers and let the agent fetch on demand. Pre-loading fills the window with material you may never use. Fetch-on-demand keeps the context lean and relevant.
Too many paper abstracts in a prompt
Pull the few relevant chunks instead of pasting everything. Dumping everything wastes tokens and buries the signal. Retrieval pulls only what is relevant to *this* question.
Agent swamped by tool choices
Give an agent the few tools it needs, not every tool you have. Too many tools create ambiguous decisions. If a human could not say which tool to use, the agent cannot either.
When my prompt is too detailed or too vague
Not a brittle 2-page rulebook, not a vague one-liner — a handful of strong heuristics. Over-specified prompts get brittle and hard to maintain; vague ones get generic. A few clear principles steer behavior without micromanaging.
Key instructions get lost in a long prompt
Models attend most to the start and end of the context — not the middle. Important instructions buried in a long middle get lost ("lost in the middle"). Anchor them at the edges.
Model can’t recall a specific paper
Don't ask the model to recall a specific paper from memory — put the actual text in front of it. A model cannot reliably recall one specific paper from training. Give it the real text and it answers from fact, not a fuzzy memory.
The same set on /recipes, filtered by tool and role.
Cole Medin on why context — not a bigger model — is what makes agents work, with RAG shown in practice.
A concrete framework for feeding an AI coding assistant the right context up front.
It is managing what information goes into the model's context window — what to include, what to retrieve, what to compress, and what to keep separate — so the model has exactly what it needs and little else.
Usually because of poor context, not a weak model: the key fact was missing, buried, or drowned in irrelevant text. Most agent failures trace back to what the model could see that turn, not its raw ability.
Retrieval-augmented generation: instead of hoping the model remembers, you fetch the relevant documents and put them in the context, so it answers from the actual text. It is the "Select" move of context engineering, and it is what tools like Dify do under the hood.
That is context rot. As the window fills with old turns and side-tracks, the signal-to-noise ratio drops and the model loses the thread. Summarise what matters, drop what does not, or start a fresh session with just the essentials.
No. More room helps, but quality still degrades as you fill it, and models reliably miss facts buried in the middle ("lost in the middle"). A big window is not a reason to dump everything in — selection and compression still pay off.
Near the start and the end of the context. Models attend least to the middle, so a critical instruction or fact stranded in the middle of a long prompt is the most likely thing to be ignored.
Agents are context engineering in motion: each step needs a clean, focused context, and good agent design isolates concerns so one step's clutter does not pollute the next. Retrieval nodes in n8n or Dify are the "Select" and "Compress" moves applied in a pipeline.
WriteSelectCompressIsolateContext windowRAGContext rotLost in the middleTokenAsk, share, or report — over on the Heidelberg AI community forum.