Design and Practice of a Proxy Gateway for Unified Access to Third-Party LLMs

    This article explains how to design a lightweight proxy gateway that sits between clients and LLM services, providing a standard chat API externally while adapting to each provider's authentication and protocol internally. It covers protocol abstraction, credential pool scheduling, layered context compression, streaming and tool-call forwarding, observability, security hardening, and a step-by-step deployment workflow, helping teams reuse model capabilities across editors, scripts, and business services at lower cost.

    In real-world development, teams often face this scenario: an intelligent coding tool already provides working model access credentials, but day-to-day work also requires reusing the same model capabilities in other editors, automation scripts, knowledge-base Q&A applications, or business services. Different clients typically use different request formats, authentication methods, and response structures. Integrating directly with the underlying APIs is not only expensive in development effort, but also introduces problems around account management, failure retries, context overflow, and audit logging.

    A general solution to this class of problems is to place a lightweight proxy gateway between clients and the model service. The gateway exposes an industry-standard chat API externally and handles adaptation to the upstream model service’s authentication method and request protocol internally. Callers only need to make requests against the standard interface, without understanding how the underlying service works.

    1. Core Problems the Proxy Gateway Solves

    1.1 Hiding API Differences

    Different model services may differ in request fields, message roles, model names, streaming formats, and tool-calling structures. For example, some APIs use a unified message array while others pass the system instruction separately; some return incremental content via an event stream while others return the complete result in one response.

    The proxy gateway can take on protocol conversion:

    • Map the model identifier in external requests to an internally available model;
    • Handle system, user, and assistant messages uniformly;
    • Convert generic tool definitions into the format required by the upstream service;
    • Repackage internal responses into the data structure callers expect;
    • Normalize error information so that low-level details are not exposed directly.

    With this abstraction layer, clients that support the standard interface usually need no core code changes—they only need to configure the service address and an access key.

    1.2 Centrally Managing Multiple Access Credentials

    A single account may be constrained by concurrency limits, rate limits, session quotas, or temporary failures. When the system serves multiple users or automated tasks, relying on one credential creates a single point of failure.

    The gateway can maintain a credential pool and track the following state for each credential:

    • Whether it is currently available;
    • Time of the most recent successful request;
    • Number of consecutive failures;
    • Current number of concurrent requests;
    • Time of the most recent rate-limit or authentication failure;
    • Cooldown end time;
    • Health score.

    For each incoming request, the scheduler selects a candidate credential based on these metrics—for example, preferring credentials with higher health scores, lower concurrency, and no recent rate limiting. If a credential fails mid-request, the gateway can decide whether to switch to another credential depending on whether the request has already produced non-retryable side effects.

    Note that retrying does not mean every request can be resent unconditionally. For tasks involving tool calls, external writes, or state changes, repeated execution may cause side effects. The scheduler should therefore distinguish read-only requests from requests with potential external impact and apply appropriate retry policies.

    A reasonably complete model proxy gateway can be divided into the following modules:

    1. Access layer: authentication, parameter validation, and request rate limiting.
    2. Protocol adaptation layer: converts external standard requests into internal requests.
    3. Scheduling layer: selects an appropriate credential from the pool.
    4. Context processing layer: checks message length and performs compression or trimming.
    5. Transport layer: forwards normal responses, event streams, and tool calls.
    6. State storage layer: stores account information, key digests, configuration, and runtime state.
    7. Administration layer: provides visual management of accounts, keys, logs, and monitoring data.
    8. Audit layer: records request metadata, error types, and scheduling decisions.

    A typical request flow looks like this:

    1. Client
    2. │
    3. ▼
    4. Authentication and parameter validation
    5. │
    6. ▼
    7. Context check and compression
    8. │
    9. ▼
    10. Credential health evaluation
    11. │
    12. ▼
    13. Target credential selection
    14. │
    15. ▼
    16. Protocol conversion and model service invocation
    17. │
    18. ▼
    19. Response parsing, format normalization, and logging
    20. │
    21. ▼
    22. Return to client

    The advantage of this layered design is clear separation of concerns. Protocol adaptation is not entangled with account scheduling, logging and monitoring can evolve independently, and adding a new model service type later only requires a new adapter.

    3. Context Compression and Session Management

    Long conversations are one of the most common constraints in model invocation. As users keep appending messages, the history quickly approaches the model’s context limit. Simply truncating the earliest messages is easy to implement but may lose the task goal, constraints, and key conclusions.

    A more robust approach is a layered context strategy:

    Layer 1: Preserve the System Instruction

    System-level rules typically define response style, output format, and safety boundaries, and should be preserved as completely as possible.

    Layer 2: Preserve Recent Messages

    The most recent turns are usually most relevant to the current task and should be kept verbatim so the model understands the immediate context.

    Layer 3: Compress Early History

    Summarize earlier conversation turns into a structured summary that includes at least:

    • The user’s overall goal;
    • Confirmed requirements and constraints;
    • Completed operations;
    • Important code, configuration, or decisions;
    • Unresolved issues;
    • Risks to watch for going forward.

    The compressed summary should not simply concatenate the original text; it should highlight facts and conclusions and avoid introducing new speculation. To reduce the cost of repeated compression, the gateway can store a summary version per session and update it only when the history changes significantly.

    In addition, three types of caches can be introduced:

    • Request-level cache: avoids reprocessing identical requests within a short window;
    • Session-level cache: stores session summaries and recent messages;
    • Configuration-level cache: caches model mappings, routing rules, and rate-limit policies.

    All caches must have expiration times, and sensitive full content should not be stored for long periods.

    4. Streaming Responses and Tool Calls

    Modern model applications usually need to display results as they are generated, so the gateway must not only support normal complete responses but also correctly forward event streams.

    When streaming, the gateway must handle the following carefully:

    • Preserve event ordering;
    • Do not arbitrarily merge incremental text;
    • Forward termination events correctly;
    • Release upstream connections promptly when the client disconnects;
    • Return recognizable error information when a mid-stream failure occurs;
    • Avoid excessive buffering that makes the response “look streaming but feel slow.”

    Tool calling is more complex. The model may first return a tool name and arguments; the application executes the tool, then appends the result to the conversation and continues the request. The gateway must ensure that tool names, argument structures, call IDs, and results correspond accurately to one another.

    Tool arguments should be strictly validated:

    1. {
    2. "name": "query_information",
    3. "arguments": {
    4. "keyword": "example content"
    5. }
    6. }

    The gateway itself should not execute arbitrary tools by default, nor should it bypass the permission controls of business services. A more reasonable design is to forward only the structured call request and let the upper-layer application decide whether to execute it, how to authorize it, and whether human confirmation is required.

    5. Admin Console and Observability

    As the system grows from personal use to team use, managing accounts and keys through configuration files alone becomes increasingly difficult. The admin console should provide at least the following capabilities:

    • Add, edit, suspend, and delete access credentials;
    • Create and revoke client access keys;
    • View credential health status;
    • Track request success rate, error rate, and latency;
    • Query recent request logs;
    • Configure rate limiting, retry, and context policies;
    • Manually recover abnormal credentials.

    Logging should follow the principle of minimization. Record metadata such as request time, latency, status code, model mapping result, error category, retry count, and response length—but do not save full conversation content by default. If the business genuinely requires content storage, it should be redacted, encrypted, and subject to an explicit retention period.

    Monitoring metrics fall into three categories:

    1. Availability metrics: success rate, timeout rate, connection failure rate;
    2. Capacity metrics: concurrency, queue length, credential usage counts;
    3. Quality metrics: context compression count, tool-call failure rate, stream interruption rate.

    6. Security Deployment Recommendations

    Access credentials are highly sensitive information. They must not be hard-coded into source code, committed to version control, or appear in ordinary logs. Recommended measures include:

    • Store admin passwords in environment variables or a dedicated secrets store;
    • Encrypt credentials at rest in the database;
    • Enforce strong passwords and session expiration in the admin console;
    • Show client access keys only once—regenerate if lost;
    • Apply source restrictions and rate limits to admin endpoints;
    • Assign independent permissions and call quotas per client;
    • Enable encrypted transport in production;
    • Rotate access credentials regularly;
    • Alert on abnormal logins and large volumes of failed requests.

    At the same time, you must confirm the model service’s terms of use, the scope of account authorization, and your organization’s internal compliance requirements. A proxy gateway can improve the technical integration path, but it cannot replace authorization management.

    7. Deployment Workflow

    Without depending on any specific vendor’s product, the deployment process can be summarized as follows:

    Step 1: Prepare the Runtime Environment

    Choose a runtime that supports asynchronous networking, event-stream transport, and lightweight persistence. Confirm that its version meets project requirements and prepare a dedicated configuration file.

    Step 2: Initialize Configuration

    Set the listening address, admin password, client access keys, log level, context limit, and retry policy. Do not use example passwords in production, and do not write sensitive configuration into publicly accessible files.

    Step 3: Start the Gateway Service

    After startup, first check the health-check endpoint, admin page, and basic logs. Confirm the service is listening properly and verify that both normal and streaming requests return correctly.

    Step 4: Register Access Credentials

    Add legitimately authorized credentials through the admin page. After registration, run a lightweight health check first—do not send complex tasks right away.

    Step 5: Configure Clients

    Enter the gateway address, client access key, and the standard model identifier in the client. For tools that support a custom API base URL, you typically only need to change the base address without touching business logic.

    Step 6: Verify Failure Scenarios

    Proactively test credential failure, request timeout, overly long context, mid-stream client disconnection, tool-call failure, and concurrent requests. Confirm the system logs errors correctly and applies the expected fallback behavior.

    8. Directions for Further Optimization

    Once the core functionality is stable, you can continue to enhance the gateway:

    • Route models based on task type;
    • Set per-user concurrency quotas;
    • Add request queues and priorities;
    • Provide cancellation for long-running tasks;
    • Introduce distributed state storage;
    • Integrate logs into a unified monitoring system;
    • Support multiple protocol adapters;
    • Build automated health checks and fault isolation mechanisms.

    Overall, the value of a model proxy gateway is not merely “converting one API into another.” More importantly, it establishes a unified access boundary. It centralizes protocol compatibility, credential scheduling, context governance, streaming transport, security auditing, and operational monitoring into a controllable layer—allowing upper-layer applications to integrate model capabilities at lower cost while laying the foundation for future expansion and scaled usage.