LLM API Pricing and Long-Running AI Agents: A Practical Guide
This guide explains how structured LLM API pricing works and how to build long-running AI agents around it. It breaks down the three billing dimensions—cached input, uncached input, and output—and shows why output is the most expensive resource. It covers prefix stabilization for context caching, the six capability layers of an agent harness, multi-agent role separation, and a decision framework for balancing cost, latency, and reliability. It also lists common mistakes, such as assuming caching happens automatically or running unattended tasks without a budget.
1. From Pay-Per-Token to Structured Pricing: Read the Bill Before Optimizing
LLM API billing has evolved from simple linear charges based on token count into a structured model. A typical pricing scheme has three dimensions: cached input, uncached input, and model-generated output. The per-unit prices of these three often differ by an order of magnitude, which directly determines the real cost curve of an application.
Take a common set of price relationships in the industry as an example: cached input costs about 1.3 per million tokens, uncached input about 13, and output about 68. The engineering implications of these numbers are clear:
- Output is the most expensive resource. Compressing output length, avoiding verbose explanations, and returning structured results are the first priority for cost reduction.
- Uncached input is the second-largest cost source. Repeatedly stuffing large system prompts, knowledge base snippets, and tool definitions into the context causes linear or even quadratic waste.
- Cached input is extremely cheap, which means a “reusable stable prefix” is an asset you can deliberately design.
In addition, the market commonly offers a “high-speed” capability that keeps model capability the same but costs about twice the standard price. This is not a new model, but a channel that trades budget for lower latency and higher throughput. It suits interactive scenarios; offline batch processing should stick to the standard channel.
2. Context Caching: Turn “Repeated Input” into a Reusable Asset
Cache pricing depends on prefix stability. The common industry implementation logic is: if a segment of content from the beginning of a request is exactly the same as in historical requests, it counts as a cache hit. So the engineering task is to “solidify the prefix.”
[Stable prefix] System instructions + tool schema + domain rules + a few fixed examples[Semi-stable] Knowledge base retrieval results (split by version)[Volatile] User's current question, timestamp, random ID
Three practical rules:
- Put volatile content last. Place timestamps, session IDs, and random numbers at the end of the prompt to avoid polluting the prefix.
- Version knowledge snippets. When the knowledge base updates, switch the whole version number rather than editing entries in place, otherwise the cache will keep invalidating.
- Control prefix size. Cache hits are cheap but not free. An overly long prefix still pushes up the absolute cost of each call and eats into the effective context window.
An illustrative call structure (pseudocode, expressing only the idea of ordering):
prefix = build_stable_prefix(tools_schema, domain_rules) # unchanged over the long termcontext = knowledge_base.get(version=kb_version) # switch by versionmessages = [{"role": "system", "content": prefix},{"role": "system", "content": context},{"role": "user", "content": f"{question}\n[req_id={req_id}]"},]resp = client.chat(model=model_name, messages=messages)
3. Long-Running Tasks: Why Agents Need a “Harness,” Not Just a Model
A single question-and-answer turn is stateless, but agents in real business scenarios run for hours or even days: continuously reading logs, polling tasks, fixing pipelines, and following up on tickets. The difficulty of this kind of workload lies not in the model’s intelligence but in the outer structure that hosts the model’s execution, commonly called a harness in the industry. It contains at least six layers of capability:
- Loop control: multi-turn driving of plan-execute-observe-reflect, plus termination condition checks;
- State persistence: writing intermediate conclusions to external storage so the process can resume from a checkpoint after a restart;
- Tools and sandbox: a controlled execution environment, permission boundaries, and network egress restrictions;
- Layered memory: short-term context, mid-term summaries, and long-term vector retrieval, each with its own role;
- Concurrency and collaboration: task decomposition, result aggregation, and conflict resolution;
- Observability: full-chain tracing, token and cost metering, and failure retries and alerts.
Providing the harness as cloud-hosted managed infrastructure creates value by separating these six layers from business code, so developers only need to describe goals and constraints. It can be expressed in a configurable way:
task:goal: "Continuously inspect the build pipeline and submit fix suggestions on failure"schedule: "7x24"max_steps: 2000budget:max_output_tokens: 500000agents:- role: planner- role: executor- role: reviewerpersistence:checkpoint_every: 20
4. Multi-Agent Collaboration: Splitting Boundaries Matters More Than Piling Up Agents
Multi-agent systems are not about copying one big task into N copies, but about splitting along “context boundaries” and “cost of failure.” A common and effective division into three roles is: a planner handles decomposition and definition of acceptance criteria; an executor calls tools to produce real side effects; a reviewer handles verification and rollback suggestions. Collaboration should follow two principles: first, separate read-only and write permissions, and high-risk actions must go through the reviewer; second, pass shared state through external storage rather than letting agents talk freely to each other, to avoid error accumulation and context pollution.
5. The Triangle of Cost, Latency, and Reliability
Here is a practical decision framework:
- Interactive, strongly real-time scenarios: choose the high-speed channel and accept roughly double the unit price in exchange for response experience;
- Offline batch processing and large-scale extraction: standard channel + prefix caching + output length limit;
- Long-running unattended tasks: set a step limit, token budget, and per-task timeout to prevent runaway loops;
- Unified metering: bring cache hit rate, average output length, and per-task cost into monitoring and alerting, and connect with common cloud product capabilities such as container platforms, logging services, message queues, and object storage to form a closed loop.
6. Common Mistakes
- Assuming “cache hits” happen automatically: any change anywhere in the prefix invalidates the whole segment;
- Optimizing only model selection while ignoring output length: output has the highest unit price, so the gains are the most obvious;
- Not setting a budget for long-running tasks: cost overruns in unattended scenarios are the most common incident;
- Giving agents direct production write permissions: default to least privilege and keep a human confirmation step.
In summary, structured pricing requires developers to design prompts and knowledge organization around “prefix stability,” while long-running agents require the runtime support layer to be settled as infrastructure. Combining the two is what makes it possible to reliably deliver 7x24 uninterrupted agent business with predictable costs.
