Selecting and Deploying Open-Source LLMs for Agent Workflows

    This article explains how to choose and deploy open-source large language models for agent workflows. It covers the core capabilities an agent needs, including multi-step reasoning, function calling, and multimodal input. It also compares model sizes by compute tier, outlines agent loop design and structured output validation, and gives guidance on memory planning, licensing, and evaluation.

    1. Background: From Question Answering to Task Execution

    Large language models were first used mainly for question answering and text generation. As application needs have changed, the industry has paid growing attention to models that can break down tasks on their own, call external tools, and keep moving forward based on execution results. These applications are commonly called agent workflows.

    To take on this role, a model needs three core capabilities. The first is multi-step planning and logical reasoning. The model must split a complex goal into sub-steps in the correct order. The second is tool calling and structured output. The model must generate parameters in an agreed format so that a program can parse them directly. The third is understanding multiple types of input, including images, video, and audio.

    The main value of open-source models is deployment flexibility. Teams can run models on end-user devices, local servers, or private cloud infrastructure, so data never has to leave a controlled environment. Open-source models also let teams further adapt the model to their own business data.

    2. Three Dimensions of Model Capability

    1. Multi-Step Planning and Logical Reasoning

    Reasoning ability determines whether a model can complete long chains of tasks. To judge whether a model suits agent scenarios, check how it performs in the following areas:

    • Whether it can break a task such as “look up an order, check inventory, and generate a refund plan” into the correct sequence;
    • Whether it can recognize an error in an intermediate step and adjust its plan;
    • Whether it can follow several interdependent constraints at once, such as format, length, and tone requirements.

    Some open-source models support a “thinking mode,” which generates a longer internal reasoning process before the final answer. This mode increases latency and token consumption. It suits tasks that require rigorous logic, such as mathematical derivation and code debugging. For simple question answering, it is unnecessary.

    2. Function Calling and Structured Output

    Function calling lets a model output a structured request instead of a natural language answer. The program reads the request, runs the corresponding operation, and returns the result to the model. The reliability of this process depends on two factors: whether the tool description is clear, and whether the parameters the model outputs strictly match the agreed format.

    The following is an example tool description for querying order status:

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

    The more specific the tool description, the less likely the model is to misuse the tool. Descriptions should include the meaning of each parameter, its valid value range, and typical use cases.

    3. Multimodal Input and Context Length

    Multimodal capability expands the range of what an agent can perceive. For example, a model can read a device screenshot to judge the state of an interface, or analyze a recording of an operation. Multimodal support varies widely across open-source models. Some support images only, while others also support video or audio. Choose a model based on the input types you actually need.

    Context length determines how much material a model can process at once. Depending on the model size, context windows may range from 128K to 256K tokens. A longer context requires more memory and compute. Therefore, keep inputs concise first, and expand the context window only when necessary.

    3. Choosing a Model Size by Compute Tier

    Models in the same family usually come in several sizes, covering compute environments from mobile devices to workstations. When choosing a size, consider the following three categories.

    Size Category Typical Deployment Suitable Use Cases Main Trade-offs
    Small-parameter on-device versions Phones, embedded devices, laptops Offline instruction parsing, local assistants, low-latency responses Limited complex reasoning capability
    Mixture-of-Experts (MoE) versions A single high-memory GPU or a small server General tasks that balance throughput and quality Large total parameter count; memory usage is higher than the active parameter count
    Dense large-model versions Workstations or multi-GPU servers Quality-first reasoning, code generation, complex planning Higher latency and hardware cost

    A Mixture-of-Experts model activates only some of its expert networks during each inference pass. As a result, its compute cost is lower than that of a dense model with the same total parameter count. However, all of its parameters must still be loaded into memory. When planning a deployment, consider both the memory needed to load the model and the number of tokens it can generate per second.

    A practical selection process looks like this:

    1. Determine the latency, privacy, and cost requirements of your business;
    2. Build a small evaluation set from your own data, and run it on two or three candidate sizes;
    3. If a smaller size meets your accuracy requirements, choose it;
    4. If complex reasoning is required, consider a larger size and evaluate the hardware investment.

    4. Engineering Design for Agent Workflows

    A reliable agent loop usually includes the following elements: task input, tool registration, model inference, tool execution, result write-back, and termination checks. The following is a simplified loop:

    1. def run_agent(task, model, tools, max_steps=8):
    2. messages = [{"role": "user", "content": task}]
    3. for _ in range(max_steps):
    4. reply = model.generate(messages, tools=tools)
    5. # The model did not request a tool call, so treat this as the final answer
    6. if reply.tool_call is None:
    7. return reply.text
    8. # Run the tool and write the result back into the conversation context
    9. result = execute_tool(reply.tool_call, tools)
    10. messages.append({"role": "tool", "content": result})
    11. raise RuntimeError("Maximum steps reached without completing the task; aborting")

    Keep the following points in mind when designing the loop:

    • Set a maximum number of steps to prevent the model from getting stuck in repeated tool calls.
    • Truncate tool results to a fixed length so the context does not grow too quickly.
    • Add a human confirmation step for operations with side effects, such as refunds, deletions, or sending messages.
    • Log the input, output, and duration of each step to make troubleshooting easier.

    5. Ensuring Reliable Structured Output

    Even with clear prompts, a model occasionally produces malformed output. In engineering practice, teams often use a three-step strategy: constrain, validate, and retry. Constraining means providing the target structure in the request. Validating means checking field types and required fields against JSON Schema rules. Retrying means returning the error message to the model when validation fails, so the model can correct its output.

    1. import json
    2. def parse_structured_output(model, prompt, schema, max_retries=2):
    3. last_error = None
    4. for _ in range(max_retries + 1):
    5. raw = model.generate(prompt, response_format=schema)
    6. try:
    7. data = json.loads(raw)
    8. validate_against_schema(data, schema)
    9. return data
    10. except (json.JSONDecodeError, ValueError) as e:
    11. last_error = str(e)
    12. prompt = f"{prompt}\nPrevious output was invalid: {last_error}. Please fix it and output again."
    13. raise ValueError(f"Structured output failed validation after multiple attempts: {last_error}")

    Limit the number of retries, because latency and cost rise quickly with each attempt. Two retries are usually enough. For critical business workflows, also track the validation failure rate as a monitoring metric for model and prompt quality.

    6. Deployment and Resource Planning

    1. Estimating Memory Requirements

    You can estimate the memory used by model weights with the following rule of thumb:

    Weight memory ≈ parameter count × bytes per parameter

    For a 30B-parameter model, 8-bit quantization uses about 1 byte per parameter, so the weights need roughly 30 GB. With 4-bit quantization, each parameter takes about 0.5 bytes, so the weights need roughly 15 GB. This estimate excludes the KV cache, activations, and runtime overhead during inference. Actual memory usage is usually higher.

    2. KV Cache and Context Length

    The KV cache grows linearly with context length and the number of concurrent requests. In long-context scenarios, the cache can use more memory than the model weights. Plan memory based on the longest expected input and the expected concurrency, not just the size of the model weights.

    3. Quantization and Accuracy Trade-offs

    Quantization can substantially reduce memory requirements, but it introduces some accuracy loss. Before deciding on a deployment setup, compare task success rates across quantization options using your own evaluation set. For tool calling and structured output tasks, pay particular attention to whether the format error rate increases after quantization.

    7. Licensing and Compliance

    Permissive open-source licenses generally allow commercial use, modification, and redistribution. However, check the specific terms of each license. Common compliance requirements include retaining the original copyright notice, including the license text with the product, and noting changes in modified files.

    Teams should also consider the following:

    • Whether training data and fine-tuning data carry copyright or privacy risks;
    • Whether model outputs will support high-risk decisions, such as those in healthcare, finance, or legal settings, which require additional human review;
    • Whether offering a service to the public requires registration or assessment under applicable local regulations.

    8. Evaluating Models with Your Own Metrics

    Public leaderboards can serve as an initial reference, but they match specific business scenarios only to a limited degree. Teams should build their own evaluation set around the following metrics:

    1. Task success rate: whether the agent ultimately achieves its goal;
    2. Tool-calling accuracy: whether parameter names, types, and values are correct;
    3. Structured output pass rate: the share of outputs that pass validation on the first generation;
    4. End-to-end latency: the time from receiving a request to returning a result;
    5. Cost per task: including inference compute, storage, and human review costs.

    The evaluation set should