On-Demand Model Routing: Combining Web Search and Private Knowledge Bases in Practice

    This article explains how to build a practical system that routes user queries to the appropriate model and retrieval channel—web search, private knowledge base, or direct generation—based on query freshness, complexity, and domain specificity. It covers architecture design, routing logic with a Python example, key steps for private knowledge base Q&A, web search risks, model cost control, evaluation metrics, and common implementation pitfalls.

    Why On-Demand Model Matching Matters

    In enterprise Q&A, R&D assistance, and office assistant scenarios, user questions vary significantly in nature. Some ask about the latest developments—whether a policy has changed, or whether a new version has been released. Others require deep domain expertise, such as explaining the derivation of an algorithm or reviewing contract clauses. Still others involve casual conversation or simple text rewriting. If every request is handled by the same model with the same retrieval method, you end up with stale information, unsupported professional answers, or unnecessarily high costs for simple queries.

    Single models also have inherent capability boundaries. Different models differ in knowledge cutoff dates, reasoning ability, context length, response speed, and invocation cost. A pragmatic approach is to build an on-demand routing mechanism: first classify the question, then decide which retrieval channel to use, and finally select an appropriate model to generate the answer.

    1. Problem Decomposition: Identify Needs First, Then Choose the Path

    The prerequisite for on-demand routing is accurately identifying question characteristics. Several dimensions help with this.

    1. Freshness: Does the information in the question change over time—for example, market prices, news, version numbers, or personnel schedules? Such questions require web search or real-time data sources.
    2. Domain specificity: Does the question depend on specialized knowledge or internal corporate materials—internal policies, product manuals, historical tickets, or technical specifications? These should primarily use a private knowledge base.
    3. Complexity: Does the question require multi-step reasoning, long-document comprehension, or a rigorous logical chain? Complex questions are better suited for models with stronger reasoning, while simple ones can use lightweight models.

    These dimensions are not mutually exclusive. A question may need both real-time data and internal standards, in which case a merge strategy is required rather than a simple either/or selection.

    2. Overall Architecture

    A production-ready on-demand routing system typically consists of several layers:

    • Request understanding layer: intent recognition, keyword extraction, and sensitive information checks on user input.
    • Routing decision layer: based on the understanding results, decide whether the request goes to web search, a private knowledge base, or direct generation, and select the model.
    • Execution layer: performs web retrieval, vector search, or direct model invocation.
    • Result fusion layer: compiles evidence sources, generates a response with citations, and logs the process for later evaluation.

    The layered design keeps responsibilities clear. Routing strategies can be adjusted independently without modifying retrieval or generation code. Adding a new knowledge source only requires adding an adapter in the execution layer.

    3. Implementing the Routing Strategy

    Routing decisions can be implemented initially with rules. Rules are stable, interpretable, and low-cost. When rules prove insufficient, you can introduce a small classification model or have the model output structured labels. Below is a simplified example illustrating the decision logic:

    1. from dataclasses import dataclass
    2. # Model names are placeholders; replace with actual service identifiers in deployment
    3. MODEL_REASONING = "reasoning-model"
    4. MODEL_LIGHT = "light-model"
    5. FRESHNESS_KEYWORDS = ("latest", "today", "recent", "current version", "recently released")
    6. @dataclass
    7. class RouteDecision:
    8. channel: str # "web" | "kb" | "direct"
    9. model: str
    10. reason: str
    11. def classify_freshness(query: str) -> bool:
    12. return any(k in query for k in FRESHNESS_KEYWORDS)
    13. def route(query: str, kb_top_score: float, is_complex: bool) -> RouteDecision:
    14. if classify_freshness(query):
    15. return RouteDecision("web", MODEL_REASONING, "Query involves time-sensitive information")
    16. if kb_top_score >= 0.75:
    17. model = MODEL_REASONING if is_complex else MODEL_LIGHT
    18. return RouteDecision("kb", model, "Private knowledge base hit score is high")
    19. return RouteDecision("direct", MODEL_LIGHT, "General question without external evidence")

    There are several points to note about this code. First, keyword rules are only an entry point and can easily produce false positives; test against real question samples before deployment. Second, the knowledge base score threshold must be calibrated based on your specific retriever—do not just copy a fixed value. Third, route decisions should be logged for post-hoc analysis of misclassification.

    4. Key Steps for Private Knowledge Base Q&A

    The effectiveness of private knowledge base Q&A largely depends on upstream data processing. Typical steps include:

    1. Document parsing: handle different file formats uniformly, preserving heading levels and table structures.
    2. Text chunking: split text by semantic paragraphs or headings, and control chunk length to avoid mixing multiple topics in one segment.
    3. Vectorization and indexing: use vector retrieval, but also maintain a keyword index. Combining the two catches both semantic similarity and exact matching.
    4. Retrieval and reranking: first recall a larger set of candidate chunks, then use a reranker model or rule-based filtering to select the most relevant pieces.
    5. Generation constraints: require the model to answer solely based on the provided chunks, and explicitly state when an answer cannot be derived from the material.

    The generation constraint is the most easily overlooked. If the prompt does not restrict the answer source, the model may mix general knowledge with internal documents, making it impossible for the user to tell which parts come from corporate materials. It is recommended to append the cited document name and paragraph location in the output so readers can verify.

    5. Considerations for the Web Search Channel

    Web search solves freshness problems but introduces new risks:

    • Source credibility varies widely: apply basic filtering on domain names, publishing organizations, and publication dates.
    • Conflicting reports: multiple versions of the same event may appear; deduplicate and compare timelines.
    • Content cleaning: remove ads, navigation text, and irrelevant code before feeding search results to the model.
    • Prompt injection: web pages may contain misleading instructions; treat the content as data to process, not as commands to execute.
    • Timeouts and retry limits: set reasonable constraints to prevent a single search from slowing down the entire response.

    Additionally, answers based on web search should indicate when the information was retrieved. “Latest” is relative; users need to know the time point the answer corresponds to.

    6. Model Division and Cost Control

    The benefits of on-demand model selection appear not only in answer quality but also in cost control. Simple questions handled by lightweight models reduce both latency and invocation costs, while complex reasoning questions go to more capable models. A practical division can follow these principles:

    • Small talk, format conversion, simple rewriting: use a lightweight model, prioritizing speed.
    • Knowledge Q&A with clear evidence: use a mid-tier model, emphasizing citation accuracy.
    • Multi-step reasoning, code review, proposal evaluation: use a high-capability model, accepting higher latency.

    Model selection should be based on actual measured performance, not just parameter count or marketing claims. The same model may perform very differently across tasks; validate with your own evaluation set task by task.

    7. Evaluation and Monitoring

    A system without evaluation cannot be improved sustainably. Establish the following metrics:

    • Routing accuracy: sample routing results and compare against human judgment.
    • Retrieval hit rate: whether the evidence needed for the answer appears in the retrieved results.
    • Citation accuracy: whether the cited sources actually support the corresponding conclusions.
    • End-to-end latency and per-invocation cost: track separately by channel to identify bottlenecks.
    • User feedback: downvotes, corrections, and follow-up counts reflect real-world usefulness.

    The evaluation set should include three types of samples: time-sensitive questions, questions answerable from the knowledge base, and questions not answerable from the knowledge base. The third type is especially important—it tests whether the system honestly states that it does not know rather than fabricating an answer.

    8. Common Pitfalls in Implementation

    1. The more complex the routing, the better. Both rules and models can make mistakes. Starting with simple rules plus logging is more reliable than designing a complex classifier at the beginning.
    2. Chasing the largest model. Large models are expensive and slow; many questions can be handled by smaller models.
    3. Ignoring the need for a “no evidence” response. The system should be trained to say “I don’t know” when no supporting evidence is available.
    4. Forgetting to monitor cost and latency. They are as important as answer quality in production.