LLM Selection for Science and Engineering Workloads: Evaluation, Routing, and Hallucination Control

    This article outlines a practical framework for selecting large language models for science and engineering tasks, where the goal is stable, reproducible performance on local workloads rather than public leaderboard rankings. It covers acceptance checklists, evaluation dimensions and thresholds, private test sets, long-context testing, version stability and release strategy, a multi-model routing gateway with sample Python code, cloud platform selection criteria, and retrieval-augmented generation for reducing hallucination. The emphasis is on measurable validation, controlled rollout, task-based routing, cost tracking, and human review as a final safeguard.

    In science and engineering scenarios, the goal of model selection is to find a solution that can reliably reproduce results on your organization’s tasks, not to rank highly on public benchmarks. Leaderboard scores come from public question sets and may have little to do with your papers, codebases, and formula systems. The following sections describe practical approaches across three areas: evaluation, routing, and hallucination control.

    1. Start by breaking tasks into an acceptance checklist

    Errors in science and engineering tasks are often subtle. A single incorrect symbol can invalidate the entire result. Before selecting a model, write acceptance criteria for each task type.

    1. Formula derivation: Check whether each equation step holds, and whether symbols, subscripts, and dimensions are consistent. Use symbolic computation tools, or substitute numerical values into the conclusion for spot checks.
    2. Code writing and refactoring: Check whether the code passes compiler or interpreter checks, whether unit tests pass, whether undeclared dependencies are introduced, and whether interfaces remain compatible with existing callers.
    3. Literature analysis: Check whether summaries, methods, and conclusions are consistent with the original text, and whether cited page numbers, figure and table numbers, and values can be found in the source.
    4. Interface and API references: Check whether function names, parameter names, and return values exist in the official documentation or source code.

    Once the acceptance checklist is clear, score every candidate model against the same checklist. Only then are comparisons meaningful.

    2. Evaluation dimensions and scorecard

    When evaluating models, cover the following dimensions and set thresholds and sample sizes for each.

    Task Test set Metric Suggested threshold Suggested sample size
    Formula derivation 50–200 self-built problems with reference answers Final answer accuracy Consider replacement only if more than 5 percentage points above the current baseline Run each problem at least 3 times and take the majority result
    Code generation Private task set with unit tests Test pass rate Above baseline with no new failing cases At least 100 tasks
    Literature question answering Question-answer pairs extracted from domain papers Answer consistency with source and citation accuracy Citation accuracy no lower than 95% At least 200 questions
    Refusal ability Questions with intentionally missing information Correct refusal rate No lower than 90% At least 100 questions

    Thresholds are only a starting point and should be adjusted according to your organization’s risk tolerance. When sample sizes are too small, differences between two models may be random fluctuation. When comparing accuracy rates, use binomial confidence intervals to judge whether a gap is reliable.

    3. Parameter scale and context window

    Parameter scale is usually related to model capacity, but it is only a reference metric. What matters more is whether the model can accurately find and use key information under your real input lengths.

    Run a “needle in a haystack” test. Place a key fact at different positions in a long text, set text lengths to 4K, 16K, and 64K characters, and record whether the model answers correctly. Plot accuracy against length and position to see where the model starts to fail.

    Vendors usually document details of positional encoding and attention implementation, but documentation cannot replace actual testing. The same model may also perform differently on long text under different versions or inference parameters.

    4. Training data and private test sets

    Public benchmarks are susceptible to training data contamination. A model may have seen the same questions during training, which can inflate its scores. To reduce this risk, build private test sets as follows:

    1. Have researchers or engineers in your organization write the questions based on real, unpublished tasks or rewritten versions of old tasks.
    2. Before submitting questions to a model, use string matching or n-gram checks to measure overlap with public corpora. Questions with excessive overlap should be rewritten.
    3. Use the test set only for evaluation. Do not place it in prompt examples or any fine-tuning data.
    4. Before changing model versions, confirm that the test set has not been accidentally added to training data or examples.

    5. Version stability and release strategy

    After a vendor updates a model version, capabilities may improve, but they may also degrade on some tasks. Before upgrading, use the following process:

    1. Pin the version currently in use. Do not use aliases such as “latest” in business code.
    2. Run the new version completely against the regression test set, covering all task types listed in Section 2.
    3. Canary release: route 5% of non-critical traffic to the new version first, and observe for one to two weeks.
    4. Define rollback conditions in advance. For example, if the test pass rate for critical tasks drops beyond a threshold, or online citation errors increase noticeably, switch back to the old version immediately. The team should set thresholds according to the business.

    If the old version meets requirements and the service is stable, do not migrate merely because a version number has changed. Migration decisions should be based on test data.

    6. Multi-model routing gateway

    A single model can hardly balance cost and quality across all tasks at the same time. A common approach is to deploy a routing layer that sends different tasks to different models.

    Routing strategies can be designed as follows:

    • For low-risk tasks such as text polishing and summarization, use a lightweight model to reduce latency and unit cost.
    • For high-risk tasks such as formula derivation, code review, and deep paper analysis, use a more capable model.
    • When the primary model fails, fall back to a backup model, and fall back only once. If the backup model also fails, return a clear error and let the caller decide whether to escalate to manual handling.

    The following code can be adapted and used directly. It reads endpoints and keys from environment variables, sets timeouts, performs a limited number of exponential backoff retries for retryable errors, distinguishes retryable from non-retryable errors, and records logs.

    1. import logging
    2. import os
    3. import time
    4. import requests
    5. logger = logging.getLogger("model_router")
    6. class ModelCallError(Exception):
    7. """Model call failed after retries were exhausted, or a non-retryable error occurred."""
    8. class ModelRouter:
    9. ROUTES = {
    10. "code_review": "heavy",
    11. "math_logic": "heavy",
    12. "paper_analysis": "heavy",
    13. "summary": "light",
    14. }
    15. def __init__(self, timeout=30, max_retries=2, backoff_base=1.0):
    16. self.endpoints = {
    17. "light": os.getenv("LIGHT_MODEL_API_URL"),
    18. "heavy": os.getenv("HEAVY_MODEL_API_URL"),
    19. "fallback": os.getenv("FALLBACK_MODEL_API_URL"),
    20. }
    21. self.api_key = os.getenv("MODEL_API_KEY")
    22. self.timeout = timeout
    23. self.max_retries = max_retries
    24. self.backoff_base = backoff_base
    25. missing = [name for name, url in self.endpoints.items() if not url]
    26. if missing:
    27. raise RuntimeError(f"Missing endpoint environment variables: {missing}")
    28. if not self.api_key:
    29. raise RuntimeError("Missing environment variable MODEL_API_KEY")
    30. def route_and_call(self, prompt, task_type="general", max_tokens=2048):
    31. model_type = self.ROUTES.get(task_type, "fallback")
    32. try:
    33. return self._call_with_retry(self.endpoints[model_type], prompt, max_tokens)
    34. except ModelCallError as primary_error:
    35. if model_type == "fallback":
    36. raise
    37. logger.warning("Primary endpoint %s failed; falling back to fallback: %s", model_type, primary_error)
    38. return self._call_with_retry(self.endpoints["fallback"], prompt, max_tokens)
    39. def _call_with_retry(self, url, prompt, max_tokens):
    40. headers = {"Authorization": f"Bearer {self.api_key}"}
    41. payload = {"prompt": prompt, "max_tokens": max_tokens}
    42. last_error = None
    43. for attempt in range(self.max_retries + 1):
    44. try:
    45. resp = requests.post(url, json=payload, headers=headers, timeout=self.timeout)
    46. except requests.RequestException as exc:
    47. last_error = exc
    48. else:
    49. if resp.status_code == 429 or resp.status_code >= 500:
    50. last_error = f"HTTP {resp.status_code}"
    51. elif resp.status_code != 200:
    52. raise ModelCallError(f"Non-retryable HTTP {resp.status_code}: {resp.text[:200]}")
    53. else:
    54. try:
    55. data = resp.json()
    56. except ValueError as exc:
    57. raise ModelCallError("Response is not valid JSON") from exc
    58. usage = data.get("usage", {}) if isinstance(data, dict) else {}
    59. logger.info("Call succeeded attempt=%d usage=%s", attempt + 1, usage)
    60. return data
    61. logger.warning("Attempt %d failed: %s", attempt + 1, last_error)
    62. if attempt < self.max_retries:
    63. time.sleep(self.backoff_base * (2 ** attempt))
    64. raise ModelCallError(f"Still failed after {self.max_retries} retries: {last_error}")

    Key points of the code:

    • Environment variables: LIGHT_MODEL_API_URL, HEAVY_MODEL_API_URL, and FALLBACK_MODEL_API_URL store the three types of endpoints, while MODEL_API_KEY stores the access key. Read keys only from environment variables or a secret management service, and do not write them into code or logs.
    • Authentication: The request header uses a Bearer token. Follow the documentation of the selected platform for the specific authentication method.
    • Timeout: The default is 30 seconds. Long-text inference may be slower, so adjust according to measured P95 latency.
    • Retries: Retry only network errors, 429, and 5xx, with a maximum of 2 retries and waits of 1 second and 2 seconds. Other 4xx errors indicate a problem with the request itself, so retrying is pointless.
    • Fallback: After the primary endpoint fails, switch to the backup endpoint only once. If the backup endpoint also fails, pass the exception to the caller.
    • Cost measurement: Log the usage field returned by each call. Calculate cost as “unit price multiplied by input and output tokens” and aggregate by task_type. Take unit prices from the platform’s billing page and update them whenever pricing changes.
    • Rate limiting: The code above does not implement rate limiting. When multiple threads or processes call concurrently, use threading.Semaphore to limit the number of in-flight requests, or set a requests-per-minute limit at the gateway layer.
    • Alerting: Connect logger.warning to the logging platform and set alerts for fallback counts and 5xx ratios. A sudden increase in fallback counts usually indicates a problem with the primary endpoint.

    7. Choosing a cloud platform

    Inference services offered by cloud platforms commonly include enterprise gateways, load balancing, quota management, monitoring and alerting, and private network access. When choosing, compare at least three platforms and examine the following conditions:

    • The list of available models and whether model versions can be pinned.
    • Availability commitments in service-level agreements and fault compensation terms.
    • Default quotas for requests per minute and concurrency, and whether they can be increased on demand.
    • Data storage regions and compliance requirements, especially when unpublished research data is involved.
    • Billing granularity, including whether input and output tokens are priced separately and whether cached pricing is available.
    • Migration cost: whether interfaces are compatible with common call formats and whether changing models requires changes to business code.

    Do not make a decision merely because a platform’s console is easier to use. Run a complete comparison using the test sets from Sections 4 and 5; the results will be more reliable.

    8. Use RAG to reduce hallucination, not to eliminate it

    Retrieval-augmented generation (RAG) provides authoritative materials as context to the model, making answers traceable. A typical workflow is as follows:

    1. Knowledge base construction: Split papers, technical specifications, and internal documents into chunks, generate vectors, and store them in a vector database. Preserve titles, page numbers, and section information during chunking to support traceability.
    2. Retrieval: After a user asks a question, retrieve the Top-K most relevant chunks. The value of K needs to be determined using a test set.
    3. Generation: The prompt requires the model to answer only based on the given chunks. When the material is insufficient, the model should explicitly answer “There is no relevant information in the materials” and annotate each conclusion with the corresponding chunk ID.
    4. Human review: Before publication or submission, manually verify cited literature, formulas, and interfaces against the original sources.

    RAG can significantly reduce fabricated content, but it cannot completely eliminate hallucination. There are three common failure modes:

    • Inaccurate retrieval: Relevant chunks are not recalled, so the model can only refuse to answer or answer based on irrelevant content.
    • Conflicting context: Different chunks give inconsistent values or conclusions, and the model may arbitrarily choose one of them.
    • Citation mismatch: The answer itself is correct, but the annotated chunk ID points to the wrong location.

    For monitoring, track retrieval recall, citation accuracy, refusal rate, and the number of errors found by human review. Citation accuracy can reveal problems in the retrieval stage relatively early, because an answer may happen to be correct while its citation is already wrong.

    9. Conclusion

    LLM selection for science and engineering scenarios is an engineering problem that requires continuous validation. First, break tasks into acceptance checklists, then compare candidate models using your organization’s private test sets. For version upgrades, follow a process of pinning, canary release, and regression testing. The routing layer should route by task risk and retain fallback and cost measurement. Use RAG to reduce hallucination, with human review as the final gate. These practices can be repeatedly tested against the same set of test data, and conclusions should be based on data.