CONTENTS
CHAPTER 5

Prompting and Context Engineering

6 MIN READ

“Prompt engineering” got a bad reputation: magic phrases, “you are a world-class expert,” tipping the model $200. Most of those tricks were artifacts of weaker models and are now useless or harmful. What survived, and grew into a real discipline, is context engineering: deliberately designing everything the model sees so it can do the job.

5.1 The core principle

The model can only act on what’s in its context window, plus what it learned in training.

Every failure can be traced to one of three things:

  1. Capability: The model can’t do this, even with perfect context. (Use a stronger model, decompose the task, or change the approach.)
  2. Missing context: The model didn’t have information it needed. (Supply it.)
  3. Bad context: The context was ambiguous, contradictory, noisy, or misleading. (Fix it.)

In practice, problems 2 and 3 account for most failures with modern frontier models. When an output is wrong, your first question should be: “If I handed this exact context to a smart new colleague with no other information, could they do it?” Usually the answer is no.

5.2 The “brilliant new hire” mental model

Treat the model like a highly capable new employee on their first day. They’re smart and well-read, but they know nothing about your company, codebase, users, conventions, or what “good” looks like for this task.

A bad task brief: “Write a push notification for our app.”

A good brief tells them:

  • Who the audience is (lapsed users of a meditation app, ages 25–45).
  • Why we’re doing this (re-engagement after 14+ days inactive, without being guilt-trippy).
  • What good looks like (under 90 characters, warm, references their last session type, no exclamation marks).
  • What to avoid (streak shaming, fake urgency, emoji overload).
  • Examples of good and bad outputs, with brief explanations.
  • The output format.

None of this is a trick. It’s just clear communication. The best prompt engineers are good writers and good managers.

5.3 Anatomy of a strong system prompt

A useful structure (adapt freely):

## Role and context
You are the in-app assistant for Strider, a running-coach app. Users are recreational
runners training for 5k to marathon distances. You have access to their training
history via tools.

## Goals
Help users understand their training, adjust plans safely, and stay motivated.
Accuracy about their data matters more than sounding encouraging.

## Guidelines
- Base every claim about the user's training on tool results. If data is missing, say so.
- For any mention of pain or injury, recommend rest and seeing a professional; never
  diagnose.
- Keep responses under ~120 words unless the user asks for detail. Mobile screens are small.

## Output format
Plain text, no markdown headers. Use at most one short list.

## Examples
<example>
User: was my long run too fast?
Assistant: (calls get_recent_runs) Your Sunday 16 km averaged 5:20/km, about 35s/km
faster than your easy pace. Long runs usually work best at easy pace...
</example>

Principles behind it:

  • Explain the why, not just the what. “Keep it short because mobile screens are small” lets the model generalize to cases you didn’t anticipate. Bare rules get followed literally and brittlely.
  • Be specific about priorities and trade-offs. “Accuracy over encouragement” resolves conflicts.
  • Use structure. Markdown headers or XML-style tags (<documents>, <example>, <user_data>) help the model separate instructions from data. Tags are especially useful for clearly delimiting untrusted content.
  • Avoid shouting. “CRITICAL!!! NEVER EVER…” was a crutch for older models. Modern models follow instructions closely, and heavy emphasis tends to cause overcorrection, where the rule gets applied where it shouldn’t. Use calm, precise language.
  • Say what to do, not only what to avoid. “Write in flowing paragraphs” works better than “don’t use bullet points.”

5.4 Examples (few-shot prompting)

Examples are among the most powerful context you can provide, and among the riskiest.

  • Models imitate examples strongly: length, tone, structure, even specific word choices. Three examples that all start with “Great question!” produce a model that starts with “Great question!”
  • Diversify examples to show the range of acceptable outputs and stop the model from overfitting to surface features.
  • Include edge cases and how to handle them (missing data, ambiguous input, refusal-worthy requests).
  • For classification, balance examples across classes, or you’ll bias the predictions.

5.5 Letting the model think

For complex tasks, giving the model room to reason before answering improves accuracy. That’s the original “chain-of-thought” finding. Today, reasoning models do this natively with configurable thinking budgets. Practical guidance:

  • For reasoning models, don’t micromanage the thinking steps. A high-level instruction (“consider the edge cases carefully”) usually beats a prescribed step-by-step procedure, which can actually constrain a strong reasoner.
  • For non-reasoning calls, ask for reasoning in a structured field before the final answer, so you can parse just the answer.
  • Thinking costs tokens and latency. Use it where accuracy matters; skip it for simple extraction.

