LLM API Selection: Context Windows, Output Budgets, and Agent Testing

    A practical, vendor-neutral guide to choosing an LLM API. It breaks down four easy-to-misread specifications—context window, single-output budget, reasoning mechanisms, and input/output pricing ratios—and explains why the cheapest tier doesn't always win. It covers a recommended trial order, a generic four-tier comparison, how output truncation and shared budgets affect results, why multi-step agent costs grow quadratically, and a six-step business re-testing process with a selection checklist. Examples are generic; actual values should follow the platform's official documentation.

    Today’s mainstream LLM services generally accept text, image, and even video inputs, and offer function calling (tool calling). Context windows have commonly reached the million-token scale, and billing typically follows “separate pricing for input and output.” Spec sheets look similar, yet real-world experience can differ dramatically: for the same document-extraction task, some models return valid JSON on the first try while others require prompt tweaks and repeated retries; for the same agent task, a single round may cost a few cents or a few dollars.

    The gap often comes not from the brand but from a few specifications that are easy to misread: the context window, the single-output budget, the reasoning mechanism, and the pricing ratio between input and output. This article breaks down these four factors one by one and offers an actionable selection workflow and re-testing method. It does not cover any specific vendor or product; the specifications are generic examples only, and actual values should follow the official documentation of the platform you use.

    1. Core principle: look at the input first, then calculate the cost

    Price matters, but two questions are worth asking first: can the cheaper tier get it right on the first try? Can the more expensive tier reduce rework?

    The direct cost of a single call is only part of the total cost. A complete cost calculation includes at least four components:

    • Direct call fees: input tokens and output tokens priced separately.
    • Retry and repair costs: invalid output formats, missing fields, and erroneous tool-call arguments all trigger retries, and input tokens are often consumed repeatedly.
    • Human fallback costs: samples that fail automatic validation go to manual handling, and this hidden cost is usually far higher than the API fee itself.
    • Operations and latency costs: end-to-end latency affects user wait time and timeout rates, and unstable responses require investment in monitoring and fallback mechanisms.

    Therefore, the selection order should be “capability gating → first-pass rate → total cost.” The single-output budget sets the capability ceiling: once the generation length a task requires exceeds this ceiling, the output is truncated and any further effectiveness comparison becomes meaningless.

    Models in every tier keep iterating, and rankings can change at any time; the only reliable basis is testing on your own tasks. Until then, you can organize trials in the following order to narrow down candidates with fewer calls:

    1. High-frequency text-and-image and structured tasks: First use a lightweight tier to establish a cost baseline, then gradually test complex samples. These tasks have short single inputs, fixed output formats, and high call volumes, so unit price and stability are the main concerns.
    2. Budget-sensitive tasks that also require longer generation: Include tiers with a larger single-output budget in your candidates. For long-form writing, multi-file code generation, and similar tasks, output that exceeds the limit gets truncated, and no low unit price can rescue a failed task.
    3. Tasks that need to understand video directly: First screen models with native video input support. Models without this capability can only take a detour by extracting frames into images, and frame rate, resolution choices, and additional call volumes all affect fidelity and cost.
    4. Multi-step agent tasks: First use the first three categories to eliminate clearly unsuitable candidates, then make the final choice with the same evaluation set.

    3. A generic comparison of four common specification categories

    The model lineups across different cloud platforms can broadly be grouped into four tiers. The table below illustrates the specification dimensions and does not represent any specific product.

    Category Input types Context window (example value) Single-output budget (example)
    Flagship multimodal tier Text, image, video 1,000,000 tokens ~131,072 without thinking; ~262,144 with thinking
    Lightweight text-and-image tier Text, image 1M, single-input limit ~960k ~64k
    Large-output tier Text, image 1M ~384K
    Long-context multimodal tier Text, image, video 1,048,576 tokens ~131,072 by default, bounded by remaining context

    These numbers come from common magnitudes in public documentation and are used only to establish a comparison framework. Suffixes like “Max” and “Flash” in names belong to each vendor’s product-tiering scheme; context length also does not directly indicate agent success rate, and has no necessary correspondence with effectiveness or price.

    Two details deserve attention when reading this table:

    • Watch the units. “1M” may mean one million or 1024×1024, and the two differ by about 4.9%—enough to decide whether a request succeeds in very-long-input scenarios. Definitions of K and M also differ slightly across vendors, so don’t assume them to be exactly equal.
    • The display name is not the call name. Calls use the API model identifier, which usually differs from the product display name. Query documentation and make calls by the identifier, and avoid writing the display name directly into code.

    Input side: context window ≠ single-input limit

    All four tiers have million-scale contexts, but “how much can be input at once” is not the same as “how large the context window is.” Some models set a separate single-input limit slightly below the context window, and long context is mainly reflected in the accumulated history of multi-turn conversations. If a program assembles input according to the window size, it may fail when approaching the limit.

    Two engineering rules of thumb:

    • Compute boundaries in binary terms and leave a safety margin. When converting the limit to an integer, approximating 1,048,576 as 1,000,000 and then adding extra padding may already push the actual concatenation over the boundary. A safer approach is to use the exact value given in the documentation (or the information returned by platform validation) and reserve a few tokens at the tail.
    • Multimodal input carries extra overhead. Images are typically encoded into a set of tokens based on resolution, and video is typically converted into image tokens by frame count or duration; both occupy the context. For a long document mixing text and images, actual consumption is often markedly higher than a text-only count.

    Output side: output budget ≠ final answer length

    The output budget (commonly the parameter named max_tokens) determines how far a single generation can go. In models that support a thinking mode, it usually covers all generated content from the first output token to the end, not just the final answer. Two typical mechanisms are:

    • Shared budget: the chain of thought and the final answer share the same allowance. Complex reasoning consumes many tokens first, leaving less for the actual answer; in extreme cases the ceiling is hit before the chain of thought finishes, and the user gets no usable answer.
    • Input and generation share the total window: the input and the current round’s generation together occupy the context window, and the actual generatable length is roughly “window size − current input length.” The more complex the task and the more intermediate tool results returned, the less space remains for the final output—you cannot read a million-token context as “fill a million input tokens and then output a million.”

    The two mechanisms require different parameter settings:

    1. # Illustrative only; exact fields and limits follow the chosen platform's documentation
    2. def build_request(prompt, mode):
    3. if mode == "thinking_shared":
    4. # Chain-of-thought and the final answer share the output budget: raise it for complex tasks
    5. # or switch to structured output / stepwise generation to avoid exhausting the budget during reasoning
    6. return {
    7. "model": "<reasoning model ID>",
    8. "messages": [{"role": "user", "content": prompt}],
    9. "max_tokens": 8192,
    10. }
    11. # Input and generation share the total window: compute available output from the actual input length
    12. available = context_window - estimate_tokens(prompt) - safety_margin
    13. return {
    14. "model": "<standard model ID>",
    15. "messages": [{"role": "user", "content": prompt}],
    16. "max_tokens": min(target_length, available),
    17. }

    Constraining tasks with the output budget, rather than letting the model improvise, improves both controllability and predictability:

    • Work backward from the output form to set the budget: for a single JSON, reserve 1–2 times the total field length; for a long article, divide the target word count by the average number of characters covered per token.
    • Prevent truncation of structured output: truncated JSON cannot be parsed, so add JSON validation on top of constraining the generation length; for required fields, enable a structured-output mode (such as JSON Schema), with actual support per the documentation.
    • Judge whether an answer was truncated: check the finish reason (e.g., finish_reason being length), and whether JSON brackets are closed and sentences are complete.
    • Generate long content in chunks: plan chapters or sections in advance, call them separately, then merge, to avoid hitting the ceiling in a single output.

    Tool calling: capability lies in the calling contract, not the name

    All four tiers support function calling, which means all four categories of tasks can connect to an agent. But whether tool calling lands reliably depends on whether several common capabilities are correctly implemented:

    • Tool-definition format and parameter schema validation;
    • Parallel calling and how call results are fed back;
    • Whether tool history is fully preserved across multi-turn conversations;
    • Whether structured output can be combined with tool calling.

    These capabilities perform similarly on most platforms; what really opens the gap is instruction-following, error recovery, and long-context stability in long tasks.

    4. Cost and latency: unit price is only the starting point

    1. Unit price and token amplification

    Output tokens are usually priced higher than input. Although reasoning models don’t necessarily have a higher per-token price, the number of output tokens increases markedly; if a platform prices reasoning content separately, reasoning tokens should be accounted for separately too. When estimating real cost, clarify at least these premises:

    • Input token unit price and output token unit price;
    • Average input length, including the system prompt, tool definitions, conversation history, and current input;
    • Average output length, distinguishing the final answer from thinking content;
    • Average number of rounds and retry rate;
    • Whether cache is hit, and the pricing rules for cache reads and writes.

    2. Quadratic accumulation in agents

    In a typical agent loop, every round resends the full history and tool results to the model. Counting L new tokens per round on average, the cumulative input tokens for an N-round task is about L × N × (N + 1) / 2—doubling the rounds makes the cumulative input roughly 4 times larger. The cost of a multi-step agent comes mainly from here, not just from the model’s unit price.

    Below is a minimal agent loop illustration that deliberately omits business logic and focuses on recording per-step overhead with observable counters:

    1. # Minimal tool-calling loop; add timeouts, error handling, and tool allowlist checks in production
    2. import json
    3. def run_agent(client, tools, user_task, max_steps=8):
    4. messages = [
    5. {"role": "system", "content": "You may obtain information only through the given tools and must not fabricate results."},
    6. {"role": "user", "content": user_task},
    7. ]
    8. total_in = total_out = total_reasoning = 0
    9. for step in range(max_steps):
    10. resp = client.create(
    11. model="<model ID>",
    12. messages=messages,
    13. tools=tools,
    14. max_tokens=4096,
    15. )
    16. # Usage field locations differ across platforms; follow the official response documentation
    17. usage = resp.usage
    18. total_in += usage.prompt_tokens
    19. total_out += usage.completion_tokens
    20. total_reasoning += getattr(usage, "reasoning_tokens", 0)
    21. tool_calls = resp.tool_calls or []
    22. messages.append(resp.message)
    23. if not tool_calls:
    24. return {
    25. "answer": resp.content,
    26. "steps": step + 1,
    27. "tokens": {"input": total_in, "output": total_out,
    28. "reasoning": total_reasoning},
    29. }
    30. # Execute tools from the allowlist, append the results, and proceed to the next round
    31. for call in tool_calls:
    32. if call.function.name not in {t["name"] for t in tools}:
    33. result = {"error": "Unauthorized tool"}
    34. else:
    35. args = json.loads(call.function.arguments or "{}")
    36. result = safe_execute(call.function.name, args) # Implemented on the business side
    37. messages.append({
    38. "role": "tool",
    39. "tool_call_id": call.id,
    40. "content": json.dumps(result, ensure_ascii=False),
    41. })
    42. raise RuntimeError("Agent did not complete the task within the step limit")

    Plugging models from different tiers into the same run_agent and recording the same metrics gives a side-by-side comparison. The following code shows how to estimate the cost per thousand tasks from measured data. Unit prices are placeholders only; replace them with actual quotes:

    1. # Per-tier prices are placeholders; replace them with actual quotes
    2. PRICING = {
    3. "light": {"in": 0.0004, "out": 0.0016},
    4. "balanced": {"in": 0.0008, "out": 0.0032},
    5. "large_out": {"in": 0.0010, "out": 0.0040},
    6. "reasoning": {"in": 0.0020, "out": 0.0080},
    7. }
    8. def estimate(model_key, metrics, calls=1000):
    9. price = PRICING[model_key]
    10. per_call = (metrics["avg_input_tokens"] * price["in"]
    11. + metrics["avg_output_tokens"] * price["out"])
    12. # Total cost: call fees + retry fees + amortized human fallback
    13. retried = per_call * (1 + metrics["retry_rate"])
    14. human = metrics["manual_rate"] * metrics["manual_cost_per_case"]
    15. total = calls * (retried + human)
    16. return {"per-task direct cost": round(per_call, 4),
    17. "cost per 1000 tasks": round(total, 2)}
    1. def cumulative_input_tokens(rounds, tokens_per_round):
    2. """Cumulative input tokens for N tool-call rounds: O(N^2)"""
    3. return rounds * (rounds + 1) // 2 * tokens_per_round
    4. for n in (5, 10, 20):
    5. print(n, cumulative_input_tokens(n, 2000))
    6. # Example output: 5 -> 30000; 10 -> 110000; 20 -> 420000

    When comparing, use “total cost / successful tasks”—divide the total cost by the number of successful tasks. A model with the lowest unit price but a high retry rate does not necessarily have the lowest cost per successful item.

    3. Latency and stability

    Multimodal input, thinking mode, and long context all lengthen time to first token; total output time is directly related to output length. High-frequency interactive scenarios (such as customer service and instant Q&A) should prioritize the first-token latency and rate-limiting policy of the lightweight tier; batch-processing scenarios (such as document archiving and offline reports) can prioritize throughput and concurrency quotas, and use asynchronous task queues to smooth peaks and fill valleys.

    5. Engineering essentials for agent scenarios

    1. Correctness of tool calling: whether arguments are valid, whether required fields are missing, whether nonexistent tools are called, and whether the model can self-correct across multiple turns based on tool results.
    2. Compatibility of structured output with tool calling: whether it can return well-formed JSON while calling tools, and whether output can be constrained by a schema.
    3. Instruction-following under long context: whether the system prompt and key constraints remain effective near the window limit.
    4. Error recovery: after a tool error or timeout, whether the model can read the error message and choose to retry, switch paths, or honestly report failure.
    5. Cost and rounds: whether the task converges within a reasonable number of steps, and whether an ineffective loop that repeatedly calls the same tool appears.

    Whichever tier you choose, the following engineering practices are worth adopting:

    • Keep tool results concise: return only necessary fields, truncate overly long text with a summary attached, and avoid intermediate results blowing up the context.
    • Set stop conditions per step: cap the maximum number of rounds, per-task timeout, and cumulative token limit to prevent infinite loops.
    • Force human confirmation for high-risk actions: operations like deleting data or sending external messages must be validated by the business layer and cannot rely on the model’s self-restraint.
    • Use a unified access layer to lower migration costs: encapsulate a unified call interface, billing standard, and observability instrumentation, and continuously compare model capabilities on the same evaluation set and monitoring dashboard.

    6. Business re-testing: six steps to implementation

    1. Define the input profile: measure task types, document length, image count, whether video is included, and the single-turn vs. multi-turn distribution against real traffic. When sampling, let edge cases (very long documents, low-resolution scans, noisy video) take up a certain proportion.
    2. Set acceptance criteria: distinguish automatically verifiable metrics (whether JSON parses, field accuracy, tool-call success rate) from manual spot-check metrics (answer quality, factual consistency); set a “first-pass rate” threshold for each task type, such as no less than 90%.
    3. Fix variables before comparing: the same prompt, the same generation parameters such as temperature, the same tool definitions, and the same evaluation set; repeat each sample 3–5 times, and record variance and failure modes alongside the mean.
    4. Record full-pipeline metrics: beyond success rate, also record per-round input/output tokens, thinking tokens, average rounds, first-token latency, end-to-end latency, rate-limiting and timeout counts, as well as retry rate and human-fallback rate.
    5. Calculate total cost: compute by “cost per successful item = (call fees + retry fees + amortized human fallback) / successful tasks,” to avoid being misled by unit price.
    6. Establish continuous regression: model versions roll out continuously, so regression-test the fixed evaluation set monthly. Use version pinning, canary releases, and automatic timeout fallback to reduce production risk, and run content-safety review on outputs.

    7. Selection checklist

    • Which modalities does the task’s input include? Is native video support required?
    • How long does a single generation need to be? Is there enough margin in the output budget, and do reasoning and the answer share the budget?
    • What are the exact context-window value and the input limit? How is multimodal input converted to tokens?
    • What is the pricing structure: how are input/output, cache read/write, and reasoning tokens each priced?
    • What are the average rounds and per-round input length for agent tasks? Is the cumulative cost acceptable?
    • Do the first-token latency, rate-limiting policy, and service level meet business requirements?
    • Has the compatibility of tool calling and structured output been verified?
    • Do the evaluation set’s first-pass rate, total cost, and stability meet the thresholds?

    Conclusion

    LLM selection is no longer about “picking the strongest one” but about making engineering trade-offs among cost, capability, latency, and stability. The context window determines how much you can read, the output budget determines how much you can write, and the billing standard determines how much you spend—but the final result can only be answered by real tasks. Treat specs as hypotheses and re-testing as conclusions, and let every selection be backed by data, so you can keep making sound decisions amid the fast pace of model iteration.