Engineering Practices for LLM Long Context and Agent Services
This article explores engineering strategies for deploying large language models (LLMs) with long context windows and AI agents. It covers transitioning from model capability to service stability, managing traffic spikes through request governance, optimizing long context processing, evaluating attention mechanisms, and building secure agent hosting architectures.
1. From Model Capability to Service Capability
The improvement of large parameter model capabilities is no longer the only issue. When parameter scales enter the trillion level, completing model training is just the starting point. What truly determines the user experience is whether the inference service can stably handle requests. A highly capable model that frequently experiences queuing, timeouts, or interruptions provides limited value to the business. Therefore, technical teams need to consider “what the model can do” and “how much traffic the service can handle” within the same evaluation framework.
From an engineering perspective, three questions usually need to be answered: What is the computational cost of a single request? How is capacity guaranteed during peak periods? And how is service continuity maintained during model version updates? The following sections will elaborate on these one by one.
2. Compute Elasticity and Request Governance
A sharp increase in request volume over a short period is a common scenario in LLM services, often caused by new feature releases, external promotions, or batch task integrations. Without a governance mechanism, the queue will rapidly grow, first-token latency will increase, and ultimately lead to client timeout retries, further amplifying the load.
Common methods include:
- Admission Control: Allocate quotas based on user level, API type, or tenant. Return explicit rate-limiting information for excess requests.
- Tiered Queuing: Schedule interactive requests and offline batch processing requests separately to prevent long tasks from crowding out online responses.
- Temporary Admission Tightening: When capacity is insufficient, pause new users or open spots to prioritize service quality for existing users. This is a business decision that requires setting trigger thresholds and recovery conditions in advance.
- Elastic Scaling: Utilize container platforms or resource scheduling systems to scale inference instances based on load, while reserving cold start time for model loading.
The token bucket is the most basic rate-limiting algorithm. A general example is provided below:
import timeclass TokenBucket:def __init__(self, rate: float, capacity: int):self.rate = rate # Number of tokens added per secondself.capacity = capacity # Maximum bucket capacityself.tokens = capacityself.last = time.monotonic()def allow(self) -> bool:now = time.monotonic()self.tokens = min(self.capacity, self.tokens + (now - self.last) * self.rate)self.last = nowif self.tokens >= 1:self.tokens -= 1return Truereturn False
This implementation is only suitable for a single process. In multi-instance deployments, the token state needs to be placed in shared storage, and concurrency issues arising from concurrent updates must be handled.
3. Design Points for Long Context Processing
As the context window lengthens, service costs are mainly reflected in two aspects. The first is memory usage. The Key-Value (KV) cache in attention computation grows with sequence length, which is especially noticeable when there are many concurrent requests. The second is first-token latency. The longer the input, the more time the prefill phase takes.
Therefore, long context does not mean putting all materials into the input at once. In practice, strategies can be selected based on the task:
- Direct Input: Suitable for tasks where the input length is within the window and the context is closely related, such as reviewing an entire contract.
- Chunking and Retrieval: Split the document, recall relevant fragments through vector or keyword retrieval, and only feed the relevant content to the model. Suitable for knowledge base Q&A.
- Hierarchical Summarization: First generate summaries for a long document chapter by chapter, and then make an overall judgment based on the summaries. Suitable for report summarization tasks, but the summarization phase may lose details, requiring spot checks.
When chunking, semantic boundaries should be preserved to avoid cutting off a sentence or a table. A simple approach is as follows:
def chunk_text(text: str, max_chars: int = 1500, overlap: int = 200):chunks, start = [], 0while start < len(text):end = min(start + max_chars, len(text))chunks.append(text[start:end])if end == len(text):breakstart = end - overlapreturn chunks
The overlap area can reduce the risk of key information falling exactly on the split point. In real projects, you should prioritize splitting by natural boundaries like paragraphs and headings, and only perform character-level splitting for overly long paragraphs.
4. Trade-offs in Attention Mechanisms
The computational cost of standard full attention grows quadratically with the sequence length. To reduce the computation and memory overhead of long sequences, the industry has proposed various improvement directions, commonly including the following categories:
- Grouped-Query Attention (GQA): Allows multiple query heads to share key-value heads, thereby reducing the cache size.
- Sliding Window Attention: Each position only attends to a nearby window, reducing computation. Long-distance dependencies need to be supplemented by other layers or mechanisms.
- Linear or Approximate Attention: Reduces complexity to near-linear through kernel functions or low-rank approximation, but may experience quality degradation in precise retrieval tasks.
- Sparse Attention: Only computes attention between certain position pairs, requiring the design of a reliable position selection strategy.
There is no universally optimal solution when selecting a model. The evaluation should revolve around three dimensions: the target task’s reliance on long-range precise retrieval, the actual throughput on the target hardware, and the quality changes on your own evaluation set. Looking only at theoretical complexity without actual testing can easily lead to conclusions inconsistent with online performance.
5. Architectural Points for Agent Hosting and Execution
The difference between an AI agent and standard Q&A is that the model autonomously plans multi-step operations and calls external tools. This introduces a larger attack surface. Incorrect tool calls may modify data, cyclic reasoning may exhaust quotas, and malicious input may induce privilege escalation.
When hosting and running agents, it is recommended to follow these principles:
- Least Privilege: Each agent should only access the tools and data required for its task. Credentials and permissions should be managed separately.
- Step and Time Limits: Set a maximum number of execution steps and a single-step timeout to prevent infinite loops.
- Human Confirmation: Irreversible operations such as deletion, sending, and payment must be explicitly authorized.
- Sandbox Isolation: Code execution and file operations should be performed in a restricted environment, with network egress opened via a whitelist.
- Full-Chain Audit: Record every model output, tool call parameters, and return results for post-mortem analysis.
Below is an example of a loop structure with a step limit and tool whitelist:
ALLOWED_TOOLS = {"search_docs", "read_file"}MAX_STEPS = 10def run_agent(model, task, tools):history = [{"role": "user", "content": task}]for _ in range(MAX_STEPS):action = model.next_action(history)if action.type == "final":return action.contentif action.tool not in ALLOWED_TOOLS:history.append({"role": "system", "content": "Tool not in allowed list"})continueresult = tools[action.tool](**action.args)history.append({"role": "tool", "content": str(result)})raise RuntimeError("Maximum steps exceeded, task terminated")
The tool parameters in the example come from the model output. In actual use, type and value validation should be performed according to each tool’s parameter specifications before calling, rather than passing them directly.
6. Checklist for Model Weight Release
When model weights are released in an open format, the technical team’s focus shifts from online services to distribution and usage security. This mainly includes the following four items:
- Licensing and terms of use: Clearly define permitted use cases, commercial restrictions, and redistribution requirements.
