Speeding Up and Cutting Costs for Multi-Step LLM Tasks

    Multi-step LLM tasks often incur high latency and cost because end-to-end time accumulates across turns and errors propagate through chained steps. This article presents a practical scheduling approach that combines long context, four thinking levels, and a planner-executor split. It also shows how to break down latency and cost, apply optimization levers, run a document-to-code pipeline, and evaluate performance using real task samples.

    1. The bottleneck is orchestration, not a single inference call

    In development and office workflows, AI is rarely used for a single question-and-answer exchange. More often, it powers pipeline-style work: reading several documents, retrieving information, modifying code, running tests, and checking results. Such tasks have two unavoidable characteristics:

    • Latency comes from turns. End-to-end time is the sum of “number of turns × per-turn time,” not the quality of one answer.
    • Errors accumulate. If an intermediate step is wrong, later steps build on that error, and recovery cost rises with chain length.

    If model improvements only aim at “deeper single-turn reasoning,” they can hit diminishing returns. Once single-turn accuracy is sufficient, the real bottleneck may be orchestration. Instead of trying to make every call “think deeper,” it is better to establish a clear layered strategy:

    • Long context determines how much information a stage can see at once.
    • Thinking levels determine how deeply each stage is worth thinking.
    • The split between planner and executor determines who does the work and to what standard.

    This article uses three typical scenarios—turning multiple document formats into a report, code generation with automated checks, and locating defects across files—to discuss how to combine these elements into a practical and measurable scheduling scheme.

    2. Long context: making heterogeneous files readable in one pass

    2.1 What long context actually changes

    Some mainstream models have extended context windows to the million-token scale. Before such windows existed, handling multiple materials usually required a “read—summarize—read again” loop: summarize each file first, ask questions based on the summaries, then go back to the original text when information was insufficient. This approach involved many round trips and high loss; the compressed-away content might be exactly what the answer needed.

    Long context changes the way information is organized. When the window allows it, the following materials can be placed in a single call:

    • Multiple PDF reports and contract clauses;
    • Row and column structures of multiple data tables;
    • Chart screenshots and UI screenshots;
    • Audio transcripts and video subtitles.

    The model can directly perform cross-document comparison, table calculation, chart interpretation, and contextual linking, reducing the need for repeated round trips. More importantly, the materials can be reused as an “interrogable material package,” without rebuilding context every time.

    2.2 From raw files to usable context

    Multimodal content cannot enter the context window as-is; it needs preprocessing first:

    • Documents: organize by heading hierarchy, sections, and page numbers; preserve table-of-contents structure so the model can locate and cite content;
    • Tables: clarify column meanings, units, and statistical definitions; avoid mixing “quantity” and “amount” in the same column;
    • Charts: provide clear, high-resolution images with necessary axis explanations;
    • Audio and video: transcribe first, chunk by speaker or topic, then retrieve key segments as needed.

    After preprocessing, three layers of “navigation” information should be added to help the model find targets in long text:

    • A file inventory and summary index;
    • Section location information;
    • Unified task instructions and output-format constraints.

    2.3 Three hidden costs of long context

    1. Prefill and time to first token. The longer the input, the slower the first response often is. Interactive Q&A and batch offline tasks should be treated differently.
    2. Decay of effective recall. Information in the middle of a long context is often used less than information at the beginning and end. Key information should be placed first and centrally, and important requirements should be restated once at the beginning and once at the end.
    3. Attention dispersion and hallucination. The more mixed the context, the easier it is for the model to connect unrelated materials. Before ingestion, deduplicate and label sources; require the model to indicate citation locations in its output.

    Therefore, the value of long context is not about “stuffing more in,” but about “organizing well and using it reliably.”

    3. Four thinking budgets: making “how deep to think” a tunable parameter

    3.1 Why layering matters

    Recent mainstream reasoning models generally allow control over internal reasoning scale. Common forms include thinking budgets and reasoning-intensity levels. This article uniformly calls them “thinking levels.” Mainstream options roughly provide four levels: low, medium, high, and very high. The higher the level, the more tokens consumed in internal reasoning; problem-solving capability usually improves for complex problems, but latency and cost also increase.

    Using the highest level for all tasks creates two problems: simple tasks suffer from “overthinking,” greatly increasing time and cost; and interactive experience deteriorates. The core idea of layering is to match reasoning investment with task difficulty and fault tolerance.

    • Low level | Clear patterns and fixed paths
      • Suitable for field extraction, format conversion, classification and tagging, code completion, and copy polishing under established rules. Steps are mostly fixed, and short reasoning can achieve stable quality.
      • It is recommended to pair this with lightweight checks such as format validation and value-range checks, so errors are easier to detect.
    • Medium level | Routine tasks requiring some reasoning and verification
      • Suitable for cross-document summaries, common error fixes, adding tests to existing functions, and turning business requirements into structured checklists. There may be some ambiguity or need for multi-step judgment, but patterns are relatively mature.
      • Medium is usually the most natural starting point for balancing quality and cost, and can serve as the default for many business scenarios.
    • High level | Complex tasks with unclear paths and a need for exploration
      • Suitable for locating defects across files, weighing architecture options, analyzing performance bottlenecks, and algorithm design with many boundary conditions. It requires testing multiple hypotheses and gradually converging.
      • High-level results should be reviewed or combined with external verification such as tests and reviews.
    • Very high level | High-value, high-risk, low-frequency tasks
      • Suitable for complex mathematical and logical reasoning, security-sensitive code review, and justifying large-impact refactoring plans.
      • Errors in these tasks are costly, so the most reasoning investment is worthwhile. A safer practice is to add multi-candidate cross-validation beyond the very high level to avoid single-point dependence.

    The four levels can be summarized as follows:

    Level Typical characteristics Recommended default scenarios
    Low Fixed steps, verifiable per step Extraction, conversion, completion
    Medium Some reasoning, relatively mature patterns Cross-document summaries, routine fixes
    High Unclear paths, multi-hypothesis exploration Defect localization, architecture trade-offs
    Very high High value, high risk, low frequency Complex reasoning, security review

    3.3 Three common pitfalls

    • Difficulty ≠ complexity. A long-looking task does not necessarily require deep reasoning. A lengthy log may only need exception lines extracted by fixed rules, and a low level may be enough. Difficulty should be determined by the nature of the task, not by input length.
    • A level does not automatically guarantee correctness. A higher level only means a larger reasoning budget. If the problem is poorly defined or necessary information is missing, more thinking may still produce a “confident wrong answer.” Check whether the input is sufficient before starting.
    • Dynamic adjustment is more effective than static configuration. Different stages of the same task may need different ideal levels. Decomposition and planning stages need higher reasoning, while mechanical execution stages can drop to low. Setting levels per stage is usually more economical than fixing one level for the entire chain.

    3.4 Thinking levels, model size, and verification

    Thinking levels are not the only quality lever; they should be used together with two others:

    • Model size. For medium-difficulty tasks, a smaller model with a medium level can often approach the effect of a larger model with a high level. Pushing both to the maximum usually yields limited incremental gains while costs rise additively.
    • Verification. Replacing some reasoning investment with executable external verification—such as test passes, successful compilation, and format validation—is often more cost-effective than simply raising the level.

    The decision principle is simple: a level buys reasoning depth, while verification buys correctness. They are complementary, not substitutes.

    4. Planner + executor: two-model division of labor

    4.1 Division of responsibilities

    Multi-step tasks can be split into two roles:

    • Planner: responsible for understanding and decomposing tasks, making plans, handling difficult branches, and defining acceptance criteria. It is invoked less frequently but has higher per-call value, making it suitable for a stronger model or a higher level.
    • Executor: responsible for writing code, running tests, organizing retrieval results, formatting output, and other verifiable, pattern-based work. It is invoked more frequently but has lower per-call value, making it suitable for a faster and cheaper model or a lower level.

    This is not about letting a weaker model “fill the gap”; it is about spending every dollar where it matters most. In complex project development, the idea of a main model handling planning and dispatching subtasks to specialized execution units has been widely adopted.

    4.2 Boundary conditions for two-model division

    The two-model split works when three conditions are met:

    1. The task can be decomposed. It can be split into relatively independent subtasks with clear input-output contracts.
    2. The results can be verified. Subtask outputs can be checked objectively through compilation, testing, format validation, and other means, rather than relying only on model self-assessment.
    3. Rework cost is controllable. When execution fails, there is a clear escalation path and errors do not propagate indefinitely.

    If the task is highly coupled and cannot be split, or if outputs are hard to verify—such as creative copy requiring subjective judgment—the two-model split may have limited benefit or may even backfire due to communication overhead.

    4.3 Common failure modes

    • Missing acceptance criteria. The executor produces “seemingly completed” output without test fallback, and the problem is passed downstream.
    • Unclear responsibility. The planner gives vague instructions such as “optimize this part,” and the executor has to guess.
    • Distorted feedback. When execution fails, only “test failed” is returned to the planner, without error logs or reproduction details, so the next plan circles in place.

    The corresponding improvements are: establish automated acceptance gates; require the planner to output structured task descriptions covering goals, constraints, input/output formats, and acceptance methods; and structure key failure logs before returning them to the planner.

    5. Speed and cost: making trade-offs explicit

    5.1 Breaking down latency and cost

    End-to-end latency for a single call can be approximately decomposed into:

    • Prefill stage: processing input and building context representation; time grows with input length;
    • Reasoning stage: higher thinking levels take longer;
    • Generation stage: more output tokens take longer;
    • External steps: tool calls, sandbox execution, network requests, and so on.

    Cost is priced separately by input tokens, thinking tokens, and output tokens. On many platforms, thinking tokens are billed separately or counted as output tokens; actual rules should follow the platform’s billing policy.

    5.2 Cost structures of three typical forms

    When these factors are viewed in different scenarios, the dominant factors are not the same:

    • Document-intensive (for example, organizing long reports): input is much larger than output, and cost is mainly determined by input tokens. The focus of cost reduction is compressing context and reusing caches.
    • Reasoning-intensive (for example, complex code generation and refactoring): output, including thinking tokens, dominates. The focus of control is setting thinking levels reasonably and avoiding unnecessary overthinking.
    • Multi-step pipelines: each step may not look large, but when multiplied across steps, the total can be significant, amplifying the impact of scheduling strategy.

    The following illustrative code breaks latency and cost into checkable components, making it easier to estimate capacity and budget before launch:

    1. # This is an illustrative estimation model. Actual pricing rules depend on the chosen platform.
    2. # req contains the following fields (in tokens): input_tokens / thinking_tokens / output_tokens
    3. # price_* are platform-published prices, in yuan per million tokens; convert units as needed
    4. def estimate(req):
    5. """Estimate latency (seconds) and cost (yuan) for a single call."""
    6. # latency = prefill + reasoning + decode; coefficients are placeholders and should be calibrated with real measurements
    7. latency_s = (
    8. PREFILL_SEC_PER_1K * req.input_tokens / 1000
    9. + THINK_SEC_PER_1K * req.thinking_tokens / 1000
    10. + DECODE_SEC_PER_1K * req.output_tokens / 1000
    11. )
    12. # Cost: many platforms count thinking tokens as output tokens; some platforms set a separate thinking-token price
    13. cost_yuan = (
    14. req.input_tokens * price_input
    15. + (req.thinking_tokens + req.output_tokens) * price_output
    16. ) / 1_000_000
    17. return latency_s, cost_yuan

    Note that the example only formalizes the pricing method. Real calls must also account for retries, cache-hit discounts, and failed calls. Accurate figures should be based on billing statements and platform pricing documentation.

    5.3 Use “cost per successful task” as the standard

    Lowering “per-token unit price” does not mean lower “cost per successful task.” If a cheap solution requires multiple rounds of rework, its total cost may be higher. It is recommended to use “cost per successful task” as the core metric, include retry counts in the accounting, and evaluate pass rate and latency together.

    5.4 Five practical optimization levers

    • Compress context: remove duplicate content and keep only fragments relevant to the current subtask;
    • Reuse prefixes: put fixed content such as system prompts, tool descriptions, and project rules at the beginning of the context to improve prefix-cache hits. Specific hit rules and discounts depend on the platform;
    • Routing by level: send simple tasks to low levels or smaller models, and escalate complex tasks as needed;
    • Control output: explicitly require conclusions or patches directly, reducing pleasantries and repeated explanations;
    • Batch and asynchronous processing: offline batch jobs can tolerate longer latency, use higher levels more comfortably, and avoid occupying interactive quotas.

    6. Practical case: a multi-step pipeline from documents to code

    Here, the methods above are applied to a concrete chain. The requirement is to extract change requirements from multiple requirement documents, design descriptions, and data tables, modify the code, and verify automatically.

    Stage 1: Document parsing and unified organization

    • Low level + executor model;
    • Extract structured key points from PDFs, tables, and screenshots, and output them in unified fields;
    • Use format validation to confirm required fields are complete.

    Stage 2: Solution design and task decomposition

    • High level + planner model;
    • Compare requirements with the existing code structure and split them into atomic tasks, such as “modify interface definitions,” “add boundary validation,” and “add test cases”;
    • Output a structured task list.

    Stage 3: Code modification and testing

    • Low to medium level + executor model;
    • Generate patches for each task and run tests automatically;
    • On failure, escalate one level with test logs; if it still fails, return to the planner to re-decompose.

    Stage 4: Change review

    • High level + planner model;
    • Check cross-file call consistency, potential regression risks, and boundary conditions.

    Stage 5: Output organization

    • Low level;
    • Summarize change lists, test results, and remaining risks, and format them into a standard report.

    In this chain, high-value reasoning appears only in Stages 2 and 4; the other stages are completed at lower-cost levels, allowing speed, quality, and cost to be balanced simultaneously.

    7. Layered scheduling skeleton: putting the strategy into code

    The following illustrative scheduling skeleton is independent of specific models and explains how to put the strategy into practice. When integrating, replace call_model with the invocation interface of the chosen platform:

    1. # This is an illustrative code skeleton, independent of specific models and platforms.
    2. BANDS = {
    3. "low": {"model": EXECUTOR_MODEL, "thinking": "low"},
    4. "medium": {"model": EXECUTOR_MODEL, "thinking": "medium"},
    5. "high": {"model": PLANNER_MODEL, "thinking": "high"},
    6. "xhigh": {"model": PLANNER_MODEL, "thinking": "xhigh"},
    7. }
    8. def handle(task):
    9. band = BANDS[route(task)] # 1. Routing: classify first, then choose a level
    10. for attempt in range(MAX_RETRY): # 2. Execution + automatic acceptance
    11. out = call_model(band, task)
    12. if verify(out): # compile / test / format validation
    13. return out
    14. if attempt == 0:
    15. band = escalate(band) # 3. Escalate one level after failure
    16. else:
    17. break
    18. plan = call_model(BANDS["high"], task) # 4. Fallback: return to planner for re-decomposition
    19. return call_model(BANDS["medium"], plan)

    The skeleton has three design points:

    • Light first, heavy later: routing should be as cheap as possible and can be done with rules, keywords, or a quick small-model judgment;
    • Verification before escalation: solve problems with tests first rather than raising the level;
    • Escalation has limits: both retry counts and escalation magnitude should have limits to avoid individual tasks consuming the overall budget.

    Context assembly also needs a clear strategy, as shown below:

    1. def build_context(files, goal):
    2. digests = [parse(f) for f in files] # PDF / tables / images / audio-video transcripts
    3. # Retrieve by task goal, keep source labels for result traceability
    4. selected = retrieve(digests, query=goal, top_k=CONTEXT_BUDGET)
    5. return render(selected)

    8. Evaluation and continuous tuning

    8.1 Build benchmarks from real tasks

    Comprehensive intelligence indices published by vendors reflect overall capability trends, but it is difficult for them to cover the task distribution and acceptance standards of a specific business. A more reliable approach is to sample from real work and build a small but scenario-oriented evaluation set:

    • Sample sources: historical tickets, defect records, and repetitive document tasks;
    • Suggested size: no fewer than 20–30 items per typical scenario;
    • Labels: difficulty level, expected outputs, and acceptance criteria.

    8.2 Focus on four types of metrics

    • Quality: first-pass rate and final pass rate;
    • Latency: median end-to-end time and P95;
    • Cost: cost per successful task and retry rate;
    • Stability: consistency of results across multiple runs.

    8.3 Evaluation design and considerations

    Use a matrix of “difficulty level × context strategy” to compare different combinations. Because reasoning results are stochastic, it is recommended to sample and repeat multiple times, then compare averages and variation ranges instead of drawing conclusions from a single run. A reference comparison design is shown below:

    Option Reasoning level Context strategy Expected advantages Main risks
    A High Full long context Complete information, simple implementation High latency and input cost
    B Low/medium Structured retrieval context Fast, cheap, easy to parallelize Retrieval omissions may reduce quality
    C (recommended baseline) Layered routing Structured retrieval + full fallback Dynamic balance by difficulty More complex routing and scheduling logic

    Routing thresholds and level mappings are not fixed. After model iteration, prompt adjustments, or business scenario changes, regression evaluation should be run promptly and scheduling configurations updated.

    8.3.1 General cloud capabilities that can help

    The scheduling system itself can also rely on general cloud platform capabilities:

    • File processing: raw documents and outputs can be stored in object storage for parsing and archiving;
    • Task decoupling: long-running chains can be split into asynchronous tasks through message queues to avoid blocking interactive requests;
    • Elastic execution: compute-heavy steps such as parsing, compilation, and testing can run on elastic compute resources such as container platforms or function computing;
    • Observability: logs and monitoring/alerting can track changes in latency, failure rate, and token consumption.

    9. Conclusion

    Long context, layered thinking budgets, and the planner-executor split all answer the same question: how to use limited reasoning resources where they need to “think clearly” most.

    • Long context solves “what can be seen”;
    • Thinking levels solve “whether thinking is worth it”;
    • The planner-executor split solves “whether it is done correctly.”

    The three are not “the more expensive the better” or “the deeper the better.” They must be measured repeatedly and calibrated continuously in real tasks. If you also have experience or questions about speeding up and reducing costs for multi-step tasks, feel free to share them in the comments.