Methods and Practices for Large Model Selection in AI Agent Scenarios

    This article explores the methodology for selecting large language models (LLMs) in AI agent scenarios. It covers the evolution of LLMs, model classification, key evaluation dimensions such as task matching, tool calling, context length, latency, cost, and data security, as well as a reproducible evaluation workflow with a sample Python script.

    1. The Core Issue: No Universal Optimal Solution

    When developers ask “which large model is the best,” they often expect a definitive answer. In reality, a model’s performance is highly correlated with specific tasks. A model that excels at code generation might not be the best choice for long-document summarization or customer service. Therefore, the selection problem should be reframed as: given specific business objectives, resource constraints, and compliance requirements, which model meets the criteria at the lowest overall cost?

    Rewriting the problem into a verifiable format is the first step in model selection. Teams need to clarify three things: the type of task, the scale of input and output, and the upper limits for response time and cost per call.

    2. Evolution of Large Language Models

    The development of large models can be roughly divided into three stages. The first stage was characterized by parameter expansion, growing from hundreds of millions to hundreds of billions of parameters, significantly improving language understanding and generation. The second stage broke through with conversational interaction, using instruction fine-tuning and human feedback alignment to enable models to stably perform Q&A, writing, and coding assistance. The third stage focuses on multimodal input and tool calling, allowing models not only to understand images and files but also to select external functions based on task descriptions, generate structured parameters, and process return results.

    This evolution directly impacts selection criteria. In the past, you only needed to focus on generation quality. Now, you also need to evaluate whether a model can reliably output correctly formatted function calling parameters, maintain state across multi-turn interactions, and locate key information within long contexts.

    3. Model Classification

    Based on capability scope and deployment methods, common large models can be divided into the following categories:

    • General-purpose large models: Broad coverage, suitable for multiple tasks like Q&A, writing, reasoning, and coding. Usually accessed via cloud APIs and billed by usage.
    • Vertical domain models: Extra training or knowledge enhancement on industry corpora (e.g., healthcare, legal, finance), suitable for scenarios with dense terminology and high accuracy requirements. The trade-off is that general capabilities might be slightly compromised.
    • Open-source local models: Weights can be downloaded and run on your own servers, keeping data in-house and allowing deep customization. Teams must bear the costs of compute procurement, operations, and performance tuning.
    • Hybrid deployment solutions: Sensitive data and high-frequency simple requests are handled by local models, while complex reasoning tasks are routed to cloud models, balancing privacy, cost, and effectiveness.
    • Tool-calling optimized models: Specifically trained for agent scenarios, offering more stability in function selection, parameter filling, and multi-step planning.

    These categories are not mutually exclusive. An agent system often uses multiple models simultaneously, such as a lightweight local model for intent recognition and a more capable cloud model for complex planning.

    4. Key Evaluation Dimensions for Model Selection

    4.1 Task Matching

    Task matching is the primary dimension. It is recommended to decompose your business into several sub-tasks, such as intent classification, information extraction, long-text summarization, code modification, and multi-step tool calling, and define evaluation standards for each. Classification tasks focus on accuracy and format stability; generation tasks focus on factual consistency and language quality; agent tasks focus on end-to-end success rate.

    4.2 Tool Calling Capability

    In agent scenarios, whether a model can correctly call tools is more important than text fluency. Evaluation should examine the following points:

    • Whether the function selection is correct, and whether it avoids unnecessary calls when no tool is needed.
    • Whether parameters are complete and conform to the schema, with correct types and enum values.
    • Whether it can retry or switch to another path after a tool returns an error.
    • Whether it maintains previous results in multi-turn tasks, without repeating steps or omitting them.

    4.3 Context Length and Information Localization

    Long context capability determines whether a model can ingest a complete document or history at once. However, a longer window does not guarantee better results. During testing, you can embed key information at different positions in a long text, count the model’s recall rate, and observe whether the answer quality drops significantly as input length grows.

    4.4 Latency, Throughput, and Cost

    Online interactive scenarios are sensitive to first-token latency, while batch processing scenarios focus more on throughput and unit cost. Cost estimation should include input and output token consumption, the number of failed retries, and extra rounds caused by tool calls. A model with a lower unit price that requires multiple rounds of correction might incur a higher overall cost than a more expensive model that succeeds on the first try.

    4.5 Data Security and Compliance

    When dealing with personal information, trade secrets, or regulated data, the following questions must be clarified: Is data transferred across borders? Is it used for model training? How long are logs retained? How is access control implemented? This dimension often directly determines whether cloud services can be used at all and should be assessed during the candidate shortlisting phase.

    4.6 Ecosystem and Maintainability

    API stability, documentation completeness, predictable version iterations, and timely issue response all affect long-term maintenance costs. It is recommended to add a unified interface abstraction layer between business code and the model. This allows you to switch models without altering business logic and reduces the risk of vendor lock-in. If teams have localization or specific deployment requirements, services such as those provided by Baidu AI Cloud can be included in the same evaluation framework and compared against other candidate solutions using the same standards.

    5. Establishing a Reproducible Evaluation Workflow

    It is recommended to follow these steps:

    1. Build an evaluation set: Extract samples from real business logs, covering common requests and edge cases. Prepare at least dozens of samples per task type and label the expected outputs.
    2. Define automated metrics: Prioritize metrics that can be programmatically judged, such as format validation, tool calling accuracy, and key field match rates.
    3. Manual review: Sample and score tasks involving semantic quality, using unified scoring criteria and cross-scoring by multiple reviewers.
    4. Sample cost and latency: Record the duration and token usage for each sample, and calculate the P95 latency and per-task cost.
    5. Form a decision matrix: Aggregate effectiveness, cost, latency, and compliance based on business weights to obtain a comprehensive score for each candidate model.

    Below is a sample evaluation script demonstrating how to batch test multiple candidate models through a unified interface. Here, call_model is a placeholder function; the actual implementation needs to connect to the model service your team uses.

    ```python
    import json
    import time
    from statistics import quantiles

    def call_model(model_id: str, messages: list, tools: list | None = None) -> dict:
    “””Placeholder function, returns {‘content’: str, ‘tool_calls’: list, ‘usage’: {…}}”””
    raise NotImplementedError

    def check_tool_call(result: dict, expected: dict) -> bool:
    calls = result.get(“tool_calls”) or []
    if not calls:
    return False
    first = calls[0]
    if first[“name”] != expected[“name”]:
    return False
    try:
    args = json.loads(first[“arguments”])
    except json.JSONDecodeError:
    return False
    return all(args.get(k) == v for k, v in expected[“arguments”].items())

    def evaluate(model_id: str, dataset: list) -> dict:
    correct, latencies, tokens = 0, [], 0
    for sample in dataset:
    start = time.perf_counter()
    result = call_model(model_id, sample[“messages”], sample.get(“tools”))
    latencies.append(time.perf_counter() - start)
    tokens += result[“usage”][“total_tokens”]
    if check_tool_call(result, sample[“expected”]):
    correct += 1
    p95 = quantiles(latencies, n=20)[18] if len(latencies) >= 20 else max(latencies)
    return {
    “model”: model_id,
    “accuracy”: correct / len(dataset),
    “p95_latency_s”: round(p95, 3),
    “avg_tokens”: tokens / len(dataset),
    }

    Batch evaluate the list of candidate models and sort by accuracy and latency

    results = sorted(

    (evaluate(m, dataset) for m in candid