AI Agent Basics: From the Host Program to Context Engineering

    This article explains how an AI Agent works beyond the model itself, focusing on the host program and Agent Harness that assemble context, execute tools, and maintain task state. It breaks down a typical context budget, shows that tool definitions consume more than half of the tokens before the first model response, and walks through the key fields of a tool definition. It also covers why KV caching makes prefix stability important and outlines a practical learning path for building a minimal Harness, measuring context usage, optimizing tools and instructions, and improving cache reuse.

    AI Agent Basics: From the Host Program to Context Engineering

    When beginners start learning about AI Agents, their first instinct is often to compare the reasoning ability of different models or look for the “strongest framework.” In real engineering practice, however, what determines whether an Agent is usable is usually not the model itself, but the layer of software wrapped around it—the software that communicates with the model, assembles context, executes tool calls, and maintains task state. The industry commonly refers to this type of software as the host program, and the full set of mechanisms built around the model as the Agent Harness.

    Understanding the relationship between the two is a key step in moving from “being able to call a model” to “being able to build an Agent.” From a general technical perspective, this article breaks down the components of the Harness, the logic of context budget allocation, the key design points of tool definitions, and how caching affects the choice of historical positions.

    1. The Host Program and Agent Harness: The Other Half Beyond the Model

    A usable Agent is essentially the result of collaboration between the model and the Harness. The model provides understanding, reasoning, and decision-making capabilities, while the Harness organizes those capabilities into a closed loop that can continuously interact with the external environment.

    Specifically, the Harness usually takes on the following responsibilities:

    • Request assembly: Combining system instructions, the tool list, environment information, and conversation history into the context required for a model call.
    • Tool execution: Parsing the structured call intent in the model output, executing it in a sandbox, and writing the result back as new context.
    • State maintenance: Tracking task progress, completed steps, and pending confirmations to keep multi-turn interactions consistent.
    • Safety and approval: Adding confirmation steps for high-risk operations and isolating the execution environment to prevent mistakes from spreading.

    A common misconception is that the model is “blank” before the user enters input. The opposite is true—before you type the first period, the host program has already prepared the model’s entire working environment. The quality of this upfront context directly determines the quality of the model’s first decision.

    2. Context Budget: Where the Tokens of a Single Call Go

    To quantify how heavy the “upfront context” is, you can use a reproducible estimation method: parse the rollout content before the first model response and estimate it in chunks with a public tokenizer. It is worth emphasizing that choosing a public tokenizer is only for obtaining comparable approximate values; tokenization granularity differs across models, so the conclusions should focus on relative proportions rather than absolute numbers.

    A typical set of estimation results is as follows (the values are illustrative and used to explain the structure):

    Context component Token estimate Share
    Tool definitions 11,055 54.2%
    Base model instructions 5,059 24.7%
    Skill discovery information 2,343 11.4%
    Other host instructions 782 3.8%
    Deferred tool discovery catalog 543 2.6%
    Sandbox and approval notes 395 1.9%
    Working environment 224 1.1%
    Project-level instruction file 43 0.2%
    User input 1 ~0%
    Total 20,495 100%

    This table reveals a counterintuitive fact: tool definitions account for more than half of the context budget, while user input is almost negligible. This means that an Agent’s “starting line” is laid by the Harness, not determined by the user’s question.

    This leads to the first principle of context engineering: the budget is a scarce resource and must be managed explicitly. Common optimization practices include:

    1. Load tools on demand: Do not inject all tools at once; provide a catalog first, then load the specific definitions after the model expresses intent (i.e., “deferred tool discovery”).
    2. Layer instructions: Separate stable base instructions from scenario-specific host instructions to make cache reuse easier.
    3. Minimize environment information: Provide only the working environment fields truly needed for the current task, avoiding lengthy descriptions that crowd out the budget.

    3. Tool Definitions: The Contract Between the Agent and the External World

    Since tool definitions are the largest overhead item, it is worth looking closely at their structure. The following is a neutralized example that keeps the main fields, showing how a “pause execution” type tool is actually written:

    1. {
    2. "type": "function",
    3. "name": "sleep",
    4. "description": "Pause execution for a specified duration. The sleep ends early when new input arrives for the active turn. Returns the elapsed wall-clock time.",
    5. "strict": false,
    6. "parameters": {
    7. "type": "object",
    8. "properties": {
    9. "duration_ms": {
    10. "type": "number",
    11. "description": "How long to sleep in milliseconds. Must be between 1 and 43200000."
    12. }
    13. },
    14. "required": ["duration_ms"],
    15. "additionalProperties": false
    16. }
    17. }

    Although this definition is short, it contains all the key elements of tool design and deserves a layer-by-layer breakdown:

    • Semantic naming: name is the main basis for the model to choose a tool, and the name should directly correspond to the action intent.
    • Description as prompt: description is not just documentation; it is itself an instruction for the model. The sentence above explains the early termination condition and the meaning of the return value, which is a high-quality “behavior contract.”
    • Upfront parameter constraints: Writing the value range into the parameter description (1 to 43200000 milliseconds) helps the model avoid invalid input during generation.
    • Strict mode and closed structure: additionalProperties: false combined with the required list reduces ambiguity and lowers the parsing failure rate.

    For beginners, there is a transferable lesson here: every sentence in a tool definition consumes budget and affects behavior. When writing tool descriptions, consider both “whether the model can understand it” and “whether the tokens are worthwhile.”

    4. KV Caching and Historical Position Selection: Why the Query Does Not Need to Be Saved

    Context engineering has another often-overlooked dimension: caching. When deciding “which historical positions the current request should attend to,” what is saved is not the original query text, but the Keys and Values produced by already-processed tokens in each Transformer layer, i.e., the KV cache.

    The reason can be inferred from the computation goal: the question we need to answer is “which of A, B, C, and D should the new attention position E attend to,” not “who did A, B, C, and D each attend to at the time.” The former only requires the Key/Value of the attended party, while the latter requires keeping the query of the querying party. Therefore, caching the KV of historical tokens can both reuse existing computation results and directly support the attention computation of new positions, avoiding repeated forward passes.

    This mechanism has a direct impact on Agent engineering:

    • Prefix stability matters: Invariant content such as base instructions and the tool catalog should be placed at the front of the context to maximize cache hits.
    • Put dynamic content later: Volatile information such as timestamps and temporary environment variables should be placed as far back as possible to prevent the prefix from becoming invalid and invalidating the entire cache.
    • Be careful with history trimming: Trimming changes the set of positions and requires a trade-off between “context length” and “cache reuse rate.”

    5. A Practical Path for Beginners

    Putting the above together forms a clear learning path:

    1. Build a minimal Harness first: Implement the three basic parts—request assembly, tool parsing, and result write-back—to get a single-tool loop working.
    2. Measure the budget: Use a public tokenizer to calculate the share of each context segment and find the largest source of overhead.
    3. Optimize tools and instructions: Compress redundant descriptions and introduce on-demand loading and layered instructions.
    4. Add safety and state: Introduce sandbox isolation, approval confirmation, and task state tracking.
    5. Pay attention to cache friendliness: Adjust the context order to improve prefix reuse.

    If you need to extend capabilities, you can use general cloud capabilities to host the runtime environment, such as using a container platform to isolate tool execution, object storage to save intermediate artifacts, and logging and monitoring services to trace the call chain. These all belong to general product categories, and specific choices should be evaluated based on your own scale and compliance requirements.

    In summary, the entry barrier for AI Agents is not the model but the Harness. Whoever can more finely manage the context budget, design tool contracts, and leverage caching can build a more stable and economical Agent with the same model.