LLM Service Selection: Hallucinations, Quotas, and Engineering Practices
Choosing an LLM service requires more than comparing benchmark scores. This article presents a practical framework for evaluating factual reliability, usage quotas, tool execution, and data analysis capabilities. It covers retrieval and citation checks, quota management, sandboxed execution, reproducible calculations, and a weighted evaluation process with a reversible trial period.
1. Choose the Right Capability Mix, Not the “Strongest” Model
Many model-selection discussions start with the wrong question: which model has the highest benchmark score? In production, the user experience often depends less on rankings than on how well four capabilities match the workload: factual accuracy, quota and rate-limit policies, local or sandboxed execution, and support for coding and data analysis.
A capable service that confidently invents details can become a liability when verifying medical literature. A cautious service with restrictive quotas and meandering responses can be equally inefficient for frequent scripting tasks.
Before comparing services, quantify your usage. Track four metrics for one week:
- Average conversation turns per day.
- Average context length per turn.
- Percentage of requests requiring external fact-checking.
- Percentage of requests requiring execution, such as writing files, running scripts, or reading spreadsheets.
These measurements should determine the weights used in the final evaluation.
2. Hallucinations Are a Hard Constraint in High-Risk Workflows
2.1 Distinguish Knowledge Gaps from Verification Failures
For engineering purposes, it is useful to distinguish two broad sources of hallucination.
The first is knowledge-based hallucination: the model’s internal knowledge is outdated or incomplete, but it still generates a plausible answer. Examples include invented material properties, pore counts, manufacturers, or publication identifiers.
The second is verification-effort failure: the system has tools that could verify an answer but does not use them. Retrieval, calculation, or execution is never triggered, and the model fills the gap with an unsupported guess.
The distinction matters because the remedies differ. Knowledge gaps require external retrieval and traceable references. Verification failures require enforced tool use and workflow orchestration.
2.2 The Engineering Value of Cautious Answers
Some services explicitly state when they cannot find evidence, identify the limits of their confidence, and avoid filling in details merely to appear knowledgeable.
This behavior is particularly valuable in high-risk domains. It exposes uncertainty to the surrounding workflow instead of disguising it as a definite conclusion.
Evaluation should therefore cover more than the percentage of correct answers. Examine what happens when the model is wrong or uncertain:
- Does it provide verifiable sources?
- Does it flag uncertainty?
- Does it recommend human review when appropriate?
2.3 Reduce Hallucination Risk with Engineering Controls
Regardless of the provider, do not rely on the model alone for accuracy. Use four layers of protection:
- Retrieval augmentation: Retrieve relevant passages from a local knowledge base or authoritative sources before answering factual questions. Replace answers from memory with answers grounded in evidence.
- Required citations: Require source identifiers for every key conclusion. Treat unsupported conclusions as unusable.
- Structured validation: Constrain the output schema. Missing fields or incorrect types should trigger failure and retry.
- External computation: Use code for numerical calculations. Let the model generate the code and explain the results rather than perform the arithmetic itself.
The following illustrative skeleton checks whether an answer includes a reference to a retrieved document:
import json, refrom typing import Anydef answer_with_citation(question: str, retrieve, llm) -> dict[str, Any]:"""Retrieve -> generate -> validate; reject answers without citations."""docs = retrieve(question, top_k=5)if not docs:return {"answer": None, "reason": "no_evidence", "citations": []}raw = llm(system="Answer only from the supplied passages. If the information is absent, return answer=null and explain what is missing.",context=docs,user=question,)try:payload = json.loads(raw) # Structured output for machine validationexcept json.JSONDecodeError:return {"answer": None, "reason": "schema_violation"}cited = set(re.findall(r"\[(\d+)\]", payload.get("answer") or ""))valid = {i for i in cited if 1 <= i <= len(docs)}if payload.get("answer") and not valid:return {"answer": None, "reason": "citation_missing"} # Reject unsupported answersreturn {"answer": payload["answer"], "citations": sorted(valid)}
The central principle is simple: do not accept an answer without evidence. Explicitly downgrade unverifiable output to a failure rather than letting it reach downstream systems.
3. Manage Quotas as an Engineering Resource
3.1 Account for Shared Quota Pools
Some platforms combine usage from web chat, coding assistants, and plugin calls into a shared quota pool. As a result, conversational usage can consume capacity needed for coding tasks.
This is a consequence of shared quota design, not necessarily a problem unique to one provider. The engineering response is quota budgeting: set separate daily usage limits for interactive questions, batch refactoring, and long-running agent tasks, and track usage locally in the client.
3.2 Four Client-Side Quota Controls
- Local metering: Track both input/output tokens and request counts. Near a threshold, switch to a more economical model or shorten the context.
- Request consolidation: Combine small questions into a single request with a checklist to reduce round trips and repeated system-prompt overhead.
- Context trimming: Retain relevant passages and a limited number of recent turns rather than allowing conversation history to grow indefinitely.
- Backoff and retry: Use exponential backoff with jitter when rate-limited to avoid retry storms.
import random, timedef call_with_backoff(fn, max_retry=5, base=0.5, cap=8.0):for attempt in range(max_retry):try:return fn()except RateLimitError:if attempt == max_retry - 1:raisedelay = min(cap, base * (2 ** attempt)) + random.uniform(0, 0.3)time.sleep(delay) # Exponential backoff with jitter
3.3 Use Free or Low-Cost Access for Appropriate Tasks
Low-cost or trial access can handle low-risk conversations and drafting tasks that tolerate delays. Reserve paid capacity for high-risk verification and longer, multi-step workflows.
This cost-tiering strategy depends on proper data classification. Sensitive data must remain within compliant services; saving money must never justify lowering security requirements.
4. Execution Matters More Than Explanation
For small scripts, batch renaming, and log cleaning, the key metric is execution success, not the quality of the written response.
Evaluate whether the service can reliably select the right tool, recover from failures, and avoid unproductive loops—for example, repeatedly taking screenshots or probing an interface without advancing the task.
Three engineering practices are especially important:
- Route by task mode. Explicitly send operational requests to an execution-capable agent mode. This reduces responses that merely discuss a task without using available retrieval or execution tools.
- Use a least-privilege sandbox. Mount only necessary directories, disable network access or allowlist destinations, and restrict writes to the workspace.
- Keep a complete audit trail. Record tool inputs, exit codes, and artifact hashes so failures can be replayed.
# Pseudocode: controlled execution with auditingdef run_task(task, sandbox):log = []for step in sandbox.plan(task): # The model generates the planr = sandbox.exec(step.cmd, timeout=120, network="deny")log.append({"cmd": step.cmd, "code": r.code, "sha": r.sha256})if r.code != 0:return {"ok": False, "trace": log} # Stop on failure; replan at a higher layerreturn {"ok": True, "trace": log}
5. Data Analysis Requires Code, Not Mental Arithmetic
For statistical questions, use a consistent workflow: have the model generate code, let an interpreter evaluate it, and then ask the model to interpret the results.
Model-generated arithmetic is unreliable for multi-digit calculations, grouped aggregations, and quantile estimates. These errors can also be difficult to notice in otherwise fluent explanations.
import pandas as pddef describe(df: pd.DataFrame, cols: list[str]) -> dict:"""The interpreter computes all numbers; the model does not calculate them."""return {"rows": int(len(df)),"cols": {c: {"count": int(df[c].count()),"mean": float(df[c].mean()),"std": float(df[c].std(ddof=1)),"q50": float(df[c].quantile(0.5)),} for c in cols},}
For reproducibility and auditing, fix random seeds, pin dependency versions, and retain notebooks together with hashes of the original inputs.
6. A Practical Decision Framework
Replace intuition with weighted scoring. Set weights according to the workload profile established in Section 1. For example, a high-risk workflow might assign factual reliability a weight of 0.45.
| Evaluation criterion | Measurement method | Suggested weight |
|---|---|---|
| Factual accuracy and quality of abstention | Test 50 domain-specific verification questions and measure the unsupported fabrication rate | 0.30–0.45 |
| Quota and rate-limit behavior | Run a two-hour sustained load test; record rate-limit frequency and recovery time | 0.15–0.25 |
| Tool use and execution success | Run 20 real tasks and measure first-pass success | 0.15–0.25 |
| Response efficiency and goal focus | Count the turns required to complete a task | 0.10–0.15 |
| Cost and compliance | Measure cost per task and assess data-classification requirements | 0.10–0.20 |
Use a two-track trial period. For two weeks, use candidate A as the primary service and candidate B as the backup. Route all high-risk outputs through the same retrieval and validation pipeline.
At the end of the trial, score both candidates using the evaluation table. Define switching conditions in advance—for example, an unsupported fabrication rate above an acceptable threshold or a rate-limit-related task failure rate above a set threshold.
This turns service selection from a one-time bet into a reversible engineering decision.
7. Three Common Mistakes
The first mistake is treating fluent answers as accurate answers. Fluency is not evidence of factual reliability.
The second is ignoring quota structure until deployment reveals that interactive and batch workloads compete for the same capacity.
The third is accepting numerical output directly from the model without executing code.
The client-side pipelines described above can address all three problems, regardless of which provider is selected.
8. Conclusion
Start by measuring the workload. Then place a consistent fact-checking pipeline and controlled execution sandbox around the model. Finally, use weighted scoring and a two-track trial to make the selection.
The value of this approach is that it converts unpredictable model behavior into measurable engineering outcomes and reversible decisions.
If the pipeline requires cloud infrastructure such as managed model services, object storage, message queues, container platforms, and logging, monitoring, and alerting, Baidu AI Cloud offers corresponding general product categories that can be considered during infrastructure evaluation. Availability and suitability for the intended deployment should be checked in the official documentation.
