Context Engineering A–Z — Part 1 of 26. This practical series moves from context fundamentals to retrieval, memory, evaluation, security, production operations, and a complete capstone. Follow the LinuxSME Learning Paths index for the complete sequence, and continue with Part 2: Design a Context Contract for AI Agents.
Context engineering is the practice of deciding what an AI model should see for one task, how that information should be organized, and what should be left out. It includes the instructions, conversation history, retrieved knowledge, tools, tool results, memory, permissions, and current state assembled for a model call. Prompt wording is only one part of that system.
Imagine asking an on-call engineer to diagnose a server. Handing them every log, old ticket, runbook, and chat message is not helpful. A concise incident summary, the relevant logs, the right runbook, and clear permissions are. An AI agent has the same need: a large context window is room, not a reason to fill every space.
What does context engineering mean?
A model answers from the information available in its current request and any state the application provides. Context engineering is the engineering work around that request: identify candidate information, select what is relevant, preserve its source and freshness, fit it within a token budget, and refresh it as the agent learns more.
Anthropic describes context engineering as curating what enters a limited context window from a larger, changing universe of possible information. OpenAI’s agent building materials similarly treat tools, state or memory, and orchestration as building blocks around the model. The shared lesson is simple: reliable behavior depends on the whole information flow, not just a clever prompt. Anthropic: Effective context engineering for AI agents; OpenAI: Building agents.
Context engineering vs. prompt engineering, RAG, and memory
| Term | What it focuses on | Example |
|---|---|---|
| Prompt engineering | The wording and structure of instructions to the model. | Tell a Linux helper to diagnose first and request approval before changes. |
| Context engineering | The complete, task-specific information and controls supplied to a model call. | Include the prompt, relevant log excerpts, service status, runbook, and read-only tool definitions. |
| Retrieval-augmented generation (RAG) | Finding relevant external knowledge and adding it to the current request. | Search approved runbooks for the systemd service named in an error. |
| Memory | Information retained outside the current call for possible future use. | Remember a project’s chosen distribution or a user-approved operating constraint. |
RAG is one way to supply context; it is not the entire discipline. Memory is also not automatically context: stored information must be selected and injected into the current request before it can influence the model.
What belongs in an agent’s context?
- Task and success criteria: the user’s goal, boundaries, output format, and what counts as done.
- Stable instructions: role, safety rules, style, and procedures that apply to the current task.
- Conversation state: the recent exchanges or a careful summary of older turns that still matter.
- Retrieved knowledge: selected documents, database records, tickets, or runbook passages, ideally with source and timestamp.
- Tool definitions and permissions: what the agent can call, required parameters, and which actions require human approval.
- Tool results and live state: outputs from commands or APIs, filtered to the facts needed for the next decision.
- Examples and schemas: a small number of representative examples or a structured response contract when consistency matters.
The context assembly loop
A useful agent does not simply paste its entire history into every request. It assembles context for the current step, checks the result, and updates its working state. The loop below shows a practical pattern.
- Define the task. Extract the goal, constraints, success criteria, and allowed actions.
- Gather candidates. Search memory, documents, recent conversation, tool schemas, and live systems for potentially useful information.
- Filter and rank. Prefer relevant, authoritative, recent evidence. Remove duplicates, stale notes, unrelated history, and sensitive fields the model does not need.
- Fit the budget. Reserve room for the answer and tool results. Summarize or omit low-value material rather than truncating important instructions unpredictably.
- Call the model. Provide a clear separation between instructions and untrusted external content. Include tools only when the task needs them.
- Check and update. Validate the response or tool result. Save only durable facts that will help a future task, then assemble fresh context for the next step.
A Linux incident example
Suppose an administrator asks an agent, “Why is nginx failing, and what should I check?” A weak design sends the whole chat history and thousands of unrelated log lines. A better context plan builds a small evidence packet:
| Context item | Selection rule | Why it helps |
|---|---|---|
| Goal | Diagnose the nginx failure; do not change the host. | Keeps the model focused and limits authority. |
| Recent evidence | A bounded excerpt around the failure timestamp, with secrets removed. | Provides concrete evidence instead of a guess. |
| System state | nginx unit status and the relevant configuration test result, if available. | Separates service symptoms from configuration errors. |
| Knowledge | The matching local runbook section, including its source and revision date. | Adds operational guidance without dumping the whole knowledge base. |
| Tools | Read-only status and log retrieval tools only. | The agent can gather evidence but cannot restart or edit services. |
| Output rules | Summarize evidence, likely causes, uncertainty, and safe next checks in a table. | Makes findings reviewable by the administrator. |
If the first evidence points to a missing configuration file, the agent can request a targeted read of that path instead of loading every nginx file. The application then adds that result to a new context and asks the model for the next step. A proposed restart or edit should be presented for human review, not silently executed.
How to keep context useful
- Retrieve just in time. Use stable identifiers such as a document ID, file path, ticket number, or query, then fetch the relevant content when the task needs it. This can be cheaper and fresher than preloading an entire corpus.
- Preserve provenance. Keep source names, timestamps, and version information alongside retrieved text. The agent should be able to distinguish a current runbook from an old chat note.
- Use a token budget deliberately. Long prompts cost more and can bury important facts. Decide how much room belongs to instructions, evidence, tool results, and the model’s response.
- Summarize with care. For long-running work, compact old conversation into decisions, current state, unresolved questions, and next steps. Keep exact values or evidence that cannot safely be reconstructed.
- Keep tool output focused. Filter command output in application code, return relevant lines and exit status, and avoid feeding the model megabytes of irrelevant data.
- Separate trusted instructions from untrusted content. Retrieved documents, websites, logs, and user-provided files can contain misleading instructions. Treat them as data; do not let them override policy or grant new permissions.
- Measure instead of guessing. Build representative tasks and compare success rate, citation accuracy, tool errors, token use, and latency as context strategies change.
Why not send everything to a very large context window?
More available context can help when a task truly needs a large source, but it does not guarantee that every detail receives equal attention. Irrelevant material can dilute the signal, stale information can conflict with current state, and longer requests may increase cost and latency. Anthropic discusses this challenge as context rot and recommends keeping context informative but focused. A practical rule is to provide the smallest evidence set that still lets the model complete the task accurately.
Common context engineering mistakes
| Mistake | Why it causes trouble | Better approach |
|---|---|---|
| Putting every rule in one giant system prompt | Instructions become hard to maintain and important rules are harder to find. | Use concise core rules, task-specific guidance, and small canonical examples. |
| Treating retrieval as fact validation | A retrieved paragraph can be stale, irrelevant, or wrong. | Check source quality, dates, and whether the result actually answers the question. |
| Replaying every tool result | Old outputs consume tokens and may contradict current state. | Keep a brief summary and retrieve the raw result again when needed. |
| Storing every conversation detail as memory | Personal or incidental information can become noise or a privacy problem. | Store only durable, useful facts with an owner-approved purpose. |
| Giving an agent broad tools by default | A context mistake can become an unsafe action. | Grant the minimum tools and permissions needed; put approval gates around consequential changes. |
| Calling a forecast a fact | Patterns in a small context may not predict what happens next. | State evidence and uncertainty separately, and verify with monitoring data. |
Frequently asked questions
Is context engineering just better prompting?
No. Prompting shapes instructions; context engineering also manages retrieval, memory, tool schemas and results, current state, token budgets, and the update loop.
Is context engineering the same as RAG?
No. RAG retrieves external material for a model request. It is one context source among several, and still needs selection, ranking, freshness checks, and source tracking.
Does a larger context window remove the need for context engineering?
No. It increases capacity, but agents still need relevant evidence, current state, safe tool access, and sensible cost and latency. More text is not automatically better context.
How do I know whether my context design is improving the agent?
Test it on representative tasks with known expected evidence and outcomes. Compare task success, unsupported claims, retrieval quality, tool-call errors, token use, and latency. Change one design choice at a time where possible.
A practical checklist
- Can the model see the user’s actual goal and constraints?
- Are the retrieved facts relevant, current, and traceable to a source?
- Are untrusted documents and logs clearly treated as data?
- Are there clear limits on which tools the agent can use?
- Is enough context reserved for the response and next tool result?
- Does the workflow preserve important state without replaying noisy history?
- Are consequential actions reviewed by a human?
- Do evaluation examples test both successful and failure cases?
Context engineering turns an AI model from a prompt responder into a more dependable part of an application. The engineering work is to make each model call well-informed, focused, current, and appropriately constrained. Start with a small context plan, observe where the agent fails, and improve the selection and refresh logic based on evidence.
Further reading: Anthropic’s context engineering article, OpenAI’s agent building guide, and OpenAI’s prompt engineering guide.