LLM Selection and Cost Control for Long Document and Code Tasks
As the number of available Large Language Models (LLMs) increases, developers face new challenges in evaluating model capabilities and accounting for task costs. This article outlines an actionable methodology for LLM selection by breaking down tasks such as long document understanding, structured output, code generation, and web search. It covers how to accurately calculate cost per qualified result, establish robust evaluation sets, implement tiered model routing based on task difficulty, apply a three-layer quality verification process, and follow engineering best practices for implementation.
I. The Growing Number of Models
Platforms increasingly offer multiple LLMs within a single interface, expanding user options from a few to over a dozen. This increase in options introduces two new challenges: assessing capability differences and accounting for the cost of the same task. Past model selection relied on experience or impression, but teams now need to turn selection into a quantifiable and reviewable engineering decision.
These issues are not limited to specific products. Regardless of the service accessed, developers face the same set of variables: task type, model capability, billing method, quality requirements, and response latency. This article does not discuss specific products but explains how these variables combine into an actionable selection methodology.
II. Deconstruct Tasks Before Selecting Models
The prerequisite for selection is breaking down tasks. “Processing a file” can mean reading an annual report summary or generating a runnable program, which require vastly different model capabilities.
- Long Document Understanding and Information Extraction
Financial reports often exceed twenty pages, containing body text, notes, and multiple tables. The model needs to locate key paragraphs within a long context, distinguish between recurring and non-recurring items, and ensure numbers match the original text. The primary risk here is hallucinated completion, where the model fills in missing values itself when the original text lacks them.
- Structured Output
Organizing extracted results into tables or key-value structures requires complete fields, unified units, and correct year-over-year calculations. These tasks demand high instruction-following capability but generally require less reasoning depth than open-ended analysis.
- Code Generation
Generating a utility tool ready for business use requires considering input validation, boundary conditions, amount precision, exception handling, and readability. Code task failures often occur not at the syntax level but due to omitted business rules, such as duplicate submission checks, tax rate selection, or amount rounding methods.
- Web Search and Briefing Writing
These tasks require retrieving the latest information, cross-verifying sources, and organizing conclusions readable by management. They rely on tool-calling capabilities and source credibility judgment, while requiring restrained text to avoid presenting speculation as fact.
III. Formulating Cost
Many teams only look at unit prices, ignoring the actual cost of tasks. The cost of a single invocation is usually determined by input length, output length, and the number of retries. If a platform uses a quota pool and rate-based billing, the single cost can be abstracted as:
Single Cost = Base Consumption × Model Rate × Invocation Count
Here, the invocation count includes retries after failures. If a low-rate model fails its initial output and requires three corrections to meet the standard, its total cost may exceed that of a high-rate model that passes on the first try. Therefore, when evaluating costs, the denominator should be the number of results that meet acceptance criteria, calculating the cost per qualified result:
Cost Per Qualified Result = Total Consumption ÷ Accepted Tasks
This metric places quality and cost on the same scale, offering a closer reflection of reality than simply comparing unit prices.
Additionally, some platforms offer quota discounts during specific time periods or waive fees for short tasks. These rules change over time, so teams should review current rules before selection and manage them as configurable parameters rather than hardcoding them.
IV. Establishing Evaluation Sets to Replace Subjective Judgment
Selection conclusions need evidence. It is recommended to prepare 10 to 20 representative samples for each task type, covering both common and edge cases. Taking annual report summaries as an example, samples can include:
- Questions where the original text explicitly provides values
- Questions where the text is undisclosed, and the model should admit “undetermined”
- Questions where the same metric has inconsistent criteria across different sections
- Questions requiring cross-page aggregation to answer
Each sample is paired with a set of checkpoints, such as whether the numbers match the original text, whether page numbers are correct, whether the word count exceeds limits, and whether unverified conclusions exist. The evaluation is divided into two layers: automated checks and manual review. Numeric comparisons, word counts, and format validations are suitable for automation; the reasonableness of conclusions requires spot-checks by personnel with financial knowledge.
V. Tiered Routing: Assigning Models by Difficulty
A mature approach is to invoke models by task difficulty tier rather than sending all tasks to the same model. A viable architecture consists of three layers:
- Rule Layer: Deterministic tasks like format conversion, field replacement, and simple calculations are handled by scripts without invoking models.
- Lightweight Model Layer: Medium-difficulty tasks like draft summarization, classification tagging, and field extraction.
- High-Capability Model Layer: Complex reasoning, cross-section analysis, and verification of key conclusions.
The routing logic can be written as the following pseudocode:
function route(task) {if (task.is_deterministic) {return run_rule_engine(task);}if (task.estimated_tokens > LONG_CONTEXT_THRESHOLD) {model = pick("long_context_tier");} else if (task.type in ["extraction", "formatting"]) {model = pick("light_tier");} else {model = pick("strong_tier");}result = call(model, task.prompt, task.input);if (!validate(result, task.checks)) {model = escalate(model);result = call(model, task.prompt, task.input);}return result;}
The escalation mechanism is key here. Automatically switching to a strong model upon lightweight model failure controls average costs while ensuring a quality floor for critical tasks.
VI. Three Checkpoints for Quality Verification
Regardless of the model used, outputs require verification. These three checkpoints treat model outputs as drafts to be verified.
First: Structural Verification. Check whether table fields are complete, units are unified, and word counts are within limits.
Second: Numeric Verification. For each financial metric, the system should locate the page number in the original text and compare the values. Year-over-year changes can be recalculated from two periods’ values; if they do not match the model’s results, they should be flagged directly.
Third: Factual Verification. For subjective content like “future events” or “risk warnings,” the output should be required to include supporting evidence from the original text. Statements without evidence should be rewritten as “not disclosed in the report” or deleted.
VII. Engineering Implementation Essentials
- Usage Monitoring: Record the model, input/output length, duration, and result status for each call. Aggregate daily into a logging service and set monitoring alerts for abnormal consumption.
- Document Preprocessing: Segment long documents by chapter and build page number indexes, sending only relevant fragments to the model to reduce overhead and interference from irrelevant context.
- Result Caching: Results for the same document and question can be cached to avoid duplicate billing. Store original documents and intermediate artifacts in object storage with configured lifecycle policies.
- Externalized Configuration: Place model lists, rates, time-based discounts, and thresholds in a configuration center so rules can be quickly adjusted without code changes.
- Least Privilege: Inject calling credentials through a key management service; do not write them into code or logs.
