LLM Inference Costs and Long-Horizon Tasks: Engineering Trade-offs in Practice
This article explains how to evaluate large language models for production by weighing task success against inference cost. It covers the token cost of long chain-of-thought reasoning, how to measure cost per correct answer, how to choose between reasoning and non-reasoning modes, how output limits can cause truncation, tiered routing, long-document processing, closed-loop coding agents, and reproducible model evaluation.
1. Background: Evaluate Capability and Cost Together
After large language models enter production, selection criteria have shifted from “Can it answer?” to “Can it complete tasks reliably, and is the spending under control?” The same model may use only a few hundred tokens on a simple question, but tens of thousands of tokens on a complex reasoning or multi-step coding task. Looking only at the per-call unit price easily underestimates the real cost.
When a model version is updated, a common change is stronger long-horizon reasoning, along with a longer internal thinking process. This has three direct effects: answer quality improves, output length increases, and the risk of exceeding limits in evaluations and online calls rises. The sections below start from the technical mechanisms and explain how to assess and respond to each effect.
2. Benefits and Costs of Long Chain-of-Thought
2.1 Why Long Chain-of-Thought Improves Quality
In multi-step reasoning tasks, the model must keep state across intermediate steps, try different paths, and backtrack. Chain of thought (CoT) makes intermediate derivations explicit, which gives the model room to work like a scratchpad. For problems with several feasible solutions, more thorough exploration makes it more likely to find the full solution set, rather than returning a single answer that only looks plausible.
These gains usually appear in the following areas:
- Logic puzzles with many constraints, where more boundary cases are covered;
- Math and planning problems, where omissions caused by converging too early are reduced;
- Code generation, where exception branches and dependencies are considered earlier.
2.2 Token Consumption Gets Amplified
The cost of long chain-of-thought is a significant increase in output tokens. Output tokens are usually priced higher than input tokens, and tokens produced during reasoning are often not shown to the user but are still billed. The cost of a single call can therefore be estimated with the following formula:
Total cost = input tokens × input price + output tokens × output price
Output tokens include both the visible answer and the internal reasoning. When the reasoning budget rises from a few thousand to tens of thousands of tokens, cost grows roughly linearly with it.
Example code (prices are placeholder values. Replace them with the billing rules of the service you use):
def estimate_cost(input_tokens: int, output_tokens: int,input_price_per_m: float, output_price_per_m: float) -> float:"""Estimate the cost of a single call from the price per million tokens. The return value uses the same unit as the price."""if input_tokens < 0 or output_tokens < 0:raise ValueError("Token count cannot be negative")return (input_tokens * input_price_per_m + output_tokens * output_price_per_m) / 1_000_000
When running batch evaluations, connect this estimation function to your logs, and track the mean, median, and P90 for each question rather than only the average. Averages are easily pulled up by a few extremely long outputs. Medians and percentiles better reflect typical cost.
2.3 Measure Efficiency with Cost per Correct Answer
At the same accuracy, different configurations may consume several times as many reasoning tokens. “Getting it right” and “getting it right at a given cost” are two separate dimensions. Engineering teams should record both accuracy and the average token consumption per correct answer. The second metric can be defined as:
Cost per correct answer = total token consumption / number of correct answers
This metric directly compares the cost-effectiveness of different configurations. It also exposes cases where accuracy is close but cost is several times higher.
3. Choosing Between Reasoning and Non-Reasoning Modes
Many models offer both a reasoning mode and a non-reasoning mode. Reasoning mode works through the problem before answering, which suits complex questions. Non-reasoning mode answers directly, with lower latency and lower cost, which suits format conversion, simple Q&A, and high-concurrency scenarios. The boundary between the two modes is not always clear. A non-reasoning mode may also increase its internal computation on hard problems on its own.
3.1 Truncation Caused by Output Limits
Setting a maximum output token limit is a basic way to control cost, but it introduces a new problem. When the model does not finish its answer within the limit, the result is truncated and may not be parseable. In evaluations, such samples are usually scored as invalid or zero.
Output limits should therefore match the task type:
- For simple tasks, set a lower limit to prevent output from growing abnormally;
- For complex tasks, first collect the historical distribution, then set the limit at a level that covers most normal cases;
- Record truncated samples separately, and distinguish “wrong answer” from “unfinished answer.” The two call for completely different fixes.
3.2 Tiered Routing
In practice, tiered routing is common. A lightweight rule set or small model first estimates question difficulty. Simple questions go to non-reasoning mode, and complex questions go to reasoning mode with a higher limit. Routing rules should be checked regularly by replaying real traffic, so that errors in the difficulty judgment itself are caught.
Illustrative pseudocode (values are examples only and should be calculated from your own task distribution):
def route(task: dict) -> dict:if task["type"] in {"format", "extract", "faq"}:return {"mode": "fast", "max_output_tokens": 2048}if task.get("steps", 1) >= 5 or task["type"] == "reasoning":return {"mode": "deep", "max_output_tokens": 32768}return {"mode": "fast", "max_output_tokens": 8192}
4. Engineering Approaches for Long Text and Files
Long-context capability lets a model read more material at once, but being able to fit material into the context does not mean the model will use it well. In long inputs, key information can be buried under irrelevant passages, and citation errors and omissions increase.
We recommend the following workflow:
- Document splitting: Split by chapter or semantic boundary, and keep the heading hierarchy as metadata;
- Retrieval: Use vector or keyword search to find passages relevant to the question, and send only the necessary content to the model;
- Structured extraction: Require the model to output a fixed structure so that programs can validate it later;
- Citation tracing: Attach the source location to each conclusion so that humans can review it.
The same approach applies to data analysis. A program should perform table calculations. The model should explain the statistical definitions, propose the analysis approach, and write the conclusions, rather than handling large amounts of numerical computation.
5. Coding Agents: From One-Shot Generation to Closed-Loop Debugging
Single-shot code generation works well for small functions and standalone scripts. Real projects, however, usually involve multiple files, dependency configurations, existing conventions, and incomplete tests. To judge whether a coding agent is usable, the key question is whether it can form a closed loop of “generate, run, observe, and fix.”
5.1 Basic Structure of the Loop
def agent_loop(task, repo, max_rounds=5):context = repo.collect_context(task)for round_idx in range(max_rounds):patch = llm_generate_patch(task, context)repo.apply_patch(patch)result = repo.run_tests()if result.passed:return {"status": "ok", "rounds": round_idx + 1}context = context.append(result.error_summary)repo.revert_patch(patch)return {"status": "failed", "rounds": max_rounds}
This pseudocode has three key points. First, test results must flow back into the context. Otherwise, the model cannot correct its output based on the actual errors. Second, the number of repair rounds should be capped to avoid consuming tokens indefinitely. Third, a failed attempt should be rolled back so the repository state can be restored.
5.2 Metrics for Debugging Ability
When evaluating a coding agent, do not look only at the first-try pass rate. Also observe the following:
- The difference between the first-round pass rate and the pass rate after multiple repair rounds;
- Whether error messages accurately point to the specific file and line number;
- Whether the scope of changes goes beyond what the task requires;
- Token consumption and time spent per task.
Routine frontend and backend tasks usually form stable closed loops more easily. Tasks involving concurrency, external service integration, and implicit conventions still need stricter testing and human review.
6. Building Reproducible Model Evaluations
When comparing models, consistency of evaluation conditions matters more than the conclusion itself. An evaluation report should state the following:
- Keep the question set and scoring rules fixed, and do not adjust them for each model;
- Apply the same output limit, and state how over-limit samples are handled;
- For tasks with strong randomness, sample multiple times and report the median rather than a single result;
- Report accuracy, token consumption, and latency together;
- Keep raw outputs so that scoring can be reviewed later.
Looking only at rankings easily hides these preconditions. The gap between two scores may stem from differences in test conditions.
