LLM Gateway Routing Rules: Automatic Model Switching for AI Coding Tools
This article explains how to build an LLM gateway that sits between AI coding tools and model providers and uses routing rules to select providers, models, and credentials per request. It covers the pain points of multi-provider setups, a four-step gateway workflow, practical routing patterns based on image content, project paths, and fallback priority, plus engineering considerations such as protocol conversion, rule engine design, observability, deployment, and tradeoffs including cache hit rates and single-point risk.
LLM Gateway Routing Rules: Automatic Model Switching for AI Coding Tools
1. Background: Why Model Switching Is So Painful
In daily development and applied AI work, more and more developers connect APIs from multiple model providers at the same time and combine them with various AI coding tools, chat tools, and automation scripts. This “multiple tools + multiple providers” setup adds flexibility, but it also introduces three notable pain points.
First, calling styles are inconsistent. The mainstream model interfaces in the industry roughly fall into two styles: a conversational style built around message lists and system prompts, and a vendor-specific protocol style used by some providers. The situation is further complicated by uneven support: some providers support both styles, while others offer only one. The tool side has the same problem. Some AI coding tools only allow an endpoint in one specific style. As a result, even if you have multiple usable model resources, you may not be able to connect them smoothly to the tool you want to use.
Second, switching costs are high. When you want to move a tool from Model A to Model B, you often need to edit configuration files, replace keys, change endpoint addresses, and sometimes restart the tool process. If multiple tools each maintain their own configuration, one switch requires repeated work across tools, which is both tedious and error-prone.
Third, model capabilities do not always match the request. In practice, there is no single “best for everything” model. A typical example is a model with strong code generation capabilities that does not support image input. If you paste an architecture screenshot or an error screenshot into a conversation, the entire session may fail or force you to switch models manually. Model selection is left to the rigid configuration of the tool instead of being decided dynamically based on the actual request content.
The common root cause of these problems is simple: requests go directly from the tool to the provider, with no layer in between that can make decisions. The solution follows naturally from that diagnosis: build your own LLM gateway.
2. Core Idea: Add a Routing Layer Between Tools and Providers
An LLM gateway is essentially a proxy service positioned between client tools and model providers. Externally, it provides a unified interface and can support multiple calling styles at the same time. Internally, it maintains a routing rule table and dynamically decides, based on the characteristics of each request, which provider should receive the request, which model should be used, and which credential should be applied.
Its core workflow can be summarized in four steps:
- Receive the request: The tool sends requests to the gateway’s local address instead of connecting directly to the provider.
- Extract features: The gateway parses the request body and extracts matchable features, such as whether the request contains image content, whether specific keywords appear in the prompt, or which tool sent the request.
- Match rules: The gateway evaluates routing rules in priority order. The first matching rule determines the target provider, target model, and corresponding credential.
- Convert protocols and forward: If the tool’s calling style does not match the target provider, the gateway converts request and response formats in the middle, then streams the result back to the tool.
The biggest change this architecture brings is that model selection moves from static configuration to dynamic decision-making. The tool only needs to be configured once with the gateway address. After that, all switching logic is consolidated into the gateway’s rule table, and the tool remains unaware of the changes.
3. Typical Patterns: Let Routing Rules Choose the Model for You
3.1 Switch by Content Feature: Send Image Requests to a Multimodal Model Automatically
This is the most intuitive and practical rule. Suppose the code model you use every day is powerful but does not support image input. You can configure a rule like this:
Rule 1: When the messages in a request contain content blocks of type image→ Route to a multimodal model that supports visual input
The effect: all ordinary text conversations use your preferred code model. Once you paste an image into the conversation, the gateway detects image content in the new request and automatically forwards that request to the multimodal model. After the request is handled, subsequent text requests return to the original model. The whole process requires no manual action, and the tool session is not interrupted.
The abstract principle behind this is worth emphasizing: let the content of the request determine who should handle it, rather than letting a one-time configuration decide the fate of every request.
3.2 Switch by Prompt Feature: Project-Level Account Isolation
Many AI coding tools concatenate the current project’s local path into the system prompt or context when constructing prompts. This seemingly minor detail can be used by routing rules.
Suppose your work projects all contain a specific path prefix, while personal projects use another prefix. You can configure:
Rule 2: When the prompt contains the path fragment "/work/company-project"→ Use the work account's key and quotaRule 3: When the prompt contains the path fragment "/personal/"→ Use the personal account's key and quota
With this setup, requests automatically use work credentials when you open a company project and personal credentials when you open a personal project. This achieves automatic isolation of billing and permissions at the project level. The same idea can be extended: distinguish production and experimental calls by keyword, or assign models of different capability tiers to different task types such as documentation writing and code generation.
3.3 Priority Fallback: Fast Switching at the Provider Level
Routing rules are evaluated in order, which naturally supports a primary/backup structure. For example:
Rule 4: All requests not matched by the rules above → Provider A, Model X (default preferred)Rule 5: All requests → Provider B, Model Y (fallback)
Rules take effect from top to bottom. To switch all traffic to Provider B immediately, you only need to disable Rule 4 in the management interface. No tool configuration changes are required, and no tool process needs to be restarted. When a provider becomes unstable or runs out of quota, this one-click switching capability is extremely valuable. The design can be further extended with simple health checks and automatic failover, allowing the gateway to probe upstream availability and automatically remove unhealthy routes.
4. Engineering Implementation Notes
Several key technical decisions are worth discussing when building such a gateway.
Protocol compatibility layer. The gateway needs to implement receiving endpoints for both mainstream calling styles and include a bidirectional converter. Conversion details include message role mapping, differences in system prompt placement, structural differences in tool-calling fields, and differences in streaming event formats. This is the largest part of the project. A recommended approach is to implement a “request model normalization middle layer”: first normalize requests from all styles into a unified internal format, then serialize them into the target provider’s format. This avoids an N x N conversion matrix.
Rule engine design. Rules should be composable, enableable/disableable, and prioritized. A single rule should contain at least three elements: matching conditions such as content type, keyword, or request source; target action such as provider + model + credential; and enabled state. Describing rules with declarative configuration such as JSON or YAML and providing a simple management interface with on/off switches can significantly reduce the mental burden of daily use. Hot updates are also important: changes should take effect immediately without restarting the gateway process.
Observability. A practical gateway cannot do without a dashboard. At minimum, expose real-time metrics such as current concurrent requests, output rate in tokens per second, hit counts for each rule, and latency and error rates for each provider. These data points not only help with troubleshooting but also guide routing rule tuning. For example, if a rule has an unusually high hit rate, its matching conditions may be too broad.
Deployment form. The gateway is essentially a stateless forwarding service. It can be implemented with any mainstream runtime and compiled or packaged as a single-file executable for distribution. For individual developer use, “download one file, run it, open the management interface” is the most friendly form because it avoids dependency installation and environment configuration.
5. Tradeoffs and Limitations
This approach is not without costs. The most notable one is the change in cache hit rate. Mainstream providers commonly offer prompt caching: repeated prefixes across consecutive requests can benefit from faster processing and lower cost. When the gateway routes requests from the same session to different models—for example, text to Model A and image requests to Model B—each provider sees a fragmented session context, so the cache prefix cannot be fully reused and the hit rate drops slightly. In practice, if image requests are not a large share of traffic, the overall impact is usually acceptable, but this is a factor to consider when designing rules.
Other limitations also deserve attention. The gateway itself becomes a single point, so production environments should consider multi-instance deployment. Keys are stored centrally on the gateway, so local access control must be handled carefully. Protocol conversion cannot cover every edge feature, such as vendor-specific extension parameters, so the design should target the intersection of common capabilities.
6. Conclusion
Taking model selection away from the tool is essentially extracting the concern of “routing decisions” from the application layer and turning it into an independent infrastructure layer. The value of an LLM gateway is not only that it removes the hassle of manual switching. More importantly, it turns “matching models to requests” into an engineering practice that can be continuously optimized: rules can evolve, metrics can be measured, and strategies can be accumulated. For developers and teams using multiple model services at the same time, this is a self-built direction with a very high return on investment. If you are building enterprise-grade AI applications, you can also combine this gateway pattern with general cloud capabilities such as container platforms, logging services, and monitoring and alerting to gain more complete elasticity and operability.
