Integrating LLMs via a Unified Gateway: Scheduling and Compression Practices
Integrating large language model (LLM) services into applications often presents challenges such as inconsistent API protocols, complex credential management, context window limits, and fragmented observability. This article explores how to address these issues using a proxy gateway. It covers the overall architecture, protocol adaptation, multi-credential pool scheduling, context compression for long conversations, streaming output handling, and best practices for secure deployment and operations.
1. Background and Challenges
When integrating LLM services into applications, developers often encounter the following four categories of problems.
1. Inconsistent API Protocols. Different service providers have varying request bodies, response bodies, and streaming event formats. Field names, message structures, and the description methods for tool calls can all differ. Every time a new model is integrated, the business logic must add another layer of adaptation, leading to high maintenance costs.
2. Complex Credential and Quota Management. A team often holds multiple access credentials. A single credential might face rate limiting, expiration, or temporary failures. If each business module independently rotates credentials, code for retries, backoff, and concurrency control becomes scattered, making troubleshooting difficult.
3. Long Conversations Exceeding Context Windows. Historical messages accumulated over multiple rounds of conversation quickly exceed a model’s token limit. Direct truncation loses key information, while retaining everything leads to request failures or increased costs.
4. Lack of Unified Observability. Request volumes, latency, error rates, and credential health are scattered across services, making it difficult to quickly pinpoint issues when they occur.
A proxy gateway can centralize the handling of these problems. The upper-layer application faces only a unified interface, while the gateway is responsible for adapting protocols, scheduling credentials, compressing context, and recording operational data.
2. Overall Architecture
A practical gateway typically contains the following layers:
Client -> Auth & Rate Limiting -> Protocol Adaptation -> Context Management -> Account Scheduling -> Upstream Model Service↑Health Check / Metrics Collection / Request Logs -> Admin Panel
The responsibilities of each layer are as follows:
- Auth & Rate Limiting: Validates the API Keys issued by the gateway itself and limits request rates per Key.
- Protocol Adaptation: Converts external requests into a unified internal structure, and then translates upstream responses back into the format expected by the client.
- Context Management: Estimates token usage and compresses historical messages when necessary.
- Account Scheduling: Selects the most appropriate account from the credential pool and switches on failure.
- Admin Panel: Used for managing credentials, viewing metrics, and checking logs.
The benefit of layering is that each layer can be tested and replaced independently. For example, changing the scheduling strategy does not require modifying the protocol adaptation code.
3. Protocol Adaptation: Unified Internal Message Structure
The core of protocol adaptation is defining an internal message model. All external formats are first mapped to it, and then it outputs to the upstream. This confines format differences to the boundary layer.
The following example demonstrates how to normalize messages. It handles both string content and multi-part content, ignoring non-text segments.
from dataclasses import dataclass, fieldfrom typing import Any@dataclassclass UnifiedMessage:role: strcontent: strtool_calls: list[dict[str, Any]] = field(default_factory=list)def normalize_messages(raw_messages: list[dict]) -> list[UnifiedMessage]:"""Normalize messages from external requests into an internal structure."""result = []for msg in raw_messages:role = msg.get("role", "user")content = msg.get("content", "")if isinstance(content, list):# For multi-part content, keep only the text partscontent = "".join(part.get("text", "")for part in contentif part.get("type") == "text")result.append(UnifiedMessage(role=role,content=content,tool_calls=msg.get("tool_calls", []),))return result
In actual implementation, note the following:
- Be tolerant of unrecognized fields to avoid rejecting the entire request because of an unknown parameter.
- Explicitly validate required fields and return an error structure consistent with the client protocol to help the caller troubleshoot.
- The response side also requires mapping, including the finish reason, usage statistics, and error codes.
4. Multi-Credential Pool Scheduling
4.1 Health Score
Credential pool scheduling relies on an explainable health metric. A common approach is to deduct points for each failure, with different deduction ratios for timeouts or rate limits. After a failure, the score gradually recovers over time. This avoids faulty accounts while allowing them to be reused after a cooldown period.
The following implementation uses linear decay: the more failures, the lower the health score. Once the cooldown period ends, the failure count gradually resets to zero.
import timefrom dataclasses import dataclassCOOLDOWN_SECONDS = 300@dataclassclass Account:name: strmax_concurrency: intinflight: int = 0failures: int = 0last_failure: float = 0.0def health(self) -> float:if self.failures == 0:return 1.0elapsed = time.time() - self.last_failureremaining = self.failures * max(0.0, 1 - elapsed / COOLDOWN_SECONDS)return max(0.0, 1.0 - remaining * 0.25)def record_failure(self) -> None:self.failures += 1self.last_failure = time.time()def record_success(self) -> None:self.failures = 0
4.2 Selection Strategy
When selecting an account, you must consider both the health score and the current load. Multiplying them to get a weight, followed by a weighted random selection, prevents all requests from concentrating on a single account.
import randomdef pick_account(pool: list[Account]) -> Account | None:candidates = [a for a in poolif a.inflight < a.max_concurrency and a.health() > 0.1]if not candidates:return Noneweights = [a.health() * (1 - a.inflight / a.max_concurrency)for a in candidates]return random.choices(candidates, weights=weights, k=1)[0]
If the candidate list is empty, a clear service unavailable error should be returned instead of waiting indefinitely.
4.3 Failover Boundaries
The prerequisite for switching accounts to retry is that the request has not yet produced visible output to the client. For non-streaming requests, a failed request can be retried directly with another account. For streaming requests, if partial content has already been sent to the client, seamless switching is impossible without causing duplicate or scrambled output. The safer approach here is to interrupt the current output and return a clear error event, letting the client decide whether to retry.
Retry limits should also be enforced, using exponential backoff to avoid amplifying traffic during upstream large-scale outages.
5. Context Compression for Long Conversations
5.1 Trigger Conditions
Context compression should be completed before the request is sent. The typical workflow is as follows:
- Estimate the total tokens of the current messages. This can be done using a character count conversion or by calling the specific model’s tokenizer (higher accuracy, but higher overhead).
- If the total is below the threshold, send as is. The threshold should reserve space for the model’s expected output.
- If it exceeds the threshold, keep the system messages and the most recent conversation rounds, and pass older messages to a summarization function.
- Insert the summary as an independent message into the history, then send the request.
5.2 Implementation Example
def compress_history(messages, count_tokens, summarize,max_tokens=24000, keep_recent=6):total = sum(count_tokens(m["content"]) for m in messages)if total <= max_tokens:return messagessystem = [m for m in messages if m["role"] == "system"]rest = [m for m in messages if m["role"] != "system"]old, recent = rest[:-keep_recent], rest[-keep_recent:]if not old:return messagessummary_text = summarize(old)summary_msg = {"role": "user","content": f"[Conversation Summary]\n{summary_text}",}return system + [summary_msg] + recent
In practice, pay attention to a few details:
- Split Boundaries: Do not separate a tool call request from its corresponding tool result. Otherwise, the upstream will throw an error due to an incomplete message structure.
- Summary Caching: Hash the old message content so that identical historical segments are summarized only once. This allows subsequent requests in a multi-turn conversation to reuse existing results.
- Summary Quality: Summaries should retain facts, constraints, unfinished tasks, and key decisions, discarding pleasantries and repetitive content.
6. Streaming Output and Tool Calling
6.1 Server-Sent Events (SSE)
Streaming output typically uses Server-Sent Events (SSE). Each event starts with data: and ends with an empty line. The gateway must translate upstream incremental content chunk-by-chunk into events recognizable by the client.
import jsondef sse_event(payload: dict) -> bytes:text = f"data: {json.dumps(payload, ensure_ascii=False)}\n\n"return text.encode("utf-8")
When the streaming response ends, a clear end marker should be sent along with the finish reason, helping the client distinguish between a normal end and an abnormal interruption.
6.2 Incremental Concatenation for Tool Calls
Tool call arguments usually arrive in segments in streaming scenarios. The name, ID, and argument string of the same tool call may be scattered across multiple fragments and need to be accumulated by index.
def merge_tool_delta(acc: dict[int, dict], delta_calls: list[dict]) -> None:for call in delta_calls:idx = call["index"]slot = acc.setdefault(idx, {"id": "", "name": "", "arguments": ""})if call.get("id"):slot["id"] = call["id"]fn = call.get("function", {})if fn.get("name"):slot["name"] = fn["name"]slot["arguments"] += fn.get("arguments", "")
After concatenation, validate whether the arguments are valid JSON before passing them to the upper layer. If validation fails, return a diagnosable error message to the caller instead of silently discarding it.
6.3 Parsing Reasoning Content
Some models wrap the reasoning process in specific tags for output. The gateway can identify these tags during streaming to separate the reasoning content from the formal answer. Parsing must handle cases where a tag is split across two fragments, which usually requires maintaining a small buffer.
7. Storage and Deployment
7.1 Embedded Storage
For small to medium-scale deployments, credentials, API Keys, usage statistics, and logs do not necessarily require an independent database. An embedded key-value store can meet the persistence needs of a single instance, requiring only one data file to manage during deployment.
The trade-off with this approach is limited horizontal scaling. If multiple instances need to share state, the storage must be migrated to an independent service, handling concurrency and consistency issues.
7.2 Configuration Management
Sensitive configurations should be injected via environment variables, not hardcoded or committed to version control.
export GATEWAY_API_KEY="Replace with a randomly generated strong key"export ADMIN_PASSWORD="Replace with the admin panel password"
It is recommended to use different keys for each deployment environment and rotate them regularly. Admin passwords should be stored as hashes, not in plaintext.
7.3 Backup
Credential pools and usage data are assets that need protection. Regularly back up the storage file, and ensure writes are complete before backing up to avoid inconsistent snapshots.
8. Security and Operations
8.1 Access Control
- External interfaces use API Keys issued by the gateway for authentication. Each caller uses an independent Key for easy individual revocation.
- The admin panel and business interfaces have separate authentication, with limits set on login failure attempts.
- Set request rate limits per Key to prevent a single caller from exhausting the credential pool.
8.2 Log Masking
Request logs usually need to record the path, duration, status code, and account identifier, but should not record complete credentials, Authorization headers, or user-sensitive content. Credential fields in logs should be masked, for example, retaining only the last four digits.
