Deploying Long-Horizon Agents: Post-Training, Model Selection, and API Cost Control

    The competition among large language models has shifted from mere parameter scale to engineering capabilities in post-training, long-context, and long-horizon agents. For enterprise developers, three critical questions emerge: How does a model perform on specific tasks? How much does each API call cost? How can issues be debugged when things go wrong? This article addresses these three questions, focusing exclusively on actionable methods that developers can verify independently.

    1. Why Post-Training Affects Agent Performance

    Many widely used models are versions derived from base models through post-training techniques such as reinforcement learning (RL) and supervised fine-tuning (SFT). The goal of post-training is to enable the model to better follow instructions, call tools more stably, and maintain direction in multi-step tasks. For developers, the effects of post-training manifest primarily in three areas:

    1. Stability of tool calls: Whether the model can generate correct parameters based on function signatures determines whether the agent can smoothly chain multiple steps together.
    2. Recovery from failure: After an execution error, whether the model can read the error message and adjust its approach, rather than repeating the same operation.
    3. Task boundary awareness: When information is insufficient, whether the model can ask questions or stop, rather than fabricating results.

    The reinforcement learning framework handles the diversity of policy sampling, reward model design, and fault tolerance in distributed training. These are internal operations of the model provider and cannot be directly tuned by developers. What developers can do is use their own evaluation sets to verify whether these capabilities hold up in their specific business scenarios.

    2. How to Interpret Model Evaluation Scores

    Vendors and media frequently publish scores on coding terminal tasks, software engineering tasks, or internal long-horizon engineering tests. While these numbers offer reference value, you must verify at least the following five things before using them for model selection:

    • Name and version of the evaluation set: Questions may differ even under the same name across different versions.
    • Specific version and inference settings of the tested model: This includes whether a “thinking mode” is enabled, temperature parameters, and tool permissions.
    • Sample size and confidence intervals: With small sample sizes, a few percentage points of difference might just be random fluctuation.
    • Runtime environment: Including timeout limits, resource caps, and whether internet access is allowed.
    • Baseline conditions: Whether the comparison objects were tested under identical conditions or if numbers were simply cited from other sources.

    If this information is missing, the scores can only serve as a rough reference. A more reliable approach is to build a small evaluation set around your own business, containing 30 to 50 real samples that cover common tasks and edge cases. Re-run this set every time you switch models or modify prompts.

    3. Practical Limits of Long-Context Inference

    Supporting ultra-long context does not mean that arbitrary lengths of input will yield stable, high-quality results. Developers need to focus on three levels:

    1. VRAM and latency: The KV Cache footprint is basically proportional to the context length. When self-hosting, you can use the following formula for a theoretical estimation:

      KV Cache VRAM ≈ 2 × Layers × KV Heads × Head Dimension × Context Length × Bytes per Element × Concurrency

      This is only a theoretical value. Actual consumption is affected by the inference framework, quantization method, and paging strategy, so empirical testing is required.

    2. Retrieval quality: The more information in the context, the more likely the model is to ignore middle paragraphs. Key information should be placed near the instructions or presented in a structured format.

    3. Cost: Input tokens are directly billed, and long contexts will amplify the cost of each call.

    In practice, the recommended approach is to first compress the context to a necessary range using retrieval, and then decide whether the full input is needed.

    4. Sandbox and Environment Verification

    When an agent executes code or modifies files, it requires an isolated runtime environment. Common practices include: using containers or lightweight virtual machines, mounting source code as read-only, restricting network egress, setting CPU and memory limits, and destroying the environment after the task completes. During the verification phase, let the agent run unit tests or build commands, and use exit codes and test results to determine success, rather than trusting the model’s description of its own results.

    5. API Cost Control: Start with the Billing Structure

    Many teams only start paying attention to costs after their bills exceed their budget. Billing typically consists of four parts: regular input tokens, cached write tokens, cached hit tokens, and output tokens. Some platforms offer different retention durations for caches, and the difference between write pricing and hit pricing can be significant. Refer to the provider’s pricing page for exact values.

    The cost of a single call can be estimated as follows:

    Cost per call = (Regular Input Tokens × Input Price) + (Cache Write Tokens × Write Price) + (Cache Hit Tokens × Hit Price) + (Output Tokens × Output Price)

    Suppose an agent carries a stable prefix of 20,000 tokens on every call, including system prompts and tool definitions, and outputs 3,000 tokens each time. If the cache hit rate for the prefix is 80%, the savings from caching are typically more pronounced than compressing output length. This example only demonstrates the calculation method; in practice, replace these with real pricing and actual statistics.

    When using caching, keep the following in mind:

    • Place immutable content at the beginning of the prompt and variable content at the end. Otherwise, the cache prefix will frequently invalidate.
    • Keep tool definitions and system prompts stable. Avoid injecting dynamic fields like timestamps into every request.
    • Log the cache hit rate. If the hit rate stays low over time, prioritize checking the prompt structure.

    6. Three Strategies to Reduce Agent Costs

    1. Summarization and retrieval: In multi-turn dialogues, instead of sending the entire history every time, store summaries and key facts, and retrieve relevant fragments when needed. This is suitable for scenarios with long histories and low per-turn information relevance. It is not suitable for compliance scenarios that require verbatim quoting of historical content.
    2. High-speed model variants: Some providers offer faster model variants for latency-sensitive, high-concurrency interactive scenarios. Their pricing and capabilities may differ from the standard versions. Before switching, verify quality with your own evaluation set; do not look at speed alone.
    3. Asynchronous batch processing: Non-real-time tasks like research reports or data cleaning can be placed in a message queue for execution during off-peak hours. This smooths out peak loads and reduces the consumption of real-time quotas, but it extends result return times. This needs to be communicated clearly to users in the product.

    These three strategies can be stacked, but system complexity increases with each layer added. It is recommended to start with caching and summarization, and gradually introduce other strategies.

    7. Frequently Asked Questions

    How to choose a model?
    First, define the task type and the cost of failure, then compare two or three candidate models using your own evaluation set. Metrics to compare include task completion rate, average cost per call, and p95 latency. Relying solely on leaderboard scores makes it easy to select a model that performs well elsewhere but is unstable on your specific tasks.

    How to estimate token costs?
    Use real request samples to calculate the average input and output token counts, plug them into the formula above to calculate the cost per call, and then multiply by the estimated number of calls. After launch, it is recommended to calibrate the estimation using one week of real data.

    What are common mistakes?
    First, stuffing the entire codebase or documentation library directly into the context. Second, mixing fields that change on every request into the prompt, causing cache invalidation. Third, retrying infinitely when an agent fails without setting a maximum step limit. Fourth, only monitoring total costs instead of the cost distribution of individual tasks, which often means issues are discovered too late.

    8. Pre-Launch Checklist

    • Validated the selected model using your own evaluation set, and recorded the model version number and evaluation date.
    • Set maximum steps, per-call timeout, and total budget limits for each agent task.
    • Configured at least two tiers of budget alerts (e.g., notifying the responsible party at 50% and 80% of the monthly budget).
    • Set up logging for model version, input and output token counts, cache hit token counts, duration, and task results.
    • Periodically sample and evaluate the recall quality of the retrieval module to check for irrelevant content being retrieved.
    • Isolated the code execution environment, with explicit restrictions on network egress and file write scopes.
    • Desensitized logs involving user data, ensuring prompts and responses are not saved or transmitted externally without authorization.
    • Checked the prompt structure to ensure static content is located at the front, allowing for stable cache hits.