5.6 Context engineering for long-running agents

For a single call, the context is a prompt. For an agent running 50 tool calls over 20 minutes, the context is a dynamic, growing resource you must manage. This is where context engineering becomes systems design.

The problem: every tool result, file read, and intermediate thought accumulates. Context fills up, cost grows (each call re-sends everything), and quality degrades as relevant information is buried in noise (“context rot”).

Techniques:

  1. Just-in-time retrieval. Instead of loading all documents upfront, give the agent tools (search, read_file, grep) to pull information when needed. This is how coding agents work: they explore the codebase rather than ingesting it whole.
  2. Compaction / summarization. When context nears a threshold, summarize older history (decisions made, current state, open problems) and continue from the summary.
  3. Tool-result hygiene. Return concise, relevant tool outputs. A tool that dumps a 40,000-token JSON blob into context is a bug. Paginate, truncate, and summarize at the tool layer.
  4. Structured external memory. Let the agent write notes to files (a NOTES.md, a todo list, a progress log) and re-read them. This persists across compaction and even across sessions.
  5. Sub-agents. Delegate a focused subtask (e.g., “search the codebase for all usages of X”) to a fresh agent with a clean context, and get back only a condensed result. The main agent’s context stays clean.
  6. Stable prefix, variable suffix. Put system prompt, tool definitions, and long-lived documents first so prompt caching works. Append new content at the end. Don’t rewrite early context unnecessarily.

5.7 Common anti-patterns

Anti-pattern Why it hurts Fix
Kitchen-sink prompt (every rule anyone ever thought of) Rules conflict and dilute attention Prune ruthlessly; keep what evals show matters
Contradictory instructions Model picks one unpredictably Resolve conflicts with explicit priorities
Prompt tuned on 5 examples Overfits; fails on real traffic Test on a representative eval set (Chapter 8)
Dumping raw HTML or JSON Wastes tokens, adds noise Clean and extract before inserting
Burying the key instruction mid-prompt Lower salience Put it clearly near the start, or restate it near the end for long contexts
Persona fluff (“You are the world’s greatest…”) Little to no effect on modern models Replace with real context about the task
Unversioned prompts in random strings Can’t track regressions Version prompts like code; review changes; tie them to eval runs

5.8 Prompts are code

Treat prompts as first-class software artifacts:

  • Store them in version control, not in a dashboard nobody reviews.
  • Template them cleanly (variables for user data, retrieved docs, dates).
  • Every prompt change runs the eval suite, just as every code change runs tests.
  • Log the prompt version with every production call so you can trace regressions.
  • Review prompt diffs in PRs. A one-word change can shift behavior across thousands of cases.

5.9 Meta-prompting: using models to improve prompts

Strong models are excellent at improving prompts, if you give them evidence. A productive loop:

  1. Run your eval set and collect failures.
  2. Give a strong model the current prompt, the failing cases, what the correct outputs should have been, and ask it to diagnose the root causes and propose revisions.
  3. Re-run the evals. Keep changes that help without causing regressions.

Tools like DSPy automate versions of this, treating prompts as parameters to optimize against a metric. The principle stays the same: optimization needs a metric. Without evals, you’re tuning by vibes.

Key takeaways

  • Failures come from capability, missing context, or bad context. Modern models fail mostly on context.
  • Brief the model like a brilliant new hire: who, why, what good looks like, examples, format.
  • Explain the reasons behind instructions; skip shouting and persona fluff.
  • Examples are powerful and get imitated closely, so diversify them.
  • For agents, context is a managed resource: just-in-time retrieval, compaction, clean tool outputs, external memory, sub-agents, and cache-friendly ordering.
  • Version prompts like code and gate changes with evals.

Exercises

  1. Pick a feature from your app. Write a one-line prompt, then a full brief using §5.3. Compare outputs on 20 varied inputs.
  2. Write a prompt with three examples that share a surface quirk (all very short, say). Observe the model copying it. Then diversify the examples and compare.
  3. Take a long agent transcript (from a coding agent you use) and identify which context was useful and which was noise. How would you restructure the tool outputs?
  4. Run the meta-prompting loop in §5.9 on one of your prompts with at least 30 eval cases.