Context Engineering in Practice: Lean Prompts and Cost-Controlled LLM Development

    This article explains how to move from prompt engineering to context engineering for LLM applications. It covers principles for lean system prompts, a five-layer context model, token-cost tradeoffs, end-to-end evaluation for complex tasks, safety and compliance controls, and a practical implementation sequence. Readers will learn how to assemble only the necessary information for each model call, prioritize context under a token budget, measure cost per successful task, and use programmatic validation to make model behavior more stable and development costs easier to control.

    1. Background: From Prompt Engineering to Context Engineering

    Early LLM application development relied heavily on prompt engineering. Developers guided model output by repeatedly stacking instructions, examples, and formatting constraints. When model capabilities were weaker, this approach worked because the model needed extensive explicit guidance to complete a task.

    As model capabilities improved, the problem changed. The more instructions there are, the more likely the model is to miss key points and waver between conflicting rules. At the same time, the longer the fixed text carried in every request, the higher the token consumption and response latency. Industry practice has therefore converged on a consensus: strong reasoning models need more concise, clearly structured instructions, not longer ones.

    Context engineering focuses on the overall information architecture. It answers the question of what information the model should see in a given call, in what order it should appear, how much budget it should occupy, and what information should be excluded. The prompt is only one part of the context. Other parts include retrieved materials, conversation history, tool descriptions, and output constraints.

    2. Principles for Lean System Prompts

    The system prompt is a fixed cost carried in every request. The more bloated its content, the more it compresses the space available for user input and retrieved materials. The following principles can help keep system prompts lean.

    1. Keep only rules that the model cannot infer from general capabilities. For example, if the model already understands the syntax of common programming languages, there is no need to explain it line by line in the system prompt. What truly needs to be specified are project conventions, such as code style, prohibited items, and output format.

    2. Use structure instead of long paragraphs. Group rules by category and use short headings and lists. This makes it easier for the model to locate rules and for developers to maintain them.

    3. Move low-frequency rules out of the resident portion. Rules used only in specific tasks should be injected when the corresponding task is detected, rather than included every time.

    4. Remove content that duplicates or conflicts with other rules. When the same rule appears in two places, the model may behave inconsistently, and maintainers may find it difficult to determine which version is authoritative.

    The following is illustrative code for layered context assembly. estimate_tokens needs to be implemented according to the actual tokenization method used; it is only a placeholder here:

    1. def build_context(system_rules, task, retrieved_docs, history, max_tokens):
    2. """Assemble context by priority and drop low-priority content when the budget is insufficient."""
    3. budget = max_tokens
    4. parts = []
    5. # Priority order: system rules > current task > retrieved documents > conversation history
    6. for block in [system_rules, task, *retrieved_docs, *history]:
    7. cost = estimate_tokens(block)
    8. if cost > budget:
    9. break
    10. parts.append(block)
    11. budget -= cost
    12. return "\n\n".join(parts)

    This code reflects a key idea: context is a budgeted resource. When assembling it, priorities should be explicit rather than concatenating content indiscriminately in writing order.

    3. Five Core Layers of Context

    To make context easier to design and troubleshoot, it can be divided into five layers.

    Instruction layer. This defines the model’s role, goals, boundaries, and output specifications. This layer should remain stable; frequent changes make behavior difficult to reproduce.

    Knowledge layer. This includes retrieved document snippets, database records, or business rules. The key to this layer is relevance. Irrelevant content not only wastes budget but also interferes with the model’s judgment.

    Conversation layer. This stores the history of multi-turn conversations. It usually needs summary compression, retaining only decisions and conclusions relevant to the current goal rather than transcribing the entire conversation.

    Tool layer. This describes callable external capabilities, including function names, parameter meanings, and usage conditions. Tool descriptions should be short and accurate, because as the number of tools increases, the descriptions themselves also consume a large amount of context.

    Constraint layer. This specifies output length, format, citation method, and safety requirements. Constraints should be programmatically verifiable, for example by returning results in a structured format that is easy to parse later.

    The benefit of layering is problem localization. When output is abnormal, developers can troubleshoot layer by layer: Is the instruction unclear, the material irrelevant, the history contaminated, or the tool description ambiguous?

    4. Tradeoffs Between Token Cost and Performance

    Call cost is usually determined by both input tokens and output tokens. The cost of a single call can be estimated with the following general formula:

    1. cost per call = input tokens × input unit price + output tokens × output unit price

    In this formula, the system prompt and retrieved materials are both counted as input tokens. Therefore, lean fixed instructions can reduce the baseline cost of each call, while reducing irrelevant retrieval results can simultaneously lower input volume and the noise the model must attend to.

    When selecting models, do not look only at the sticker price of an individual model. Instead, measure cost per task. A practical approach is as follows:

    1. Select a set of representative tasks covering typical scenarios such as daily Q&A, code generation, and long-document processing.
    2. Record the input tokens, output tokens, response time, and completion quality for each task.
    3. Calculate the average cost and success rate for each task category to obtain the cost per successful task.
    4. Decide on the tradeoff between performance and cost based on business priorities. For example, use a lower-cost configuration for low-risk tasks and a more capable configuration for high-risk tasks.

    The advantage of this method is that conclusions are reproducible. After the team changes models or adjusts prompts, it only needs to rerun the same task set to compare differences.

    5. Evaluation Design for Complex Tasks

    General Q&A tests are not enough to reflect real engineering capability. For tasks that require generating complete programs or interactive interfaces, end-to-end evaluation can be designed.

    A feasible evaluation process includes the following steps:

    • Input standardization: Unify task descriptions, for example by providing a piece of text and requiring the generation of a corresponding interactive scenario.
    • Output executability check: Automatically run the generated code and record whether errors occur and whether it can start.
    • Functional coverage check: List checkpoints based on task requirements and determine item by item whether they are implemented.
    • Resource logging: Record elapsed time, output code size, and total cost.

    An example evaluation record can use the following structure:

    1. {
    2. "task_id": "scene-001",
    3. "runnable": true,
    4. "checklist_passed": 7,
    5. "checklist_total": 9,
    6. "elapsed_minutes": 120,
    7. "output_lines": 5500,
    8. "cost_usd": 10
    9. }

    The key to evaluation is consistent standards. The same task should be run multiple times under the same conditions because generation results are stochastic. Reporting only the best single result can easily overestimate capability.

    6. Security and Compliance Constraints

    Context often contains user data, internal documents, and business rules, so filtering should be done during the assembly stage.

    • Sensitive information filtering: Before writing to context, identify and redact fields such as phone numbers, identification numbers, and keys.
    • Citation length limits: Set a maximum length for each retrieval citation to avoid direct output of large excerpts, while also reducing copyright and leakage risks.
    • Memory write control: Clearly define which information may be stored long term and which information is valid only for the current session.
    • Audit logs: Record the context version used in each call for later tracing.

    These measures should be implemented at the code level, not merely written in prompts. A model following instructions is probabilistic behavior; programmatic validation is what provides deterministic guarantees.

    7. Implementation Recommendations

    In real projects, context engineering can be advanced in the following order:

    1. Inventory existing system prompts and remove duplicate, conflicting, and outdated rules.
    2. Manage the five layers—instruction, knowledge, conversation, tool, and constraint—separately, and set a budget cap for each layer.
    3. Establish a fixed task evaluation set and rerun it after every prompt change or model change.
    4. Record cost per task and periodically review resource allocation.
    5. Perform structured validation on outputs, and automatically retry or degrade when validation fails.

    The core of context engineering is not writing longer instructions, but ensuring that each call carries only the necessary information. The more precise the information, the more stable the model’s judgment, and the easier it is to control cost.