LLM Selection: Methods and Acceptance for Long-Running Background Tasks
This article explores the criteria and practices for selecting Large Language Models (LLMs) for long-running background tasks. It emphasizes that the ability to deliver results is more critical than simply answering questions correctly. The guide covers scenario division (interactive vs. background), task decomposition principles, building reliable API integration layers, failure handling strategies, rigorous acceptance testing, and cost and scheduling considerations.
1. Answering Questions Does Not Equal Delivering Results
While Large Language Models (LLMs) are quite mature in Q&A and text generation, the truly time-consuming parts of a project often lie not in whether the model answers correctly, but in how to integrate the model into workflows, break down large tasks into executable sub-steps, recover from failures, and ultimately verify that the results meet requirements.
A conversational test can be completed in a few minutes. However, a task that needs to run continuously for hours and process dozens of files exposes a different set of problems: request timeouts, truncated outputs, gradual format deviations, and partial completions mistakenly recognized as full completions.
Therefore, model selection should be based on whether it can deliver results, rather than just looking at the quality of a single response or leaderboard scores.
2. Scenario Division First: Interactive vs. Background
The requirements for models vary greatly across different tasks and can be evaluated along two dimensions:
- Response latency: Is the user waiting for the result, and do they need to modify the conversation on the fly?
- Task duration and scale: Does a single task require several minutes or more, and does it involve a large number of repetitive calls?
Interactive scenarios, such as instant Q&A, code completion suggestions, and copywriting polishing, prioritize first-token response speed and multi-turn dialogue stability. Background scenarios, such as batch translation, batch test data generation, and long document organization, focus more on throughput, unit cost, recoverability, and result integrity.
A common practice is to assign the model with fast response and good interactive experience to handle primary conversations and judgments, while assigning the model with controllable costs and suitability for long-running operations to handle batch processing. The two types of models do not replace each other; rather, they are allocated based on task characteristics.
3. Three Principles of Task Decomposition
- Controllable granularity. The input scale of each sub-task should be small enough to be completed stably in a single API call. Translating an entire book can be chunked by chapter or fixed word count, with each chunk called independently.
- Defined input and output. Specify the input format and output structure for each step, such as fixed JSON fields or delimiters, to facilitate automated program validation.
- Verifiable results. Each sub-task needs judgment criteria. For translation tasks, check if source paragraphs correspond one-to-one with translated paragraphs; for code generation, run tests; for data organization, verify that the number of records is conserved.
Improper decomposition leads to two typical problems. If chunks are too large, the model may lose context midway or simply refuse to execute. If chunks are too fragmented, context is severed, and terminology can easily become inconsistent.
4. Integration Layer: Encapsulating Calls into Reliable Components
Background tasks should invoke models through a unified encapsulation layer rather than scattering request logic within business code. The encapsulation layer is typically responsible for reading authentication information, setting timeouts, executing retries with backoff, validating responses, and logging.
Below is a sample code snippet. The call function here is a placeholder implementation and should be replaced with the SDK or HTTP interface provided by your chosen service in actual use.
import osimport timeMAX_RETRY = 3def call_model(prompt: str, api_key: str) -> str:"""Placeholder function: Actual implementation depends on the SDK or HTTP interface of the chosen service."""raise NotImplementedErrordef run_with_retry(prompt: str, validate) -> str:api_key = os.environ["MODEL_API_KEY"] # Keys are read from environment variables, not hardcodedlast_error = Nonefor attempt in range(1, MAX_RETRY + 1):try:result = call_model(prompt, api_key)if validate(result):return resultlast_error = ValueError("Output did not pass format or content validation")except TimeoutError as e:last_error = etime.sleep(2 ** attempt) # Exponential backoffraise RuntimeError(f"Failed after multiple attempts: {last_error}")
This code embodies three key points: keys are injected via environment variables, validation logic is passed in by the caller, and there is an upper limit on retry attempts.
5. Failure Handling: Categorize First, Then Decide Strategy
Background tasks experience various forms of failure and should be handled distinctly:
- Timeouts or network errors: These can be retried directly, paired with backoff waiting.
- Server-side rate limiting or peak-hour queuing: Reduce concurrency, lengthen request intervals, and if necessary, postpone non-urgent tasks to off-peak hours.
- Model refusal to execute: Usually related to the task description or current execution environment. Check if the task exceeds the model’s available tools or conditions, modify the prompt, and then execute again, rather than mechanically retrying.
- Partial completion: Insufficient output length, mid-way truncation, or only the first few sections completed. Record the completed fragments and resume from the breakpoint.
- Format deviation: When structured output is missing fields, append the validation error to the prompt and make a new request, while limiting the number of retries.
The key is saving intermediate states. The input, output, status, and time consumed for each fragment should be persisted to disk. If a task is interrupted, the system can continue from the most recent successful position without having to rerun the entire task.
6. Acceptance: Do Not Just Check If the Output Exists
During the acceptance phase, it is easy to encounter situations that appear completed. Take long document translation as an example: the output file may have been generated, and the cover and table of contents converted to the target language, but the body text remains in the source language. If you only spot-check the first few pages, such issues are hard to detect.
Acceptance methods that can be adopted include:
- Coverage check. Count the number of paragraphs in the source text that need processing and compare them with the output paragraphs to find missing or omitted parts.
- Sampling check. Randomly select middle and ending chapters for manual verification to avoid only looking at the beginning.
- Language check. Use simple rules to calculate the proportion of target language characters in the output to locate unprocessed paragraphs.
- Automated testing. Run unit tests or build commands for code-based tasks; verify row counts, field types, and total volume conservation for data-based tasks.
- Traceability and reproducibility. Retain the parameters, prompt versions, and output files for each run to facilitate comparison and issue reproduction.
Acceptance criteria should be clearly written out before the task begins, not decided upon after completion.
7. Cost and Scheduling
The cost of background tasks is primarily determined by the number of calls, input/output length, and retry count. When estimating, first run the process with a small sample segment, record the consumption of a single fragment, and then extrapolate the overall cost based on the total volume. This yields an estimate based on empirical testing rather than a guess.
In terms of scheduling, peak and off-peak tasks can be scheduled separately, with non-urgent tasks prioritized for off-peak execution. For parallelizable fragments, concurrency must be controlled. Excessive concurrency easily triggers rate limiting, and massive retries can actually prolong the total duration.
8. Implementation Checklist
- Define the scenario: Determine whether it is interactive or background, and establish latency and duration goals.
- Define deliverables and acceptance criteria, writing them into the task description.
- Decompose tasks by chapter, module, or record count to ensure each fragment can be independently verified.
- Unify the encapsulation of the call layer; manage keys via environment variables.
- Categorize and handle failures, save intermediate states, and support breakpoint resumes.
- Combine sampling and automated testing for acceptance, focusing on coverage checks.
- Record costs and time consumed, and adjust division of labor and scheduling accordingly.
The value of a model is ultimately reflected in the deliverable results. Stabilize the workflow first, and then discuss the pros and cons between different models—only then will your judgment be well-founded.
