Optimizing an LLM Gateway: Model Routing and Prompt Compression
When teams that each call different model providers' APIs directly are consolidated behind a single gateway, the organization sees, for the first time and in one place, which model received each request and how many tokens it consumed. Two kinds of waste tend to show up in that data. Trivial queries, such as polishing a single sentence, are still sent to the most expensive model. And the same system instructions and examples ride along with every request, inflating input tokens. Swapping out an application's default model means re-tuning its prompts and re-running its evaluations. So the first question operators ask is whether they can cut both kinds of waste at the gateway while leaving the application alone.
Automatic model routing and prompt compression answer that question directly. Routing decides, per query, whether a cheaper model will do; compression reduces the input tokens sent to the same model. In both techniques, however, the trade-off between cost and quality is set by a single value, the router's threshold or the compressor's compression rate, and both values have to be recalibrated on the organization's own traffic. That calibration needs query text, request structure, and judgments of answer quality. What a gateway records by default, by contrast, is token counts and model names. Whether the two techniques actually save what the organization expects therefore depends on whether the gateway collects those three signals separately. This post starts from what a gateway observes by default, walks through how each technique works and which signals each value needs for calibration, and closes with the query categories where quality loss concentrates.
The LLM Gateway as a Single Point for Multi-Model Calls
An LLM gateway is a proxy layer that sits between applications and multiple model providers, receives every inference request, and forwards it to the target model. Because every inference request passes through this layer, the gateway can change the target model and the input of any request without modifying the application. For the same reason, usage and cost are aggregated at the organization level. A gateway that brokers tool calls was covered in "The MCP Gateway, A Deep Dive." This post looks at an inference gateway in the same position and how it changes cost on a per-request basis.
What a gateway should record for each request is being defined by OpenTelemetry's semantic conventions for generative AI. Semantic conventions fix the names and meanings of telemetry attributes so that different implementations record the same value under the same name. A client inference span records the name of the requested model (gen_ai.request.model) separately from the name of the model that actually generated the response (gen_ai.response.model). Input and output token counts are recorded alongside them as recommended attributes. Because the two model names are distinct attributes, a gateway that sends a request to a different model leaves that difference in the span.
Unlike these default attributes, the content of queries and answers is recorded only when the operator explicitly turns it on. In the same conventions, input messages, output messages, system instructions, and tool definitions are opt-in attributes. Input messages also carry a warning that they are likely to contain users' personal information, so not recording content by default is a reasonable choice. The result is that a gateway with default settings records which model got how many tokens, but not what the query was or whether the answer was good enough. The gateway sits where per-request cost can be changed, yet by default it records only the attributes needed to aggregate cost.
Two Levers for Cutting Cost at the Gateway Without Changing the Application
The cost of a single request comes down to which model handles it and how many tokens that model receives. Those are also the two levers a gateway can adjust to lower cost. One is automatic model routing, which decides per query whether a cheaper model is good enough; the other is prompt compression, which reduces the input tokens sent to the same model. The open-source RouteLLM implementation runs as a server compatible with the chat completions API, so the client only has to put a name that designates the router in the request's model field. A compressor like LLMLingua shortens only the content of the prompt in front of the target model, so the target model and the way it is called stay the same.
The two techniques also share the property that a single value sets the cost-quality trade-off. For the router, raising the threshold sends more queries to the cheaper model, which lowers cost and raises the risk of degraded quality. For the compressor, raising the target compression rate means fewer input tokens and more information removed. The RouteLLM implementation, however, uses a public preference dataset as its default calibration data. Since actual routing ratios vary with incoming traffic, the threshold has to be recalibrated on data that resembles the queries the organization actually receives. The maximum practical compression rate for LLMLingua likewise varies with prompt length and task type, and performance drops noticeably at very high compression rates. The compression rate therefore should not be carried over from a single benchmark; it has to be matched to the kinds of tasks the organization actually sends.
The signals needed for calibration are of a different kind from the default attributes covered in the previous section. Recalibrating the router's threshold requires the text of the queries the organization actually receives. Applying different compression rates to different parts of a request requires a request structure that marks which part is the system instruction and which parts are examples or the question. Both techniques also need a judgment of whether a routed or compressed answer came out worse than the unrouted or uncompressed one. Both levers can be applied at the gateway right away, but the threshold and the compression rate can only be set from signals the gateway collects separately, outside the default attributes.
Automatic Routing of Queries to the Right Model
In automatic model routing, the router looks only at the query text, before the request runs, and picks either a strong model or a weak one; the gateway then forwards the request to that model. In RouteLLM, researchers at UC Berkeley and elsewhere formalized this decision as a problem of learning from preference data. Preference data is a record of human judgments about which of two models' answers to the same query was better. RouteLLM's cost-savings results and limitations were covered in "From Query to Module — A History of LLM Cascade Routing," so this section focuses on how the router reaches its decision and what signals that process requires.
The router's decision has two steps: win prediction and comparison against a threshold. Win prediction takes a query and computes the probability that the strong model's answer will beat the weak model's. A matrix factorization router, for example, represents the query and each model as embedding vectors and derives the win rate from a score that combines them. If the win rate is at or above the threshold α, the router sends the query to the strong model; below it, to the weak model. Suppose a router with α set to 0.3 estimates a win rate of 0.2 for a summarization request: that request is sent to the weak model. If it estimates 0.6 for a multi-step reasoning query, that query is sent to the strong model. Lower α to 0.1 and the same summarization request is sent to the strong model as well. (All of these values are hypothetical, for illustration.) In this way, the single value α sets the share of queries sent to the strong model, and that share sets the cost of routing.
The win rate a router computes is meaningful only within the distribution of its training data. The public preference data RouteLLM used was collected from a public service where users see two models' answers side by side and vote for the better one. A router trained on this data alone performed roughly on par with random routing on MMLU, a general-knowledge benchmark, and on GSM8K, a math word-problem benchmark. Most queries in both benchmarks fell outside the training distribution. Augmenting the training data with gold labels and LLM-judge labels improved the router's performance. The authors acknowledge as a limitation that the query distribution of real applications may differ substantially from the benchmarks. To get a router that fits an organization's traffic, the gateway has to collect that organization's query text and quality judgments so they can be used to retrain the router.
The distribution mismatch shows up directly as a cost error when the threshold is set. In RouteLLM, operators don't pick α directly; they set a target for the share of queries to send to the strong model, the call fraction. The implementation's calibration script takes this target as input and computes the α that produces it on the calibration data. But if the query distribution of the calibration data differs from that of real traffic, the actual call fraction drifts from the target even at the same α.
The default attributes are enough to detect this error. The actual strong-model call fraction can be aggregated from gen_ai.response.model alone. Recomputing α, however, requires recording the router's estimated win rate in the span for every routing decision. With that record, the gateway can compute directly from the win-rate distribution of recent requests the α that yields the target share. The threshold sets how much routing saves, and whether that threshold behaves at the intended ratio depends on whether it was calibrated on the organization's queries.
Prompt Compression by Removing Low-Information Tokens
Prompt compression leaves the model as it is and reduces the input tokens sent to it. LLMLingua chooses which tokens to drop by perplexity. Perplexity measures how difficult it is for a language model to predict the next token given the preceding context. LLMLingua first uses a small language model to compute the perplexity of each token in the prompt. It then treats low-perplexity tokens as contributing little information, removes them until the target compression rate is met, and sends the shortened prompt to the target model. For instance, phrases that restate the previous sentence and function words that are easy to predict from context are dropped first, while hard-to-predict tokens such as numbers and proper nouns survive. (This is an illustrative example.)
LLMLingua does not apply one compression rate to the whole prompt. Its budget controller is the component that splits the prompt into instruction, demonstrations, and question and sets a separate compression rate for each part. The budget controller first assigns high retention ratios of 0.85 and 0.9 to the instruction and the question, respectively, and gives the remaining budget to the demonstrations. Multiple demonstrations tend to overlap heavily in information, so they leave the most room to cut. This allocation is possible only when the caller passes the boundaries between instruction, demonstrations, and question to the compressor. If the whole prompt is passed without them, tokens in the instruction that define the format and scope of the answer can be dropped by the same criterion as tokens in repetitive examples.
Choosing tokens to drop by perplexity has a structural weakness. The small language model computes probabilities from the preceding context only. Moreover, a token that is easy to predict is not thereby a token the answer doesn't need. LLMLingua-2 cites this weakness to recast compression as a token classification problem. Token classification is a binary decision, made for each word in the original text, about whether to keep or drop it. The classifier is a Transformer encoder that sees bidirectional context, trained on compressed versions produced by a large model as ground truth. At inference time, the encoder computes a keep probability for each word, and the compressor retains the highest-probability words, in their original order, up to the target ratio.
Because LLMLingua-2 only selects words from the original and keeps them in order, it never introduces content that wasn't in the source. There is no guarantee, though, that the retained words include every condition the answer depends on. LLMLingua-2 is task-agnostic, so the question that will follow the context is not part of its input at compression time. A condition needed to answer the question can therefore receive a low probability and be dropped. This difference also explains why, on a long-context benchmark, LLMLingua-2 scored lower than a method that compresses with the question in view. If a gateway uses this approach, finding out what the compressed version left out requires a separate judgment of answer quality.
To put a compressor in the gateway, the gateway has to pass the request's structure along to it. The open-source LLMLingua implementation offers structured compression, where segments of the prompt are wrapped in tags and either excluded from compression (compress=False) or given their own compression rate (rate). In chat-format requests, the gateway can distinguish message roles (system, user) and tool definitions. The gateway can therefore enforce a rule that leaves system instructions, output-format instructions, and tool definitions uncompressed and compresses only long reference context and examples. The target compression rate sets how much compression saves, but whether compression leaves instructions intact depends on whether the gateway passes message roles to the compressor.
Quality Loss from Compression and Routing, and Its Verification
The quality loss from both techniques barely shows in average scores and concentrates in specific categories of queries. In How Robust Are Router-LLMs?, researchers from the Max Planck Institute for Intelligent Systems, the University of Toronto, and elsewhere showed that routers tend to use a query's category as a cue for their decisions. Routers trained on preference data sent nearly all coding and math queries to the strong model, even easy ones. When math or code keywords were inserted into queries from other categories, the routers changed their decision on about 98% of the modified queries. The routers were responding to the keywords in the query rather than to its difficulty, and an operator who looks only at average scores has no way to see this kind of per-category bias.
In the safety category, the bias runs the other way. A jailbreak query is one crafted to get a model to bypass its safety policy. In the same experiments, the routers sent most jailbreak queries to the weak model. The matrix factorization router sent only 4% of them to the strong model, and the weak model used in the experiments failed to block those attacks. When a router sends a query to the weak model, both its cost and the safety policy that applies to it change.
Since the category of an incoming query can't be known in advance, adjusting the threshold alone cannot fix this bias. The study doesn't propose a concrete mitigation either. The path for reversing misrouted decisions therefore has to live outside the router. The gateway can send categories that policy says need the strong model, such as queries a safety classifier flags as risky, down a fixed path ahead of the router.
For queries that do go through the router, the gateway can add escalation. Escalation re-sends a query to the strong model when the weak model's answer fails. Failure conditions can include the weak model's answer not passing output-format validation, or the user immediately re-sending the same query. If the gateway records escalated queries along with the condition that triggered them, that record becomes a set of samples labeled as queries for which the weak model was not enough, which can feed the next threshold calibration and router retraining. Escalated queries call both models, though, so routing savings have to be calculated net of escalation cost.
The loss from compression varies widely by task type. The authors of Understanding and Improving Information Preservation in Prompt Compression for LLMs fixed the compressed prompt at 350 tokens, applied LLMLingua, and compared scores before and after compression. Scores fell by as little as about 3% relative to no compression, and by about 54% on HotpotQA, a question-answering benchmark that requires reasoning across multiple documents. Grounding, the degree to which an answer is based on the input context, also fell on HotpotQA from 0.80 to 0.45. On GSM8K, compressed math demonstrations produced worse results than including no demonstrations at all. The evaluation was limited to one target model and English benchmarks. Even so, because the drop varies this much across tasks, the compression rate has to be set per task type the organization actually sends.
Question-answering scores can also make this loss look smaller than it really is, because the model generating the answer can still get it right from a compressed version that is missing part of its evidence. That is why KEEP-Bench, a benchmark for evaluating context compression, measures directly whether the compressed version preserves the evidence for the answer instead of whether the answer is correct. Because this benchmark evaluated LLM-based compressors, its results cannot be applied directly to token-deletion methods. The evaluation principle, however, that evidence preservation must be measured separately from answer correctness applies to both.
Since a single average score can't reveal the loss, the quality signals a gateway collects also have to be samples from the categories where the evidence above showed loss. For routing, those are queries a safety classifier flags as risky and queries mixed with math or code keywords. For compression, they are multi-document question answering and requests containing math demonstrations. The gateway records input and output messages only for requests in these categories and compares answers with and without compression and routing. Each comparison costs an extra call, either sending the same request uncompressed or sending it to the strong model. Restricting sampling to these categories reduces both the cost of the extra calls and the scope of personal-data exposure. Since there is not yet a standard metric for measuring the loss from either technique, the basis for calibration comes from samples the gateway collects per category itself.
Summary
Automatic model routing compares the strong model's win rate against a threshold to send queries to a cheaper model, and prompt compression removes low-information tokens up to the target compression rate. Both techniques are applied per request at the gateway without changing the application. But a router's win rate falls to the level of random routing outside its training distribution, and compression loss is largest in multi-document question answering and in math demonstrations. The threshold and compression rate therefore have to be reset on the organization's own traffic, yet the token counts and model names that the standard observability conventions record by default show only the size of the savings, not the loss.
In the end, cost optimization at the gateway is less a matter of choosing a router or a compressor than of deciding which signals to collect for calibration. Query text is used to retrain the router to fit the organization's distribution. With the estimated win rate recorded for every routing decision, the threshold can be recomputed whenever the actual strong-model call fraction drifts from its target. Request structure is passed to the compressor as message roles, so that system instructions, output-format instructions, and tool definitions are excluded from compression. Quality judgments come from escalation records and from samples in the categories where loss concentrates, and opt-in collection of input and output messages is limited to those categories as well. Only a gateway that has all three signals can set the threshold and compression rate to values that fit the organization's traffic.
References
- Semantic conventions for generative AI client inference
- lm-sys/RouteLLM
- LLMLingua: Compressing Prompts for Accelerated Inference of Large Language Models
- RouteLLM: Learning to Route LLMs with Preference Data
- LLMLingua-2: Data Distillation for Efficient and Faithful Task-Agnostic Prompt Compression
- microsoft/LLMLingua
- How Robust Are Router-LLMs? Analysis of the Fragility of LLM Routing Capabilities
- Understanding and Improving Information Preservation in Prompt Compression for LLMs
- KEEP-Bench: Evaluating Evidence Preservation in Context Compression