Long Context and Agentic Programming with Mixture of Experts LLMs

    This article explores the engineering practices of combining Mixture of Experts (MoE) large language models with long context capabilities for agentic programming. It covers the underlying mechanisms of MoE, bottlenecks and optimization strategies for long context processing, capability requirements for AI agents, API integration, custom evaluation systems, and practical engineering recommendations for deployment.

    1. Why Focus on Mixture of Experts and Long Context?

    Large language model capabilities are continually improving, but inference costs have become the primary constraint for large-scale applications. The Mixture of Experts (MoE) architecture allows each input to activate only a subset of the model’s parameters. This enables the total parameter count to scale further while keeping the per-step computation within an acceptable range.

    Long context capability determines whether a model can process an entire code repository, lengthy technical documentation, or multi-turn tool call logs in a single pass. Agentic programming applications rely on both capabilities: the model must read extensive code, plan multi-step actions, and maintain goal alignment over a long history. The combination of MoE and long context has become a critical trend in current LLM engineering.

    2. Mechanism of the Mixture of Experts Architecture

    An MoE layer generally consists of two parts. A router calculates scores for each expert based on the hidden representation of each token and selects the top-scoring experts. The selected experts perform their calculations independently, and the results are combined via a weighted sum based on the routing weights. Unselected experts do not participate in the computation.

    The following code demonstrates the basic logic of top-k routing, for illustrative purposes only:

    1. import math
    2. def softmax(xs):
    3. m = max(xs)
    4. exps = [math.exp(x - m) for x in xs]
    5. total = sum(exps)
    6. return [e / total for e in exps]
    7. def route(token_vec, gate_weights, top_k=2):
    8. """Each element in gate_weights corresponds to a routing weight vector for an expert."""
    9. logits = [sum(w * x for w, x in zip(gw, token_vec)) for gw in gate_weights]
    10. probs = softmax(logits)
    11. ranked = sorted(range(len(probs)), key=lambda i: probs[i], reverse=True)[:top_k]
    12. norm = sum(probs[i] for i in ranked)
    13. return [(i, probs[i] / norm) for i in ranked]

    Let’s illustrate the change in computation with a hypothetical example. If a layer contains 64 experts and activates 2 experts per token, the expert computation per token is approximately 2/64 (about 3.1%) of the total expert computation. These numbers are for demonstrating proportions only and do not represent any specific model.

    2.1 Total Parameters vs. Active Parameters

    MoE models require distinguishing between two types of parameter counts. Total parameters determine the model’s storage size and knowledge capacity, while active parameters determine the computation for a single inference step. During deployment, memory must accommodate all parameters, whereas per-token latency is primarily affected by active parameters. Therefore, both metrics must be evaluated when assessing MoE model costs.

    2.2 Common Issues in Training and Inference

    Routing training is prone to load imbalance, where a few experts are frequently selected while others barely learn. Common solutions include adding a load balancing term to the loss function or limiting the number of tokens each expert can receive per batch.

    During inference, experts are distributed across different devices. Tokens must be dispatched and aggregated across devices, and communication overhead can impact throughput. Engineering solutions typically employ expert parallelism, batch scheduling, and communication-computation overlap to mitigate this overhead.

    3. Main Bottlenecks of Long Context and Mitigation Strategies

    3.1 Computation and Memory Pressure

    The computation of standard self-attention grows quadratically with the sequence length n. Expanding the sequence from 10,000 to 1,000,000 theoretically increases attention computation by about 10,000 times. Additionally, during inference, the model needs to cache the key-value vectors of historical tokens (KV cache). The cache size can be estimated using the following formula:

    KV cache bytes ≈ 2 × layers × KV heads × head dimension × sequence length × bytes per element

    Assume an example configuration: 60 layers, 8 KV heads, head dimension 128, sequence length 1,000,000, and 2 bytes per element (FP16). Substituting into the formula yields approximately 246 GB. This is just the cache for a single request, indicating that long context services must fundamentally address the cache structure itself.

    3.2 Token-Level Compression

    One approach is to reduce the number of cached entries. By merging the KV representations of several adjacent tokens into a single compressed unit, the number of cache entries is reduced to a fraction of the original. A higher compression ratio lowers memory usage but increases the risk of information loss. Engineering requires a careful balance between compression ratio and task accuracy.

    3.3 Sparse Attention

    The core idea of sparse attention is that each query only attends to a subset of historical positions rather than all of them. Common combinations include local sliding windows, a few global anchors, and key positions selected by a lightweight indexer.

    The following code demonstrates the process of selecting top-k positions based on relevance scores:

    1. def select_topk_positions(scores, k):
    2. """scores[i] represents the estimated relevance of the current query to the i-th historical position."""
    3. ranked = sorted(range(len(scores)), key=lambda i: scores[i], reverse=True)
    4. return sorted(ranked[:k])

    The risk of sparse selection is missing critical information. When evaluating, you should test both retrieval-type tasks (e.g., locating specific information in a long text) and real-world business tasks (e.g., cross-file code modifications) to avoid relying on a single metric.

    4. Capability Requirements for Agentic Programming

    Agentic programming typically operates in a loop: the model plans steps, calls tools (read files, run tests, search code), observes results, and revises the plan. The following code demonstrates the basic structure of this loop:

    1. def agent_loop(task, model, tools, max_steps=20):
    2. history = [{"role": "user", "content": task}]
    3. for _ in range(max_steps):
    4. reply = model.chat(history, tools=tools)
    5. history.append(reply)
    6. if not reply.get("tool_calls"):
    7. return reply["content"]
    8. for call in reply["tool_calls"]:
    9. result = tools[call["name"]](**call["arguments"])
    10. history.append({
    11. "role": "tool",
    12. "name": call["name"],
    13. "content": str(result),
    14. })
    15. raise RuntimeError("Exceeded maximum steps, task not completed")

    There are four main requirements for the model:

    1. Stable tool call formatting, with parameters that pass structural validation.
    2. Retention of the original goal even with a long history, without going off-topic due to early information loss.
    3. Ability to identify the cause of tool errors and switch to alternative solutions.
    4. Adherence to permission boundaries, not executing write operations beyond the task scope.

    On the engineering side, the loop should be constrained by a maximum number of steps, per-step timeouts, and write operation confirmation mechanisms. These limits prevent accidents more effectively than model capabilities alone.

    5. API Integration and Compatibility Design

    Most LLM services use a message-list-based conversational interface, where the request body contains the model name and a message array, and the response returns the generated content. Below is an example using the standard library to make a request. Interface fields should follow the service provider’s official documentation:

    1. import json
    2. import os
    3. import urllib.request
    4. def chat(messages, model_name):
    5. url = os.environ["LLM_ENDPOINT"]
    6. api_key = os.environ["LLM_API_KEY"]
    7. body = json.dumps({"model": model_name, "messages": messages}).encode("utf-8")
    8. req = urllib.request.Request(
    9. url,
    10. data=body,
    11. headers={
    12. "Content-Type": "application/json",
    13. "Authorization": f"Bearer {api_key}",
    14. },
    15. method="POST",
    16. )
    17. with urllib.request.urlopen(req, timeout=120) as resp:
    18. data = json.loads(resp.read().decode("utf-8"))
    19. return data["choices"][0]["message"]["content"]

    Three recommendations for integration:

    • Inject keys and endpoints via environment variables or secret management services; do not hardcode them in the source code or log them.
    • Add an adapter layer between your business code and the model so that switching models only requires configuration changes.
    • Set timeouts, retry limits, and rate-limiting policies for requests, and apply exponential backoff for 429 and 5xx errors.

    6. Building a Custom Evaluation System

    Public benchmarks reflect general capabilities but cannot replace evaluations tailored to your specific business. It is recommended to sample from real tickets, historical code changes, and production logs to build an internal evaluation set, tracking at least the following metrics:

    Metric Meaning Collection Method
    Task Pass Rate Proportion of results that meet acceptance criteria Run tests or manual spot checks
    Tool Call Legality Rate Proportion of calls where format and parameters pass validation Parse call records from logs
    Average Steps Average number of loops required to complete a task Count execution rounds in agent_loop
    Cost per Task Input and output token costs consumed per task Record token usage per request
    First Token Latency Time from sending the request to receiving the first token Time on the client side

    The evaluation set should be updated regularly, and a portion of hold-out samples that have never been used for tuning should be retained to prevent metric overfitting.

    7. Engineering Deployment Recommendations

    Tiered Routing. Assign simple tasks like Q&A and format conversion to small models, and complex planning and cross-file modifications to large models. After tiering, both average cost and latency will decrease.

    Control Context Size. Just because the context window can hold more content does not mean it should all be included. For large code repositories, use retrieval to filter relevant files first, then place the key snippets and summaries into the context. This is usually more stable and cost-effective than feeding the entire repository.

    Protect Data Security. Content sent to the model should be desensitized first, removing keys, personal information, and customer data. Tool permissions should follow the principle of least privilege, allowing the agent to access only the directories and interfaces required for the task.

    Design Fallback Paths. When a service times out or hits rate limits, the system should switch to a backup model or route to a manual processing queue instead of failing outright.

    Monitor Cost and Quality. Continuously log token usage, task pass rates, and manual correction rates post-launch. When a metric changes significantly, first troubleshoot the prompts, tool definitions, and context construction before deciding whether to switch models.