Selecting Open-Source LLMs by Scenario and Building Reliable AI Agents

    This article provides a practical guide to choosing the right open-source large language model (LLM) for your deployment environment, latency budget, and task complexity. It covers model size gradients from small edge models to dense large-scale models, cost-efficient handling of multimodal inputs, estimating KV cache memory for long-context tasks, enforcing structured output and function calling, and design principles for robust agent workflows. A pre-launch checklist is included to help teams validate models with real business samples, review licenses, ensure security, and plan for cost and concurrency.

    1. Shift from “Pursuing the Best Model” to “Matching the Scenario”

    Open-source LLMs now come in a full spectrum of parameter sizes, and the latest generation is often released in multiple configurations simultaneously. The question for teams is no longer “which model has the highest benchmark score,” but rather “which configuration can reliably complete the target task within the constraints of existing compute, latency, and cost.”

    Three dimensions determine whether a model size fits your use case:

    • Deployment environment – edge device, server, or workstation
    • Latency budget – acceptable time for a single inference
    • Reasoning depth – how complex the task is

    Ignoring any of these can lead to runaway costs or poor user experience after deployment.

    2. Model Size Gradients and Deployment Positions

    The table below summarizes typical use cases for four model categories, ordered by increasing compute requirements.

    Model Type Typical Deployment Suitable Tasks Key Constraints
    Small (~2B params) Mobile phones, embedded devices, offline environments Text classification, information extraction, simple Q&A, voice interaction Limited complex reasoning capability
    Medium (~4B params) High-performance edge devices, edge nodes Multi-turn dialogue, lightweight code assistance Limited long-text reasoning
    Mixture-of-Experts (~26B total params) A single server or workstation Multi-step planning, code generation VRAM must accommodate all expert weights
    Dense (~31B params) Workstations or multi-GPU servers Complex reasoning, high-quality generation Large per-inference compute, higher latency

    Mixture-of-Experts (MoE) architectures split the network into multiple expert sub-networks. A routing module activates only a small subset of experts for each token. As a result, the actual parameters involved in each inference are far fewer than the total parameter count, which lowers computational cost. However, all expert weights must still reside in memory. When estimating cost, it is important to distinguish between “computationally cheaper” and “memory cheaper.”

    Dense models activate all parameters during every inference, so output quality is typically more stable. The trade-off is that computational cost scales with model size, leading to higher latency.

    3. Engineering Multimodal Inputs

    Image and video inputs are becoming baseline requirements for many business applications. Before integration, clarify three points:

    1. Image resolution. Higher resolution produces more visual tokens and increases inference cost. Tasks that require fine detail, such as receipt recognition, need high resolution; scene classification can use a lower resolution.
    2. Video frame extraction. Videos are usually sampled at fixed time intervals or key frames. The number of frames and resolution together determine input size. First estimate the token budget for a typical request, then decide on the sampling strategy.
    3. Audio input. Some small models support native audio input. For voice-related tasks, compare two paths: feeding audio directly to the model, or first transcribing it to text and then passing the text to the model. Measure the differences in latency and accuracy using your own sample data.

    Use the following formula to estimate token budget and leave headroom:

    1. token_budget = image_tokens × image_count + video_frames × tokens_per_frame + text_tokens
    2. if token_budget > context_limit × 0.8:
    3. reduce resolution or decrease frame sampling

    4. Cost Model for Long Contexts

    The context length stated in a model specification (e.g., 128K or 256K tokens) is the maximum input the model can accept – not a license to fill it without cost. During inference, the model must cache the key-value (KV) cache for every layer. An approximate memory footprint can be estimated as:

    KV cache memory ≈ 2 × layers × KV_heads × head_dim × sequence_length × bytes_per_element × concurrent_requests

    For example, with 48 layers, 8 KV heads, head dimension 128, 16-bit precision (2 bytes per element), and a sequence length of 131,072 (128K tokens), a single request’s cache is approximately:

    2 × 48 × 8 × 128 × 131072 × 2 bytes ≈ 24 GiB

    Serving multiple long-context requests concurrently multiplies memory pressure accordingly.

    Practical recommendations:

    • When a task can be solved by retrieval and chunking, prefer splitting the content before sending it to the model rather than stuffing the entire long context in.
    • Reserve ultra-long context for tasks that truly need global understanding, such as cross-referencing clauses across an entire contract.
    • Plan concurrency and context length together. Do not stress-test a single request and then go live without testing realistic concurrent load.

    5. Structured Output and Function Calling

    In agent systems, model output must be reliably parsable by the program. The recommended approach is to define the input/output schema first, have the model generate according to that schema, and then validate and retry at the program level rather than trusting the raw output.

    Here is an example tool definition:

    1. {
    2. "name": "query_order_status",
    3. "description": "Query the current status of an order by its ID",
    4. "parameters": {
    5. "type": "object",
    6. "properties": {
    7. "order_id": {"type": "string", "description": "Order ID"}
    8. },
    9. "required": ["order_id"]
    10. }
    11. }

    A typical call flow in pseudocode:

    1. response = model.generate(prompt, tools=tool_definitions)
    2. for call in response.tool_calls:
    3. args = parse_JSON(call.arguments)
    4. if not validate_schema(args):
    5. log_error_and_retry(call, max_retries=N)
    6. continue
    7. result = execute_tool(call.name, args)
    8. append_result_to_context(result)

    Three implementation notes:

    1. The arguments generated by the model are only candidate inputs – never use them directly for database queries or system calls. Use parameterized queries.
    2. Write operations require independent permission checks.
    3. When a tool call fails, provide a fallback path, such as returning an error message to the user or routing the case to human review.

    6. Design Principles for Agent Workflows

    Most agents follow a loop of plan → execute → observe → decide whether to stop. Engineering practices should follow these principles:

    • Limit the maximum number of steps to prevent infinite loops and runaway cost.
    • Design tools to be idempotent where possible. Repeated execution of the same call should produce the same result, avoiding duplicate orders on retries.
    • High-risk actions such as deletion, money transfer, or external sends must require human confirmation.
    • Log inputs, outputs, and tool call records at every step for replay and troubleshooting.

    7. Pre-Launch Checklist

    1. Build your own evaluation set. Pull samples from real business scenarios, covering the target languages, input modalities, and long-text cases. Public benchmark rankings are only useful as a first-pass filter because their task distributions likely differ from your actual workload.
    2. Review licenses. Check the commercial terms, redistribution requirements, and attribution obligations of the open-source license. Permissive licenses generally allow commercial use, but always verify the exact clauses.
    3. Security. Implement prompt injection detection on user input, sensitive-information filtering on output, and apply the principle of least privilege for tool permissions.
    4. Cost and latency. Estimate memory, throughput, and time-to-first-token based on peak concurrency. Reserve headroom for scaling.

    8. Summary

    Model selection is a multi-dimensional engineering decision. Match the model size to the deployment environment, latency budget, and reasoning depth. Plan for multimodal token consumption, understand KV cache memory for long-context workloads, enforce structured output and function-calling validation, and design agent workflows with safeguards. Validate with your own data and review license and security implications before deployment.