LLM API Selection: An Engineering Framework Across Six Dimensions

    Evaluate LLM APIs using six engineering criteria: pricing, context window, reasoning, coding and agent capabilities, Chinese-language quality, and performance. This guide explains how to estimate real costs, manage agent token consumption, route tasks across model tiers, and build a business-specific evaluation dataset.

    1. Why LLM API Selection Has Become More Complex

    Once systems such as customer support assistants, document analysis tools, retrieval-augmented question answering, and coding assistants enter production, teams often integrate multiple model services. Providers differ in pricing, context limits, API design, and capability priorities.

    Choosing the “strongest” model based on reputation alone commonly leads to two problems: monthly bills that exceed expectations and inconsistent output quality for particular subtasks.

    Instead, treat model services as measurable infrastructure. Before evaluating candidates, define your business objectives, daily request volume, average input and output lengths, and latency and accuracy requirements. These numbers determine which evaluation dimensions matter most and how much weight each should carry.

    2. Six Evaluation Dimensions

    2.1 Unit Pricing and Billing Structure

    Most services charge separately for input and output tokens, typically per million tokens. Output tokens usually cost more because generation requires sequential token computation.

    Comparing headline prices is not enough. Review these billing details as well:

    • Input caching: When a request prefix matches previously cached content, the cached portion may be billed at a lower rate. Workloads with fixed system prompts or repeatedly queried documents benefit most.
    • Batch processing: Offline tasks, such as overnight labeling or summarizing historical records, can often use batch APIs to exchange more relaxed latency requirements for lower prices.
    • Internal reasoning tokens: Some reasoning models generate intermediate reasoning before producing an answer. These tokens may also be billable and can substantially outnumber the tokens in the final response.

    2.2 Context Window

    The context window determines how much information a single request can contain. Larger windows are useful for repository-wide code reviews, comparisons of long contracts, and extended conversation histories.

    However, a large window does not mean every request should fill it. Longer inputs increase both time to first token and cost. Models may also use information unevenly across a long input: relevant details placed near the beginning or end are often retrieved more reliably than details buried in the middle.

    In practice, use retrieval, summarization, and segmentation to keep context to the minimum needed to complete the task.

    2.3 Reasoning Ability

    Reasoning ability matters for multistep logic, mathematical calculations, conditional decisions, and task planning.

    Public benchmark scores can help with initial screening, but business tasks often involve domain-specific rules. Extract test cases from real workloads and check whether each model reaches the correct conclusion under those constraints.

    Record error types as well as overall correctness. For example, did the model overlook a condition, or did it apply the condition incorrectly?

    2.4 Coding and Agent Capabilities

    Agent applications depend on three capabilities:

    • Following the required format for tool-call arguments.
    • Correctly interpreting tool results.
    • Adjusting their strategy after an error.

    Coding assistants must also understand project context and produce code that compiles and passes tests.

    Useful quantitative metrics include:

    • Tool-call success rate: Whether argument types and required fields are valid.
    • Multistep task completion rate: Whether the entire workflow, from request to result, succeeds.
    • Repair iterations: The average number of revisions needed for incorrect code or configuration to pass validation.

    2.5 Chinese-Language Quality

    For applications that handle Chinese, evaluate terminology accuracy, register, coherence across long texts, and understanding of conversational language.

    Customer support requires appropriate tone and complete information. Document workflows place greater emphasis on professional terminology and formatting conventions. Mixed simplified and traditional Chinese, abbreviations, industry jargon, and dialect expressions can reveal weaknesses.

    A practical evaluation method combines manual sampling with rule-based checks. Human reviewers assess meaning and tone, while automated rules check restricted terms, required fields, and formatting requirements.

    2.6 Response Speed and Reliability

    Response speed has two distinct measures:

    • Time to first token (TTFT): Determines how long users wait before a response begins.
    • Generation speed: Measured in output tokens per second, it determines how quickly a long answer finishes.

    Interactive applications are more sensitive to TTFT, while batch workloads place greater emphasis on throughput.

    Reliability is equally important. Track timeout rates, rate-limiting policies, error-code distributions, and the provider’s published availability commitments. Network paths also affect latency, so test performance directly when deploying across regions.

    3. Estimate Real Spending with a Cost Model

    The cost of a single call is:

    1. Call cost =
    2. input tokens × input price / 1,000,000
    3. + output tokens × output price / 1,000,000

    Agent task costs must be summed across steps. Each step typically resends message history, tool results, and the system prompt, so input token usage grows as the workflow progresses.

    Consider the following hypothetical example. These prices are illustrative, not actual quotes from any provider.

    Assume a lightweight model costs CNY 1 per million input tokens and CNY 4 per million output tokens. An agent task runs for an average of eight steps, with an average of 12,000 input tokens and 800 output tokens per step.

    • Total input: 8 × 12,000 = 96,000 tokens, costing CNY 0.096.
    • Total output: 8 × 800 = 6,400 tokens, costing CNY 0.0256.
    • Total per task: Approximately CNY 0.12.

    At 5,000 tasks per day, the daily cost is roughly CNY 600. This illustrates why multiplying a single-call price by the number of user requests often underestimates agent spending.

    Expressing the calculation as a function makes it easier to test different assumptions:

    1. def estimate_call_cost(input_tokens, output_tokens, in_price, out_price):
    2. # in_price and out_price are in CNY per million tokens.
    3. return (input_tokens * in_price + output_tokens * out_price) / 1_000_000
    4. def estimate_agent_task_cost(steps, base_input, avg_output, in_price, out_price):
    5. total = 0.0
    6. context = base_input
    7. for _ in range(steps):
    8. total += estimate_call_cost(context, avg_output, in_price, out_price)
    9. # Append each step's output to the context, increasing the next input.
    10. context += avg_output
    11. return total

    This simplified model uses a fixed output-length increment to represent context growth rather than separately accounting for tool-result lengths. For real estimates, replace these assumptions with measurements from production logs.

    4. Why Agents and Coding Workloads Consume More Tokens

    Compared with ordinary question answering, coding and agent workflows have several factors that amplify token consumption:

    1. Reading code and logs: A troubleshooting request may include large amounts of source code, stack traces, and configuration files.
    2. Analyzing diffs: More changed files mean longer context.
    3. Tool results: If tools return complete JSON payloads or raw web pages, redundant fields may be billed repeatedly.
    4. Multiple reasoning rounds and retries: Models may explore several approaches and make additional calls after failures.

    To control consumption:

    • Send only file excerpts relevant to the problem.
    • Trim logs at the tool layer, retaining error lines and surrounding context.
    • Convert tool results into compact, structured fields.
    • Periodically compress conversation history.
    • Set maximum step counts and budget limits for each task. When a task exceeds those limits, stop execution and hand it off to a human.

    5. A Tiered Model-Routing Architecture

    Mature systems often use more than one model. A common approach divides tasks into three tiers:

    • Lightweight: High-volume, low-complexity tasks such as classification, information extraction, rewriting, and keyword extraction.
    • Balanced: Core workloads such as routine question answering, business-logic generation, and ordinary code changes.
    • Premium: A small subset of requests involving complex planning, difficult troubleshooting, or critical decisions.

    This architecture requires a unified integration layer. Business code depends only on an internal interface, while model names, endpoints, and credentials remain in configuration. With that abstraction in place, model changes can be confined to configuration rather than application code.

    The following simplified routing example uses placeholder model identifiers:

    1. TIERS = {
    2. "light": "model-light",
    3. "balanced": "model-balanced",
    4. "premium": "model-premium",
    5. }
    6. def choose_tier(task):
    7. if task["kind"] in ("classify", "extract", "rewrite"):
    8. return "light"
    9. if task.get("complexity", 0) >= 0.7 or task.get("needs_planning"):
    10. return "premium"
    11. return "balanced"
    12. def call_with_fallback(task, clients):
    13. primary = choose_tier(task)
    14. order = [primary] + [t for t in ("balanced", "premium") if t != primary]
    15. last_error = None
    16. for tier in order:
    17. try:
    18. return clients[tier].complete(task["prompt"], timeout=task.get("timeout", 30))
    19. except (TimeoutError, ConnectionError) as err:
    20. # Switch tiers only for transient errors such as timeouts
    21. # or connection failures; let invalid-argument errors propagate.
    22. last_error = err
    23. raise last_error

    Two points matter here.

    First, escalation and downgrade rules should reflect business quality requirements. For example, if a lightweight model’s output fails format validation, retry with the balanced tier.

    Second, switching models after a failure can change the output style. Add downstream format validation to keep results consistent with application requirements.

    6. Build Your Own Evaluation Dataset

    Public leaderboards cannot replace business-specific evaluation. Build an internal evaluation dataset using the following process:

    1. Sample real logs. Include common requests, edge cases, and historical failures. A few hundred examples can be a reasonable starting point.
    2. Define acceptance criteria for each example. Use reference answers, scoring rules, or validation conditions for structured fields.
    3. Run candidate models with fixed prompts and parameters. Record outputs, execution times, and token usage.
    4. Aggregate the metrics. Track accuracy, format compliance, tool-call success rate, average cost per task, and P95 latency.
    5. Rerun the full dataset after changes. Repeat the evaluation whenever you switch models or upgrade a model version.