Scenario-Based LLM Selection and Engineering Implementation: A Practical Guide

    This article explains how to move from one-off LLM selection to routing and orchestration of replaceable model backends. It profiles four common workloads—code generation and refactoring, general dialogue and content processing, real-time information lookup, and deep research and reporting—and presents a six-dimension evaluation framework, a unified gateway architecture with policy routing and fallback, implementation guidance for each workload, and practices for cost, capacity, observability, and continuous evaluation. It also lists common anti-patterns and concludes with the engineering foundations needed to make model selection sustainable.

    1. Reframing the Problem: From Choosing a Model to Orchestrating a Set of Capabilities

    In engineering practice, teams often make the mistake of treating LLM selection as a one-time decision: choose one vendor and one version, then push every business use case onto it. In reality, different workloads have needs that are orthogonal or even conflicting. Code generation emphasizes structural consistency over long contexts and stable tool-call behavior. General question answering emphasizes response latency and natural tone. For real-time information tasks, the crux is not the model itself, but the freshness and traceability of the retrieval pipeline. Deep research tasks are long-cycle, multi-step, batch-like workloads that can tolerate high latency.

    A more reasonable abstraction is to treat models as replaceable backend capabilities and turn model selection into a routing and orchestration problem. The intuition that different tasks call for different tools is correct, but it must be codified through engineering. Otherwise, it degrades into individual habits and cannot be reused across teams and production systems.

    2. Capability Profiles for Four Typical Workloads

    Workload Type Key Metrics Failure Modes Design Priorities
    Code generation and refactoring Structural consistency, tool-call correctness, long-context retention Hallucinated APIs, cross-file inconsistency Repository-level retrieval augmentation, compile/unit-test loop validation
    General dialogue and content processing Time to first token, instruction following, controllable tone Verbosity, off-topic answers Small-model first, templated prompts, streaming output
    Real-time information lookup Result freshness, verifiable sources Stale information, no citations Retrieval first; the model only summarizes and cites
    Deep research and reporting Coverage, complete logic chain, reproducibility Step drift, unsupported conclusions Task decomposition, multi-round iteration, human checkpoints

    It is important to note that real-time performance and depth cannot be achieved at the same time. Putting research-grade tasks on a low-latency path only produces conclusions that “look fast but do not hold up.” Conversely, routing simple question answering to a heavy reasoning path is a pure waste of cost.

    3. Six-Dimension Evaluation Framework

    Do not rely on a single leaderboard score. Build an internal evaluation set with 100–300 real business samples per workload type, score candidates across the following dimensions, and apply weights:

    1. Task success rate: For code tasks, focus on compile pass rate and unit-test pass rate. For question answering, focus on factual correctness verified manually or by rules.
    2. Latency distribution: Look at P50/P95 rather than the mean. For streaming scenarios, also measure time to first token.
    3. Context and throughput: Truncation strategy and effective utilization in long-document and multi-file scenarios.
    4. Unit cost: Calculate cost per thousand successful tasks rather than token unit price, so that retries and rework do not hide the real cost.
    5. Compliance and data boundaries: Whether data leaves the environment, log retention policies, and content safety filtering capabilities.
    6. Operability: Version change notifications, canary release capability, quota and rate-limiting policies, and failure fallback paths.

    4. Reference Architecture: Unified Gateway + Policy Routing + Fallback

    1. Business application
    2. │
    3. ▼
    4. Unified model gateway (auth / quotas / audit)
    5. ├── Routing policy: workload type + complexity + latency budget + cost budget
    6. ├── Semantic cache (object storage + vector index)
    7. ├── Retrieval augmentation (document parsing → chunking → indexing → reranking)
    8. ├── Primary/backup and fallback chain (primary model → backup model → rule/template fallback)
    9. └── Observability (log service + monitoring and alerting + sampled evaluation)

    Illustrative routing code (pseudocode; interface names are custom abstractions):

    1. def route(task):
    2. if task.kind == "code":
    3. return Plan(model="reasoning_tier", ctx="repo",
    4. timeout_ms=8000, fallback="mid_tier")
    5. if task.kind == "chat":
    6. return Plan(model="fast_tier", stream=True,
    7. timeout_ms=1500, fallback="mid_tier")
    8. if task.kind == "fresh_lookup":
    9. return Plan(model="mid_tier", retriever="live_search",
    10. require_citation=True, timeout_ms=5000)
    11. if task.kind == "deep_research":
    12. return Plan(model="reasoning_tier", steps="decompose",
    13. async_queue=True, human_review=True)
    14. return Plan(model="mid_tier")
    15. async def run(task):
    16. plan = route(task)
    17. for candidate in [plan.model, plan.fallback, "template"]:
    18. try:
    19. return await invoke(candidate, task, plan)
    20. except (TimeoutError, RateLimited):
    21. metrics.incr("route_fallback", tags=[candidate])
    22. return template_answer(task)

    The key point is that the fallback path must be part of product behavior, not an exception branch. A user-perceivable “slower but with an answer” experience is always better than a blank screen or a timeout.

    5. Implementation Guidance for the Four Workload Types

    Code tasks: Do not simply throw prompts at the model. Build repository-level retrieval with a symbol index and dependency graph, and use relevant files as context. After generation, force a loop of “compile → unit test → static check.” If it fails, retry with the error information, up to N times. For tool-call scenarios, use strict schema validation and reject free-text arguments.

    General dialogue tasks: Prioritize a small, fast model with a high-quality system prompt. Use semantic caching to intercept high-frequency repeated questions. Return output in streaming mode to improve perceived latency. Apply pre-content safety filtering for sensitive and high-risk intents.

    Real-time lookup tasks: Decouple retrieval from generation. The retrieval layer is responsible for freshness and sources. The generation layer may answer only based on the provided snippets and must cite sources sentence by sentence. When no reliable snippets are available, explicitly answer “no supporting evidence found.” This is more valuable than fabrication.

    Deep research tasks: Use a multi-stage process of “decomposition—parallel evidence gathering—cross-validation—summarization.” Use a message queue for asynchronous tasks and peak shaving, and store intermediate artifacts in object storage for reproducibility. Insert human confirmation at key checkpoints, and attach a complete citation chain and confidence labels to the output.

    6. Cost, Capacity, and Continuous Evaluation

    • Tiering and caching: Route high-frequency simple requests to cache and small models, and route long-tail complex requests to heavier paths. Cache keys must include the prompt version to avoid stale hits after version upgrades.
    • Batch processing and off-peak scheduling: Make research and offline summarization tasks asynchronous through a message queue, and use a container platform for elastic scaling to avoid quota contention during peak hours.
    • Observability closed loop: Record routing decisions, token consumption, latency, and failure reasons across the full chain. Set monitoring alerts for P95 latency, fallback rate, and unit success cost. Run regressions on a fixed evaluation set every week to prevent hidden quality degradation caused by model or prompt changes.
    • Canary release and rollback: Any change to model versions, prompt templates, or routing weights should go through canary release, with a one-click rollback switch.

    7. Common Anti-Patterns

    1. Using a single model across the entire site, leading to both cost and experience losses.
    2. Selecting models by token unit price while ignoring the hidden costs of rework and retries.
    3. Relying on parametric model memory in real-time scenarios without retrieval.
    4. Running research tasks without human checkpoints, allowing errors to be amplified across long chains.
    5. Having no evaluation set, so quality changes after model upgrades go unnoticed.
    6. Having no fallback path, binding availability entirely to a single backend.

    8. Conclusion

    The experience of “what task uses what” is essentially a simple match between workload characteristics and capability boundaries. To engineer it, three things are needed: a unified model gateway that abstracts backend differences, explicit policy routing that carries selection decisions, and a complete evaluation and observability system that ensures decisions can be continuously corrected. With these three in place, the model is no longer a “selection dilemma” that must be discussed repeatedly, but a replaceable, measurable, and optimizable infrastructure component.