How to Choose and Integrate Large Language Models for AI Agent Development

    This article walks application developers through a practical, repeatable process for selecting and integrating an LLM: turning business requirements into measurable metrics, evaluating candidates across five dimensions (task fit, performance, cost, ecosystem, and compliance), validating them with your own evaluation set and a small-traffic rollout, and designing the architecture so any model can be swapped out later. It includes concrete cost formulas, sample evaluation and backend-abstraction code, routing patterns, and a checklist to run before switching models.

    1. Introduction: Choosing a model means choosing a solution, not a name

    Over the past year or two, general-purpose LLM services have converged rapidly in terms of capability. Text generation, logical reasoning, code generation, structured output, tool calling, long-context understanding, and multimodal recognition are becoming standard features across providers. That convergence has two direct consequences:

    • The capability gap between any two models is shrinking: the real question is no longer “which model is strongest” but “which model best fits my scenario and my constraints.”
    • Models are still iterating fast: today’s best choice may be rewritten by a new release in a few months. Old model identifiers usually keep working for a while after a new version ships, but billing rules and output style can shift underneath you.

    Model selection therefore should not be a one-off gut decision. It should be an engineering capability that is measurable, reproducible, and quick to switch. From an application developer’s point of view, this article breaks the process into five steps:

    1. Decompose the requirements
    2. Evaluate across dimensions
    3. Verify with benchmarks and a PoC
    4. Integrate at the architecture level
    5. Keep governing over time

    The goal is a selection approach that is well-justified, easy to swap, and continuously improved.

    2. Step 1: Translate business requirements into measurable metrics

    Selection starts with the business, not with a model list. Before writing code, answer four questions on a single page:

    • What task are you solving? For example: customer support Q&A, long-document summarization, information extraction, code generation.
    • What quality level counts as usable? For example: accuracy no lower than 95%, human satisfaction no lower than 4 out of 5.
    • What constraints does it run under? For example: whether data may leave your environment, budget ceiling, peak concurrency, acceptable response time.
    • Who maintains it? An algorithm team, a backend team, or the business team? Will you later need fine-tuning or on-premises deployment?

    Turn the answers into a “requirement-to-metric” mapping table so the discussion has something concrete to stand on.

    Requirement Corresponding metric Validation method
    Customer support Q&A Answer accuracy, correct refusal rate Offline evaluation on a labeled question set
    Contract summarization Recall of key information, human adoption rate Sampling review by business staff
    Information extraction Field-level F1, JSON format validity rate Automated script validation
    Code generation Unit test pass rate Automated testing
    Real-time conversation P95 first-token latency, output speed Load testing
    Sensitive data handling Data does not leave the environment, auditable traces Compliance review, architecture review

    It also helps to split the requirements into two groups:

    • Hard gates: failing any of these is disqualifying, for example data cannot leave the country, on-premises deployment is mandatory, or monthly cost must stay under a given budget.
    • Optimization goals: among candidates that clear the gates, compare quality, for example every additional percentage point of accuracy, or how much the cost per call can drop.

    With this table in place, every evaluation dimension maps to a clear business value, which keeps the discussion from sliding into “bigger parameter count is better.”

    3. Step 2: Build a five-dimension evaluation framework

    3.1 Effectiveness and task fit: judge on real tasks, not leaderboard rank

    Public benchmark leaderboards are useful as a first filter, but they cannot replace validation on your own workload. There are three reasons:

    • Different task distributions: benchmark prompts differ greatly from real user input in wording, length, and domain terminology.
    • Prompt sensitivity: the same model can perform very differently under different prompts, so a score only reflects results under one specific condition.
    • Benchmark contamination: public test items may already be heavily represented in training data, which makes generalization hard to judge.

    A more reliable approach is a small-scale live test on business data. Take contract information extraction as an example and focus on:

    • The accuracy and completeness of extracted fields;
    • Whether the model honestly returns an empty value when a field is missing from the document, instead of fabricating content;
    • Whether the output reliably conforms to the JSON Schema rather than mixing in explanatory prose.

    These metrics often correlate only weakly with leaderboard scores.

    3.2 Performance and stability: latency, throughput, and rate limiting

    Once quality clears the bar, performance shapes the user experience. At minimum, look at:

    • First-token latency: in streaming output, how long until the user sees the first token. This drives the perceived responsiveness of conversational applications and matters more to experience than total end-to-end time.
    • Output speed: tokens generated per unit of time. Roughly, total time equals first-token latency plus output tokens divided by output speed, and scenarios that produce long text are especially sensitive to it.
    • Concurrency and rate limits: understand the per-account or per-key quotas, such as requests per minute and tokens per minute, and what the service returns once a limit is triggered.
    • Availability commitments: whether the service level agreement meets business requirements, and whether you can degrade gracefully during an outage.

    When load testing, simulate realistic peak traffic and watch P95 and P99 latency rather than only the average. Averages easily hide the stalls caused by long-tail requests.

    3.3 Cost: work out what it actually costs to complete one task

    Model services are usually billed per token, with input and output priced separately, and the output price is generally much higher than the input price. Developers often overlook these hidden costs:

    • Repeated consumption: the system prompt is resent on every request, and multi-turn conversations keep carrying the message history. Late in a long conversation, a single request’s input tokens can reach many times the first turn’s.
    • Retry consumption: re-invoking after a timeout or a format-validation failure can multiply the cost.
    • Reasoning models: some models generate a long reasoning trace before the answer. Whether that content is billed, and how, varies by provider, so check the service documentation rather than assuming.

    A better metric is “cost per completed task,” which you can approximate with this simplified formula:

    1. cost per task = input tokens per call × input price
    2. + output tokens per call × output price
    3. + retry rate × cost per call

    For example, a task averaging 3,000 input tokens and 300 output tokens with a 10% retry rate:

    • At CNY 0.001 per 1K input tokens and CNY 0.006 per 1K output tokens, the cost per task is about CNY 0.00498, or about CNY 498 per day at 100,000 calls per day.
    • With a lightweight model at CNY 0.0004 per 1K input tokens and CNY 0.002 per 1K output tokens, the same conditions give about CNY 0.00186 per task, or about CNY 186 per day.

    That is a difference of more than CNY 300 per day, nearly CNY 10,000 per month, and the gap widens as the business grows. If the task is not sensitive to the input content, these optimizations are also worth considering:

    • Caching high-frequency fixed prefixes;
    • Caching results;
    • Summarizing and compressing message history.

    3.4 Engineering ecosystem and switching cost: can you replace a model smoothly?

    • Interface shape: most mainstream model services expose JSON APIs over HTTP, with fields such as messages in the request. Adopting this common convention makes it fairly easy to switch between providers at the integration layer.
    • Supporting capabilities: whether structured output, function calling, streaming responses, and batch inference are supported. These directly affect how complex your business code becomes.
    • Portability: beyond hosted model services, some scenarios also require on-premises deployment. In that case, also consider how model weights are obtained, what inference resources are needed, and what the team can operate.

    One easily overlooked factor is model identifier naming conventions. Platforms do not name model versions consistently. Some append suffixes such as “latest” or “stable” to a base name, pointing at a continuously updated version; some use fixed snapshot identifiers that point at one behaviorally stable version; and a single family is often split into different sizes by parameter count. On fast-moving platforms, the generation and size of a model should be confirmed against the official documentation rather than guessed from habit.

    In production, pin an explicit version snapshot so behavior is reproducible. In test environments, an alias that follows updates is fine and lets you try new capabilities early. The exact rules depend on the provider, so verify them in the official documentation.

    3.5 Compliance and security: the lines you cannot cross

    Compliance is often a hard gate, so settle these points early:

    • Data boundaries: whether business data may be sent to an external service, and whether personal information and sensitive commercial data need to be masked first.
    • Content safety: whether inputs and outputs must pass content filtering, and what the process is when prohibited content appears.
    • Auditability: how long call records are retained, and whether you can trace a specific request and response.
    • Deployment model: public cloud API, on-premises deployment, or a hybrid.

    If your business is built on a cloud environment such as Baidu AI Cloud, you can combine the model service with foundational capabilities such as object storage, logging, monitoring and alerting, and key management to build a unified LLM gateway. The gateway handles authentication, quotas, auditing, and call records, which satisfies compliance requirements while keeping room to switch models later.

    3.6 Weighting the five dimensions per business

    There is no universal weighting for these five dimensions. For example:

    • Consumer-facing applications can weight effectiveness and performance more heavily;
    • Internal enterprise tools tend to care more about cost and compliance;
    • Data-sensitive industries put compliance first.

    Have the team agree on the weights before scoring each dimension, which reduces subjective argument.

    4. Step 3: Narrow the candidate list with evaluation and a PoC

    4.1 Build your own evaluation set

    The quality of the evaluation set determines how trustworthy the conclusion is. Sample from real production requests to build a set of a few dozen to a few hundred cases, covering:

    • Typical cases: the most common inputs, most representative of day-to-day requests;
    • Boundary cases: very long inputs, empty inputs, mixed languages, unusual formats;
    • Error-prone cases: requests that have failed or drawn complaints before;
    • Adversarial cases: inputs that try to make the model fabricate facts or produce prohibited content.

    Each case should come with a reference answer or an automatically executable check function, and the whole set should be version controlled. That way, after a model upgrade you can run a one-command regression and avoid shipping a silent quality regression nobody noticed.

    4.2 Multi-dimensional comparison and small-traffic validation

    For subjective-quality generation tasks, pairwise comparison works well: shuffle the outputs of two models and have business staff evaluate them blind, which reduces brand bias.

    Candidates with stable quality can then go through a small-traffic canary. Keep recording real call data during the canary and watch in particular:

    • User feedback metrics;
    • Cost per task;
    • Changes in error rate.

    Only move to full rollout once the small-traffic numbers meet the baseline.

    4.3 Example evaluation skeleton

    The following is illustrative evaluation code. It abstracts the common flow of “batch invocation, automated checking, summary report”; to connect a specific service you only need to implement the chat method.

    1. from dataclasses import dataclass
    2. from typing import Callable
    3. @dataclass
    4. class EvalCase:
    5. id: str
    6. messages: list[dict]
    7. check: Callable[[str], tuple[bool, float, int]] # returns (passed, elapsed seconds, output tokens)
    8. def evaluate(chat_fn, cases: list[EvalCase]) -> dict:
    9. """chat_fn(messages) -> str; check is implemented on the business side"""
    10. passed = total_cost = total_time = 0
    11. for case in cases:
    12. answer = chat_fn(case.messages)
    13. ok, cost, elapsed = case.check(answer)
    14. passed += int(ok)
    15. total_cost += cost
    16. total_time += elapsed
    17. n = len(cases)
    18. return {
    19. "pass_rate": round(passed / n, 3),
    20. "avg_cost": round(total_cost / n, 4), # average cost per task
    21. "avg_time": round(total_time / n, 3), # average elapsed time (seconds)
    22. }

    5. Step 4: Design the architecture so swapping models is easy

    5.1 A unified access layer

    Whichever provider you end up with, put an abstraction layer between business code and the model service, and define only the methods the business actually needs:

    1. from abc import ABC, abstractmethod
    2. class LLMBackend(ABC):
    3. @abstractmethod
    4. def chat(self, messages: list[dict], **kwargs) -> str:
    5. """Send a chat request and return text; see below for the messages format"""

    messages follows the widely used role convention: system sets the role and constraints, user carries user input, and assistant carries prior replies in a multi-turn conversation.

    Each concrete implementation only has to do three things:

    1. Read configuration;
    2. Assemble the request according to that service’s HTTP convention;
    3. Parse the response into the unified return value.
    1. import os
    2. import requests
    3. class HttpLLMBackend(LLMBackend):
    4. """Adapter for model services that follow the HTTP/JSON convention (illustrative)"""
    5. def __init__(self, base_url: str, api_key: str, model: str, timeout: int = 30):
    6. self.url = base_url.rstrip("/") + "/chat/completions" # confirm the path in the service docs
    7. self.headers = {"Authorization": f"Bearer {api_key}"}
    8. self.model = model
    9. self.timeout = timeout
    10. def chat(self, messages: list[dict], **kwargs) -> str:
    11. payload = {"model": self.model, "messages": messages, **kwargs}
    12. resp = requests.post(self.url, json=payload,
    13. headers=self.headers, timeout=self.timeout)
    14. resp.raise_for_status()
    15. return resp.json()["choices"][0]["message"]["content"]

    With this in place, changing models usually means changing configuration, with almost no business code changes.

    5.2 Task-based routing

    Different tasks have different requirements, and sending everything to one model is neither economical nor necessarily optimal. Three routing strategies are common:

    • Capability routing: send complex reasoning and code tasks to a stronger reasoning model; send routine summarization, classification, and rewriting to a lightweight model.
    • Cost routing: set a cost ceiling per task and automatically switch over-budget requests to a cheaper model.
    • Failover routing: when the primary model times out or errors, automatically switch to a backup model to keep the service available.
    1. # Illustrative config: task -> primary and fallback model
    2. ROUTES = {
    3. "reasoning": {"primary": "reasoning_model", "fallback": "general_model"},
    4. "summary": {"primary": "light_model", "fallback": "general_model"},
    5. }
    6. def call_model(task: str, messages: list[dict], **kwargs) -> str:
    7. route = ROUTES.get(task, ROUTES["summary"])
    8. try:
    9. return BACKENDS[route["primary"]].chat(messages, **kwargs)
    10. except Exception:
    11. # In production, log the failure and metrics, and throttle fallback triggers to avoid a cascade
    12. return BACKENDS[route["fallback"]].chat(messages, **kwargs)

    6. Step 5: Model configuration in development assistants

    For many developers, the first place they encounter “model selection” is an AI coding assistant or an IDE plugin. These tools usually let you configure the service endpoint, access credentials, and model identifier in settings, and you can start chatting once it is saved.

    A few practical recommendations:

    1. Keep credentials out of config files: inject them through environment variables or a system secret manager so keys never get committed to the repository along with configuration.
    2. Manage model identifiers centrally: multiple tools often each keep their own copy of the model configuration, and upgrades get missed. Maintain a shared configuration inventory, or a team-level configuration template.
    3. Separate test from production: test environments can use aliases that follow updates to try new capabilities early; production should pin version snapshots to keep behavior stable.
    4. Match models to scenarios: code completion values response speed, while architecture design and technical writing value reasoning depth. Different models per scenario usually beats “one model for everything.”

    7. Common pitfalls and a checklist to avoid them

    • Trusting leaderboards only: leaderboards are for first-pass filtering; the final decision should rest on your own evaluation set.
    • Looking at unit price only: ignoring the input/output ratio, retries, and context growth means the real bill can far exceed expectations.
    • Changing prompts frequently without comparison: you cannot tell whether a quality change came from the model or the prompt. Put prompts under version control and change one variable at a time.
    • No degradation plan: when a single service is rate limited or fails, the business simply goes down.
    • Hard-coding model identifiers: retiring or revising a model then requires sweeping code changes.
    • No monitoring after launch: selection is not a one-time action; track quality, cost, and latency over time.

    Have the team maintain a selection checklist and confirm each item before switching models:

    • Does the pass rate on the business evaluation set meet the baseline?
    • Is the cost per task within budget?
    • Does P95 latency meet the experience requirement?
    • Have data and content safety passed review?
    • Are the backup model and degradation strategy ready?
    • Are model identifiers and configuration recorded centrally?

    8. Conclusion: make model selection a sustainable engineering capability

    There is no universal answer to “which LLM should I choose.” A more reliable approach is:

    1. Start from business requirements and define metrics and constraints;
    2. Build an evaluation framework across five dimensions: effectiveness, performance, cost, ecosystem, and compliance;
    3. Validate candidates with your own evaluation set and a small-traffic canary;
    4. Write “replaceable” into the architecture through a unified access layer and model routing.

    On cloud platforms such as Baidu AI Cloud, model services can be combined with foundational capabilities like object storage, logging, and monitoring and alerting to support model integration and ongoing governance. Ultimately, the model is just one replaceable component in the system. Once the selection method, the evaluation system, and the degradation mechanisms are in place, your application stays flexible, stable, and cost-efficient no matter how the model market shifts.