What is the difference?
| Criterion | Prompt Engineering | Context Engineering |
|---|---|---|
| Goal | Instructions | Information selection |
| Scope | Instructions and examples | Data, tools and state |
| RAG | Rules for using evidence | Retrieval and evidence selection |
| Memory | Rules for using history | Retention, retrieval and freshness |
| Evaluation | Instruction adherence | Relevance, cost and security |
Prompt engineering is the iterative design of instructions, demonstrations and task presentation. Context engineering addresses a larger question: which information and tools are supplied at each inference step, in what form, order and quantity, and how that selection changes over time. The distinction is a useful convention rather than a formal standard; the prompt itself is part of context. [1][2][3]
A simple text classifier may only require an instruction and a few examples. An order assistant additionally needs current order data, regional policy and the result of earlier operations. Rephrasing the instruction cannot supply absent evidence.
Designing effective instructions
Specify the goal, input, constraints and acceptance criteria. Instead of asking a model to assess a ticket, define allowed categories, assignment criteria, what to do when information is missing and the expected response format. Zero-shot prompting uses no demonstrations; few-shot prompting supplies a small set. Include boundary cases as well as common examples. [1][3]
Separate application instructions from user content using supported message roles and clear structure. Delimiters aid interpretation, not security enforcement. Use schema-constrained output where supported and validate values independently. Version instructions and evaluate them against the selected model; prompting techniques are not equally effective across models.
An instruction for the order assistant could read: “Explain return eligibility using the supplied policy and the eligibility service result. Include the source identifier. If the service result or applicable policy is unavailable, mark the answer incomplete. Do not confirm a refund without system confirmation.” This defines expected behavior; the server must still verify sources, permissions and operation state.
What enters the model context?
Context may include system and developer instructions, the current request, selected messages, retrieved passages, API data, available tool schemas and tool results. Not every element belongs in every call. Images and other modalities can consume context capacity depending on the model and provider's accounting. [2][4]
Distinguish model-visible context from application execution state. Session identifiers, credentials and permissions may be necessary to the backend without being sent to the model. Return authorized tool results instead of exposing credentials that could execute the operation. [5][8]
Context windows, token budgets and cost
A context window measures capacity rather than the ability to use every item effectively. Lost in the Middle found that some tested models performed worse when relevant evidence appeared in the middle of long inputs than near their ends. This is not a universal curve for all models or tasks. Test evidence position, document count and history length on your own workload. [6]
For an illustrative shared capacity of 32,000 tokens, reserve 4,000 for generation and 2,000 as headroom, leaving 26,000 input tokens. If instructions and tools consume 3,000 and the question and history use 5,000, sources have 18,000 remaining. These are planning assumptions, not a particular model's limits. Check provider-specific input, output and reasoning-token accounting.
At 10,000 calls per month, reducing input from 20,000 to 8,000 tokens saves 120 million input tokens. At a hypothetical $2 per million, that is $240 before retrieval, summarization and caching costs. Prompt caching may reduce the processing cost and latency of reusable prefixes, but neither increases context capacity nor replaces selection. [7]
Check the budget before every call, including message-format overhead and tool schemas. If input exceeds the limit, remove low-value sources, reduce irrelevant tool results or split the task. Preserve instructions, the current request and evidence necessary for the decision. If it still does not fit, stop or change strategy rather than silently dropping essential information. Distinguish cached prefix computation from cached answers: the latter require freshness and access checks. [2][4][7]
RAG and dynamic data acquisition
Retrieval-augmented generation retrieves evidence, selects passages, optionally reranks them and includes them in context. Selection depends on task relevance, access rights, freshness and budget. Vector search is not mandatory; full-text search, metadata filters and hybrid retrieval may be appropriate. [2][8]
For changing facts such as a balance or stock level, use an authorized API or deterministic business query. If evidence is insufficient, report the gap or ask for clarification. RAG cannot guarantee correctness. Compare retrieval with directly supplying documents on a common evaluation set.
Keep the document ID, version, effective date and excerpt location. Deduplicate results and resolve conflicting sources using explicit precedence rules. If selection misses essential evidence, further retrieval must stay within the task budget. Verify model-generated citations against the actual excerpt, not merely a list of IDs.
Memory, history and long-running agents
Conversation history records interactions; short-term memory retains information for the current task; persistent memory may store selected facts across sessions. Business state, such as an approved transaction identifier, needs a separate authoritative source. Memory does not enlarge the model's context window. [4][5]
Trim irrelevant messages, summarize, keep source-linked notes or isolate subtask contexts. Summarization is lossy and may omit constraints or introduce errors. Preserve source references, decisions and pending work; check the target system before retrying an operation. Limit memory retention and revalidate freshness and permissions when reading it. [2][4][8]
Persistent memory is also a trust boundary. Do not automatically promote instructions found in documents into future policy. Distinguish verified facts, user preferences and unverified observations; retain provenance, scope and expiration. Test memory deletion and correction, including retrieval after permissions change. [4][8]
Architecture and an order assistant example
A practical flow starts with an authenticated API, followed by server-side authorization and budget checks, retrieval, a context assembly module with versioned instructions, model generation and independent output validation. If more data is needed, an agent can invoke an allowed tool and receive its result on a subsequent step. Bound time, cost and retries at every stage.
A customer asks whether an order can be returned. Instructions specify the answer format and evidence requirements. The backend retrieves the customer's order and current return policy. The model drafts an explanation. The business service determines eligibility and amount, and any write requires independent authorization. If the service is unavailable, the assistant must not invent a decision or confirm an operation.
Harness engineering encompasses the broader execution environment, including isolation, tool control, execution loops, testing, state and error handling. Context engineering supplies information for reasoning within that environment; prompt engineering specifies instructions. These are complementary responsibilities, not mutually exclusive technologies. [9]
Context security and privacy
Treat documents, web pages, tool responses and user content as untrusted data. Direct prompt injection originates in user input; indirect prompt injection can arrive through retrieved documents, web pages or tool results. Both can introduce instructions that conflict with the task. Keep secrets out of instructions; enforce least privilege, tenant isolation, authorization before retrieval and independent authorization before execution. Output shape is not authorization. [8]
Scope caches, summaries and persistent notes by identity, tenant and permission version. Revocation must prevent exposure during index updates too. Log source identifiers, instruction versions and token usage rather than full contexts by default. Align retention with product requirements and provider terms.
The POLPROG guide to OWASP Top 10 for LLM Applications covers additional safeguards. [11]
Evaluation and error diagnosis
| Symptom | What to inspect |
|---|---|
| Missing document | Retrieval and permissions |
| Invalid format | Instructions, schema and validation |
| Stale data | Source, index and cache |
| Unauthorized operation | Authorization and execution layer |
Build representative cases with expected outcomes and evidence. Hold the model fixed and compare four configurations: baseline prompt and context, improved prompt with baseline context, baseline prompt with improved context, and both improvements. Keep task, settings and permissions consistent; record index and data versions. Repeat trials because model responses can vary. [10]
Measure retrieval recall (such as Recall@k), factual correctness, evidence coverage, appropriate abstention, task success, cost per successful task and p95 latency. Recall@k is the fraction of relevant expected items returned in the top k results. If the relevant document never reaches the model, investigate retrieval; if present but misused, evaluate the prompt, model and context layout. Verify permissions and actual side effects separately from response text.
Diagnostic example: if a query has four known relevant passages and three appear in the first five results, Recall@5 is 3/4 = 75%. This is not answer accuracy. Also evaluate generation with manually selected correct evidence to isolate retrieval errors from generation errors. Cost per successful task is the total cost of all attempts divided by the number of accepted tasks; it is undefined when there are no successes. Report incorrect refusals and unauthorized effects separately.
Which approach should you choose?
Start simple. For short-text classification or transformation, focus on instructions, examples and validation. For document questions, select evidence. For multi-step agents, add state, memory, tool and budget management. If reliable knowledge is already supplied yet behavioral errors persist despite prompt improvements, evaluate a different model or fine-tuning with held-out tests.
A production release should have versioned instructions and selection rules, measurable budgets, regression tests, access controls and a rollback procedure. Improving one component must not degrade the safety or cost of the overall task.
The related POLPROG article compares RAG, fine-tuning and long context, including costs and hybrid approaches. [12]
