LLM Agents in Long-Horizon Tasks: Prompt Caching and Cost Control
Long-horizon agents require models to retain key context, stay consistent across multiple steps, and use tools reliably. This article examines where newer models improve in research, code engineering, and complex planning, how prompt caching affects agent costs, how to structure cache-friendly calls, and what to check before deployment.
LLM Agents in Long-Horizon Tasks: Prompt Caching and Cost Control
The shift from single-turn question answering to long-horizon tasks has been one of the main changes in Agent development over the past year or two. A long-horizon task requires the model to execute multiple steps in sequence, call tools along the way, read context, revise its plan based on intermediate results, and only then produce a final result. Such tasks place concentrated demands on the model in three areas: retaining key information in a long context, maintaining consistency across multi-step reasoning, and using tools correctly while handling errors returned by those tools.
Earlier models commonly had two problems in these areas. The first was context forgetting: files or conventions read earlier were ignored in later steps. The second was logical discontinuity: each step might look reasonable on its own, but the dependencies between steps were broken, and the final result did not match the goal.
Newer models have improved in these areas, mainly in three types of scenarios.
In research tasks, a model can read literature, write experiment scripts, run them, and adjust parameters based on the output. This capability needs to be evaluated in an isolated sandbox environment. When citing results, you should include the benchmark name, model version, and test date.
In code engineering, a model can understand project structure across multiple files, identify duplicated logic or heavily coupled modules, and propose a step-by-step refactoring plan. To judge whether it is reliable, you need to check whether tests pass after refactoring and whether the scope of generated changes can be reviewed manually.
In complex task planning, a model can break a larger goal into subtasks and modify the plan during execution. Developers still need to set step limits, human approval checkpoints, and rollback mechanisms. Once a planning error enters later steps, its cost accumulates.
How Caching Affects Agent Costs
Every Agent call carries the system prompt, historical messages, and code context. If the server can reuse the computation for these prefixes, input costs drop noticeably. This reuse is commonly called a cache read. Most vendors price cached input tokens separately. Specific discounts, minimum cache length, cache TTL, and whether caching must be explicitly enabled all depend on the selected vendor’s official pricing page.
Caching applies only to prefixes. If any part of the preceding system prompt or historical messages changes, all subsequent cache entries are invalidated. Therefore, the Agent’s message structure needs to remain stable: fixed content should come first, and user instructions and temporary retrieval results that change on each call should come later.
When evaluating cost reduction, record at least the following metrics:
- Input tokens per task, separated into cache reads and regular input
- Cache hit rate, meaning the ratio of cached prefix length to total input length
- Total cost per task, including output tokens and tool call costs
- Task completion rate, so that quality is not reduced just to save money
Only with this data can you determine whether an optimization is effective. This article does not provide a universal cost-reduction ratio. Any advertised percentage should first be retested with your own task data.
How to Write Cache-Friendly Call Code
The following example shows how to organize the message structure. The endpoint and model name are placeholders, and cache-related parameters need to be set according to vendor documentation. The example has not been validated against a real API and should not be deployed directly. The key is injected through the environment variable LLM_API_KEY; do not write keys into code, logs, or version control.
import osimport requestsclass PrefixStableAgent:# Fixed prefix: keep the system prompt unchanged so the server can reuse the prefix cacheSYSTEM_PROMPT = "You are a senior code refactoring expert. Based on the code context, provide a step-by-step refactoring plan."def __init__(self, endpoint: str, model: str):# Read the key from an environment variable; do not write it into codeapi_key = os.environ["LLM_API_KEY"]self.endpoint = endpointself.model = modelself.headers = {"Authorization": f"Bearer {api_key}","Content-Type": "application/json",}def run(self, code_context: str, user_query: str) -> str:# Put relatively stable content first and the changing instruction lastmessages = [{"role": "system", "content": self.SYSTEM_PROMPT},{"role": "user", "content": f"Code context:\n{code_context}"},{"role": "user", "content": f"Current instruction:\n{user_query}"},]payload = {"model": self.model, "messages": messages, "max_tokens": 4096}try:resp = requests.post(self.endpoint, headers=self.headers, json=payload, timeout=60)resp.raise_for_status()data = resp.json()return data["choices"][0]["message"]["content"]except requests.RequestException as exc:raise RuntimeError(f"Model call failed: {exc}") from excexcept (KeyError, IndexError, ValueError) as exc:raise RuntimeError(f"Response format was not as expected: {exc}") from excif __name__ == "__main__":agent = PrefixStableAgent(endpoint="https://api.example.com/v1/chat/completions", # Placeholder URL; replace with the selected vendor's endpointmodel="your-model-name", # Placeholder model name)print(agent.run(code_context="...code content...", user_query="Split the monolith service into microservices"))
If a vendor provides explicit cache parameters, confirm the parameter names and placement in the official documentation before adding them to the request body.
Checks Before Deployment
Long-horizon Agents usually run in a cloud-native environment composed of containers, object storage, message queues, and logging services. The specific choices depend on the team’s existing cloud environment. Before deployment, check the following items one by one:
- Least privilege: grant the service account used by the Agent only the read and write permissions required by the task. The sandbox environment must not directly access the production database.
- Network isolation: use a controlled path between the code execution environment and the model gateway, and disable external network access by default.
- Timeouts and retries: set a timeout for every tool call and cap the number of retries so that a stuck task does not continue consuming resources.
- Cost caps: set budgets for individual tasks and daily totals, and pause tasks and notify the owner when thresholds are exceeded.
- Full logging: record a summary of model input, tool call parameters, and returned results at each step, and store sensitive fields after masking them.
- Resource release: reclaim compute instances and temporary files after a task ends, and check for leftover processes.
Conclusion
Newer models allow Agents to handle longer task chains, and caching makes the cost of very long contexts calculable. Developers need to evaluate model capability, cost data, and operational safeguards in the same table. Capability, cost, and reliability all need to be quantified before a team can decide whether an Agent project is worth scaling.
