Efficiency and Implementation of Agentic LLMs: A Guide to Mixture of Experts Architecture

    This article explores the practical implementation of agentic Large Language Models (LLMs) using the Mixture of Experts (MoE) architecture to balance capability, speed, and cost. It covers the core principles of MoE, including sparse activation and gating networks, and breaks down essential capabilities like logical reasoning, code generation, and tool calling. Furthermore, it provides evaluation methods for latency and cost, a practical use case for formal document generation, and best practices for model selection, risk management, and deployment.

    1. Background: From Answering Questions to Completing Tasks

    Early Large Language Models (LLMs) primarily handled Q&A and text completion. As applications deepened, business stakeholders raised more specific requirements: models needed to understand complex instructions, generate executable code, and call external systems to perform queries, formatting, and validations. This means models must possess not only knowledge reserves but also the capabilities for multi-step reasoning, structured output, and tool calling.

    As capabilities improved, cost issues emerged. With larger parameter scales, every inference requires computing all parameters, leading to increased VRAM usage and response latency. Balancing capability, speed, and cost is an unavoidable challenge in engineering implementation. The Mixture of Experts (MoE) architecture is a common solution designed to address this contradiction.

    2. Basic Principles of the Mixture of Experts Architecture

    2.1 Dense Models vs. Sparse Activation

    A Dense Model activates all its parameters during the forward pass for every token. In contrast, a Mixture of Experts model splits the feedforward network into multiple “expert” sub-networks, with each token processed by only a few selected experts. The number of activated parameters is far less than the total parameters of the model, an approach known as sparse activation.

    Sparse activation brings two direct benefits. First, the computation for a single inference correlates with the active parameters rather than the total parameters. Second, the model can be scaled up in total parameters to accommodate more knowledge without linearly increasing inference overhead.

    2.2 Gating Network and Expert Routing

    The Gating Network is responsible for selecting experts for each token. The most common approach is Top-k routing: it calculates scores for all experts, selects the top k highest-scoring experts, and normalizes these k scores (usually via softmax) to serve as weighted coefficients for each expert’s output.

    The following example uses NumPy to demonstrate a simplified Top-k routing and weighted merging process to help understand the data flow:

    1. import numpy as np
    2. def top_k_gating(x, w_gate, k=2):
    3. """Calculate expert selection and weights for a single token."""
    4. logits = x @ w_gate # Shape: [num_experts]
    5. topk_idx = np.argsort(logits)[-k:] # Top k highest scoring experts
    6. topk_logits = logits[topk_idx]
    7. weights = np.exp(topk_logits - topk_logits.max())
    8. weights /= weights.sum() # Softmax normalization
    9. return topk_idx, weights
    10. def moe_forward(x, experts, w_gate, k=2):
    11. """Weighted merge of selected experts' outputs based on gating results."""
    12. idx, weights = top_k_gating(x, w_gate, k)
    13. out = np.zeros_like(x)
    14. for i, w in zip(idx, weights):
    15. out += w * experts[i](x)
    16. return out

    In actual systems, load balancing must also be addressed. If the gating network persistently favors a few experts, those experts become bottlenecks while others remain idle. During training, an auxiliary loss is typically added to encourage experts to receive a roughly uniform distribution of tokens.

    2.3 Efficiency vs. Quality

    Sparse activation does not inherently guarantee better or worse quality. It changes how parameters are utilized. Whether the division of labor among experts is reasonable, whether routing is stable, and whether training data covers various tasks will all affect the final outcome. Therefore, evaluating an MoE model should not rely solely on total parameters; one must also consider active parameters, performance on target tasks, and actual inference latency.

    3. Capability Breakdown: Reasoning, Coding, and Tool Calling

    LLMs oriented towards real-world business typically need to possess three types of capabilities simultaneously.

    The first is logical reasoning, including mathematical calculations, conditional logic, and multi-step planning. When evaluating, focus on whether the model can produce traceable reasoning steps and verifiable conclusions.

    The second is code generation. The code output by the model needs to pass compilation or unit tests, not just exhibit syntactic similarity. In engineering practice, model outputs are often directly integrated into testing pipelines, with pass rates used to measure effectiveness.

    The third is tool calling. Based on user intent, the model outputs structured function call requests, which are executed by external programs before the results are fed back to the model. This mechanism typically relies on JSON Schema to describe parameters. Below is a generic tool definition example for searching document templates:

    1. {
    2. "name": "search_document_template",
    3. "description": "Retrieve formal document templates by type and scenario",
    4. "parameters": {
    5. "type": "object",
    6. "properties": {
    7. "doc_type": {"type": "string", "description": "Document type, such as notice, request, report"},
    8. "scene": {"type": "string", "description": "Brief description of the usage scenario"}
    9. },
    10. "required": ["doc_type"]
    11. }
    12. }

    The key to tool calling lies in parameter validation. Parameters output by the model should first undergo type and range checks before entering the actual system. Operations involving writing or sending should retain a manual confirmation step.

    4. Methods for Evaluating Speed and Cost

    When selecting a model, several metrics are commonly used to measure service performance.

    Time to First Token (TTFT): The time from sending a request to receiving the first output token, which directly impacts the interactive experience.

    Tokens per Second (TPS): The number of tokens generated per unit of time, determining the wait time for long-text outputs.

    Cost per Request: Typically determined by the number of input tokens, output tokens, and unit prices. Output tokens are often more expensive than input tokens, so the cost of long-form generation must be calculated separately.

    The cost estimation can be expressed with a simple formula:

    Cost per Request = Input Tokens × Input Price + Output Tokens × Output Price

    Pricing and billing rules vary significantly across providers. During actual selection, refer to the official documentation and conduct stress tests based on your own business request distribution.

    The following script demonstrates how to measure latency and throughput, where generate is the inference function to be tested, injected by the caller:

    1. import time
    2. def benchmark(generate, prompts, repeat=3):
    3. results = []
    4. for prompt in prompts:
    5. for _ in range(repeat):
    6. start = time.perf_counter()
    7. tokens = generate(prompt) # Returns a list of output tokens
    8. elapsed = time.perf_counter() - start
    9. results.append({
    10. "latency_s": elapsed,
    11. "tokens": len(tokens),
    12. "tps": len(tokens) / elapsed if elapsed > 0 else 0.0,
    13. })
    14. avg_tps = sum(r["tps"] for r in results) / len(results)
    15. return results, avg_tps

    When measuring, fix the input length distribution and record concurrency, network environment, and warm-up conditions; otherwise, data from different batches cannot be compared horizontally.

    5. Scenario Practice: Formal Document Generation

    Formal document generation has strict requirements for format, terminology, and factual accuracy, making it a suitable starting point for LLM-assisted scenarios. A reliable workflow typically includes the following steps.

    Step 1: Structured Requirements. Decompose user input into document type, issuing entity, recipient, subject, key data, and deadline requirements. Structured information facilitates subsequent template matching and validation.

    Step 2: Template Constraints. Embed internal formatting standards into the system prompt, specifying title hierarchy, signature formats, date conventions, and terminology. The model is only responsible for filling in content; the template controls the format.

    Step 3: Fact-Checking. Numbers, dates, and policy clauses generated by the model need to be compared against source materials. Rule scripts can be designed to extract key elements for item-by-item verification.

    Step 4: Human Review. The final responsibility for formal documents is clearly defined and must be reviewed and signed off by the handler. Model output should be treated as a draft.

    Below is an example of prompt assembly used to convert structured requirements into generation instructions:

    1. def build_doc_prompt(doc_type, issuer, recipient, subject, facts, deadline=None):
    2. lines = [
    3. "You are a writing assistant familiar with formal document standards.",
    4. f"Document type: {doc_type}",
    5. f"Issuing entity: {issuer}",
    6. f"Recipient: {recipient}",
    7. f"Subject: {subject}",
    8. "Based on the following materials (do not add facts outside of these materials):",
    9. ]
    10. lines += [f"- {item}" for item in facts]
    11. if deadline:
    12. lines.append(f"Deadline: {deadline}")
    13. lines.append("Please output in standard formal document format, and mark the content that requires manual verification at the end.")
    14. return "\n".join(lines)

    Requiring the model to “not add facts outside of the materials” and asking it to flag content for verification can significantly reduce the risk of fabricated information entering the final draft.

    6. Selection and Evaluation Advice

    When evaluating LLMs, it is recommended to start from business samples rather than relying solely on generic leaderboards. Generic leaderboards have broad coverage but limited relevance to specific tasks.

    When building an evaluation set, organize samples along the following dimensions:

    • Task type: Q&A, rewriting, code, structured extraction, tool calling.
    • Difficulty layering: Separate single-step tasks from multi-step tasks.
    • Failure modes: Record the frequency of hallucinations, format errors, refusals, and overly long outputs.

    Each evaluation should fix the random seed, prompt version, and scoring criteria, and retain the raw outputs. Scoring can combine automated validation (e.g., code tests, JSON parsing) with manual spot-checks, complementing each other.

    On the cost side, it is advisable to compare “cost per request” with “cost per valid result.” The latter equals the total cost divided by the number of results passing manual acceptance. A solution with a lower unit price but a high rework rate may not ultimately be cheaper.

    7. Risks and Boundaries

    Deploying LLMs in production involves several risks that require proactive mitigation.

    Hallucination Risk. Models may generate content that seems plausible but is factually incorrect. This should be controlled through Retrieval-Augmented Generation (RAG), fact-checking, and human review.

    Data Compliance. If inputs contain personal information, classified data, or internal data, they should be desensitized first. Ensure that the data processing terms of the service used meet compliance requirements.

    Access Control. Tool calling should follow the principle of least privilege. The model should only access the APIs necessary to complete the task, and write operations require explicit confirmation.

    Traceability. Retain prompt versions, model versions, inputs, outputs, and review records to facilitate problem post-mortems and accountability.

    8. Conclusion

    Through sparse activation, the Mixture of Experts architecture provides a viable compromise between capability and cost for large models. Whether it suits a specific scenario depends on task characteristics, quality requirements, and acceptable latency and cost. Building evaluation on real business samples and establishing validation and review steps for generated results are the foundations for translating model capabilities into stable productivity.