Building a Custom LLM Gateway: Multi-Model Switching with Dynamic Routing

    This article explains why developers need a custom LLM gateway when they use several model providers. It covers the protocol and capability differences that make switching models difficult, the role of a protocol adaptation layer, and dynamic routing based on input modality and prompt content. It also covers hot reloading, real-time monitoring, and the trade-off with prefix cache hit rates.

    As large language models (LLMs) become standard in development workflows, developers often need to use API services from several model providers at once. Different models have different strengths in reasoning, code generation, and multimodal processing. However, this creates serious engineering problems. AI programming tools and AI assistants do not support API calling styles consistently. Some support only the Chat Completion style, while others support only the Message format. Providers also differ in how closely their interfaces follow common standards. This fragmentation makes it tedious to configure tools or switch models, and it prevents developers from easily using the best combination of models. A custom LLM gateway that uses dynamic routing rules to distribute requests across models is a key technical approach for regaining control over model selection and improving development efficiency.

    1. Core Pain Points: API Fragmentation and Model Selection in the Multi-Model Era

    In practice, the pain points fall into three areas:

    1. Protocol incompatibility: AI tools on the client side and cloud providers often use incompatible protocols. Developers must find tools and providers that support the same protocol style, which limits their options.
    2. Uneven capabilities: No single model performs best in every dimension. For example, some large models with strong reasoning abilities do not accept image input. Multimodal models may also generate code in certain programming languages less well than models specialized for code.
    3. Fragmented cost and access management: Developers often use different API keys for work projects and personal projects to separate billing and meet compliance requirements. Switching tokens by hand within tools is error-prone and tedious.

    To solve these problems, adding a gateway layer that hides model differences from upper-layer tools has become a common architectural direction in the industry.

    2. Architecture: The LLM Gateway and Protocol Adaptation Layer

    The core value of an LLM gateway is a unified entry point with dynamic distribution. Its basic architecture needs a protocol adaptation layer. When a client tool sends a request, the gateway first receives it and parses it into a unified internal representation, regardless of the API style the tool uses. When forwarding the request to a downstream provider, the gateway then repackages the request body to match that provider’s requirements.

    With this design, upper-layer tools do not need to know which provider or model handles a call. They only need to interact with the standard interface that the gateway defines.

    3. Core Engine: Dynamic Routing for Intelligent Distribution

    The dynamic routing engine is the core of the gateway. Using predefined matching rules, the gateway analyzes request payloads in real time and routes each request to the most suitable model.

    1. Automatic switching based on input modality

    This is one of the most typical use cases. Suppose a developer mainly uses a text-only model with strong reasoning ability. That model cannot process tasks that require visual understanding.

    By configuring a “multimodal detection route” in the gateway, the gateway checks the request body for image-related data structures, such as Base64-encoded images or image URLs. If it detects image input, it redirects the request to a model that supports multimodal input. If it detects no image, the request continues along the default text and code model route. This process is fully transparent to upper-layer tools, so the switch happens without any visible change for the user.

    2. Token isolation based on contextual features

    Many AI programming tools include the current working directory path in the system prompt when they initialize. The gateway can use this behavior for finer-grained management through regex-based prompt routing.

    For example, consider this rule: if a request’s prompt contains the path /home/user/company/, the gateway routes the request to the company’s dedicated API endpoint and injects the company API key. If the path matches /personal/, the gateway uses the developer’s personal token and billing channel. This context-based routing separates the costs and access of company and personal projects without any manual switching in the tool.

    The following illustrative routing rule configuration shows how the distribution logic can be defined flexibly:

    1. {
    2. "routes": [
    3. {
    4. "name": "multimodal-route",
    5. "match": {
    6. "type": "has_image"
    7. },
    8. "forward": {
    9. "endpoint": "https://api.vision-model.com/v1/chat",
    10. "model": "vision-pro",
    11. "api_key_env": "VISION_API_KEY"
    12. }
    13. },
    14. {
    15. "name": "company-project-route",
    16. "match": {
    17. "type": "regex",
    18. "pattern": "/home/dev/company/",
    19. "field": "system_prompt"
    20. },
    21. "forward": {
    22. "endpoint": "https://internal-gateway.company.com/api",
    23. "model": "enterprise-llm",
    24. "api_key_env": "COMPANY_TOKEN"
    25. }
    26. },
    27. {
    28. "name": "default-code-route",
    29. "match": { "type": "catch_all" },
    30. "forward": {
    31. "endpoint": "https://api.code-model.com/v1/chat",
    32. "model": "code-master-v2"
    33. }
    34. }
    35. ]
    36. }

    4. Engineering Practice: Hot Reloading and Observability

    An LLM gateway must be flexible and observable to fit complex development environments.

    1. Configuration hot reloading and seamless switching

    Restarting the gateway service to change its configuration is unacceptable in a frequently used development environment. A well-designed LLM gateway should support enabling and disabling routing rules while it runs. Developers can turn a routing rule on or off from the console with one action. For example, to send all requests to a specific model for a comparison test, a developer can disable the default route and enable a backup route. Connections from the programming tools stay active, and the next request uses the new distribution logic immediately.

    2. Real-time monitoring and dashboard

    To maintain service quality, the gateway should include a built-in observability dashboard. The dashboard collects and displays key metrics in real time, including the number of concurrent requests, output speed (tokens per second), and request latency. Developers can use these metrics to compare how each model responds. When a provider applies rate limits or experiences network instability, the dashboard also helps developers find the cause quickly.

    5. Technical Trade-off: Impact on Cache Hit Rate and Optimization

    Dynamic routing has a cost. Its main drawback is that it lowers the cache hit rate. LLM services and local gateway layers often use prefix caching to speed up responses and reduce cost. When requests are frequently routed to different underlying models, the existing prefix cache often becomes invalid, because different models use different tokenizers and cache keys. This can slightly increase the latency of the first response and may cause repeated token computation.

    In practice, this overhead is usually acceptable. Developers gain flexibility and the best combination of models. Compared with the small drop in cache hit rate, the gain in overall development efficiency is worth more. To reduce the impact, the gateway can implement sticky sessions or apply cache strategies per model, so that context is reused as much as possible within the same routing path.

    Conclusion

    Separating model selection from any single AI tool and letting developers control it directly is an important step for LLM applications as they mature. A gateway with protocol adaptation, dynamic routing, hot reloading, and real-time monitoring lets developers combine multimodal and text-only models in one workflow. It also handles enterprise access control and cost separation. This architecture makes the tool chain more reliable and provides a standardized base for connecting more heterogeneous models in the future.