Routing Chinese LLMs Through One API Endpoint

DeepSeekAPIKeyFree · Updated 2026-11-24 · 14 Min read

Diagram showing a central gateway connecting to multiple AI models
A unified gateway architecture connecting multiple LLMs

Many developers find it tedious to manage separate API keys, rate limits, and endpoint URLs for each Chinese large language model. Instead of writing custom adapters for DeepSeek, Qwen, and GLM, you can build a unified gateway that normalizes requests into a single interface. This approach reduces boilerplate code and makes switching models as simple as changing a configuration variable, allowing you to focus on application logic rather than infrastructure quirks. Check /llms.txt for available model details.

A unified gateway acts as a reverse proxy that accepts standard requests, determines the target model, and routes traffic accordingly. By abstracting the underlying infrastructure, you gain flexibility to test different models for specific tasks—such as reasoning or coding—without rewriting your integration logic. This is particularly useful when pricing or availability shifts for one provider, as you can redirect traffic without modifying your application code. You can test the standard interface at https://api.deepseekapikeyfree.com/v1/chat/completions.

This guide walks you through constructing a lightweight gateway that supports multiple Chinese LLMs. We will cover request normalization, response streaming, and error handling. You will also learn how to integrate a free, keyless option like the free-ai endpoint into your routing logic, giving you a zero-cost baseline for testing. Note that while this guide discusses DeepSeek, this site is not affiliated with DeepSeek, and the models discussed are independent products. See /prompt.txt for prompt templates.

Frequently asked questions

What is a unified API gateway for LLMs?

A unified API gateway is a middleware service that sits between your application and multiple large language models. It normalizes input requests and output responses, allowing your code to interact with different models through a single, consistent interface without needing to know the specific details of each provider's API.

How does a gateway differ from a direct API call?

A direct API call sends data straight to one model's endpoint, requiring you to handle that specific model's authentication, rate limits, and response format. A gateway abstracts these details, allowing you to route requests to any supported model through a single endpoint, simplifying integration and reducing code complexity.

Which gateway is better for production use?

The best gateway depends on your needs. A custom-built gateway offers full control and lower costs, while managed services offer ease of use but often add markup. For developers who want flexibility and transparency, building a lightweight proxy using tools like FastAPI or Go is often the best balance of performance and cost. Read more about access without markup.

What is the role of the free-ai endpoint in a gateway?

The free-ai endpoint provides a keyless, OpenAI-compatible API for testing and light usage. Integrating it into your gateway allows you to route requests to a zero-cost model for non-critical tasks, reducing overall expenses while maintaining the same interface structure as your paid model integrations.

How do I handle rate limits in a unified gateway?

A robust gateway tracks usage per IP or API key and implements retry logic with exponential backoff. When a 429 status code is received, the gateway can queue the request and retry after the specified delay, ensuring that temporary rate limits do not disrupt your application's workflow.

Can I use a gateway with streaming responses?

Yes, most modern gateways support Server-Sent Events (SSE) for streaming. By forwarding the streaming response from the underlying model, you can maintain real-time updates in your application, which is crucial for chat interfaces and interactive experiences where latency matters.

What models are commonly supported by such gateways?

Commonly supported models include DeepSeek, Qwen, GLM, and other Chinese LLMs. These models vary in size and capability, from lightweight 8B parameter models to large 35B+ models. A good gateway allows you to switch between these models dynamically based on the task requirements.

Is a unified gateway better than using multiple SDKs?

A unified gateway is generally better for scalability and maintainability. Using multiple SDKs leads to fragmented codebases and inconsistent error handling. A gateway centralizes logic, making it easier to update models, add new providers, and monitor performance across all integrations from a single dashboard.

Step by step

  1. Set Up Proxy — Install a lightweight framework like FastAPI and define routes for /v1/chat/completions. Configure environment variables for API keys and endpoints of supported models to establish the foundation of your gateway.
  2. Normalize Requests — Write a middleware function to map model-specific parameters to a standard schema. Ensure all incoming requests are validated against a Pydantic model for consistency, ensuring that your application receives predictable inputs.
  3. Implement Routing — Create a routing function that selects the target model based on configuration or load balancing rules. Integrate the free-ai endpoint as a default fallback for testing, providing a zero-cost option for non-critical tasks.
  4. Handle Streaming — Implement an SSE parser to forward streaming responses from the underlying models. Ensure metadata events like token usage are forwarded alongside content chunks, providing a complete view of the request lifecycle.
  5. Add Error Handling — Implement retry logic with exponential backoff for transient errors. Log errors with context and respect Retry-After headers for rate limit responses, ensuring that your gateway is resilient to temporary disruptions.
  6. Deploy and Monitor — Deploy the gateway using a containerization tool like Docker. Set up monitoring for latency, error rates, and token usage to ensure ongoing performance and make data-driven decisions about optimization.

Designing the Gateway Architecture

A unified gateway must normalize requests from various models into a common format, typically the OpenAI chat completions structure. This means mapping different model-specific parameters like temperature, max_tokens, and stop sequences into a standard payload. By standardizing the input, you can write a single client library that works with any model behind the gateway, reducing the need for model-specific adapters. You can also check /llms.txt for model details.

The architecture should also handle response normalization. Each model may return data in a slightly different format, so the gateway must parse these responses and convert them into a consistent structure. This includes handling streaming responses, error messages, and token usage statistics. A well-designed gateway ensures that your application receives predictable outputs regardless of the underlying model, which is critical for maintaining data integrity in your application.

Request Normalization

Normalization involves translating model-specific parameters into a common schema. For example, mapping DeepSeek's 'reasoning' flag to a standard 'tools' or 'metadata' field. This ensures that all requests follow a consistent structure, making it easier to debug and log traffic across different models and ensuring that your application logic remains decoupled from specific provider quirks.

Response Parsing

Response parsing requires handling various JSON structures and streaming formats. The gateway must extract the content, usage statistics, and any metadata, then repackage them into a unified format. This step is critical for maintaining consistency in your application's data processing pipeline, especially when switching between models with different response characteristics.

  • Define a standard input schema for all supported models
  • Map model-specific parameters to standard fields
  • Implement a response parser for each model type
  • Ensure consistent error handling across all endpoints
import httpx

async def normalize_request(request: dict, model: str) -> dict:
    # Standardize parameters for different models
    normalized = {
        'model': model,
        'messages': request.get('messages', []),
        'temperature': request.get('temperature', 0.7),
        'max_tokens': request.get('max_tokens', 2048)
    }
    return normalized

Implementing Routing Logic

Routing logic determines which model handles each request. This can be based on the model name specified in the request, the user's preferences, or load balancing rules. A simple implementation might route all requests to a default model unless specified otherwise. More advanced setups can use heuristics to select the best model for a given task, such as sending reasoning-heavy queries to larger models. See DeepSeek Think vs Expert for insights on model selection.

The routing layer should also handle failover. If a model is unavailable or returns an error, the gateway can automatically retry with a different model or return a cached response. This improves reliability and ensures that your application remains functional even if one provider experiences downtime. Implementing a health check endpoint for each model helps the gateway make informed routing decisions based on real-time performance.

Load Balancing Strategies

Load balancing distributes traffic across multiple models to prevent any single provider from becoming a bottleneck. Strategies include round-robin, least-connections, or weighted routing based on model performance. This ensures optimal resource utilization and reduces latency for end-users, especially when dealing with high-volume traffic patterns.

Failover Mechanisms

Failover mechanisms automatically switch to a backup model when the primary one fails. This can be triggered by high latency, error rates, or explicit configuration. Implementing circuit breakers prevents repeated requests to a failing model, allowing it time to recover while maintaining service continuity and preventing cascading failures.

  • Define routing rules based on model capabilities
  • Implement health checks for each model endpoint
  • Set up failover logic for redundant requests
  • Monitor routing decisions for performance optimization
async def route_request(request: dict, models: list) -> str:
    # Simple round-robin routing
    selected_model = models[0]
    # In a real scenario, use a load balancer or health check
    return selected_model
Code editor showing Python gateway implementation
Implementing routing logic in Python

Integrating Free and Paid Endpoints

Integrating both free and paid endpoints allows you to optimize costs while maintaining performance. The free-ai endpoint, for example, offers a keyless, OpenAI-compatible API that is ideal for testing and light usage. By routing non-critical requests to this endpoint, you can reduce expenses without sacrificing functionality. Paid endpoints can be reserved for high-priority or compute-intensive tasks. See Cheap Proxy vs Official API for more context.

When integrating paid endpoints, ensure that you handle authentication and rate limits correctly. Each provider may have different requirements for API keys and usage quotas. A unified gateway should abstract these details, allowing you to switch between providers seamlessly. This flexibility is crucial when pricing or availability changes for one provider, as you can redirect traffic without modifying your application code, ensuring business continuity.

Cost Optimization

Cost optimization involves routing requests to the most cost-effective model for each task. For example, sending simple queries to smaller models and complex reasoning tasks to larger ones. This strategy reduces overall API costs while maintaining response quality, making it ideal for applications with variable workloads and budget constraints.

Authentication Management

Authentication management centralizes API keys and credentials for all supported models. This simplifies key rotation and security updates. By storing keys in a secure vault, you reduce the risk of exposure and make it easier to manage access across different environments, ensuring that only authorized requests reach the underlying models.

  • Identify suitable use cases for free vs. paid endpoints
  • Implement cost-aware routing logic
  • Centralize API key management
  • Monitor usage and costs per model
async def get_endpoint(model: str, is_paid: bool) -> str:
    if is_paid:
        return f"https://api.paid-provider.com/v1/{model}"
    else:
        return "https://api.deepseekapikeyfree.com/v1/chat/completions"

Handling Streaming and SSE

Streaming responses are essential for providing a smooth user experience in chat interfaces. The gateway must support Server-Sent Events (SSE) to forward streaming data from the underlying model to the client. This requires parsing the SSE stream, extracting the content chunks, and re-emitting them in the standardized format. Proper handling of streaming ensures that users see responses in real-time, reducing perceived latency and improving engagement.

In addition to content streaming, the gateway should handle metadata updates, such as token usage and finish reasons. These updates are often sent as separate SSE events and must be forwarded to the client without disrupting the content stream. Implementing a robust streaming handler ensures that your application can handle both text and metadata updates seamlessly, providing a complete picture of the request lifecycle.

SSE Parsing

SSE parsing involves reading the stream line by line and extracting the data payload. The gateway must handle edge cases like partial lines, encoding issues, and stream interruptions. A reliable parser ensures that no data is lost during transmission, maintaining the integrity of the response and ensuring that the client receives a complete message.

Metadata Forwarding

Metadata forwarding involves extracting and re-emitting events like usage statistics and finish reasons. These events are crucial for tracking token consumption and understanding the model's behavior. By forwarding them accurately, you provide your application with the necessary data for analytics, billing, and debugging purposes.

  • Implement an SSE parser for streaming responses
  • Handle partial lines and encoding issues
  • Forward metadata events alongside content
  • Test streaming performance under load
async def stream_response(response: httpx.Response):
    async for line in response.aiter_lines():
        if line.startswith('data: '):
            data = line[6:]
            yield data
Server rack with active data transmission lights
Monitoring server performance and traffic

Error Handling and Retries

Error handling is critical for maintaining reliability in a multi-model gateway. When a model returns an error, the gateway should log the issue and attempt to retry with a different model or the same model after a delay. Implementing exponential backoff prevents overwhelming the failing model with rapid retries. This approach ensures that transient errors do not result in immediate failure for the user, improving the overall user experience.

The gateway should also handle specific error codes like 429 (rate limit) and 503 (service unavailable). For 429 errors, the gateway should respect the Retry-After header and wait before retrying. For 503 errors, a short delay before retrying is often sufficient. Proper error handling improves the user experience by providing clear feedback and recovering gracefully from disruptions, ensuring that your application remains resilient.

Exponential Backoff

Exponential backoff increases the delay between retries exponentially, reducing the load on failing models. This strategy prevents thundering herd problems and allows the model time to recover. Implementing a maximum retry limit ensures that the gateway does not retry indefinitely, providing a clear failure state when necessary and preventing resource exhaustion.

Error Logging

Error logging records details about each failure, including the model, error code, and timestamp. This data is invaluable for debugging and monitoring. By analyzing error logs, you can identify patterns and optimize your routing logic to avoid known issue points, ensuring that your gateway becomes more robust over time.

  • Implement exponential backoff for retries
  • Respect Retry-After headers for rate limits
  • Log errors with detailed context
  • Set maximum retry limits to prevent infinite loops
import time
import random

async def retry_request(func, max_retries=3):
    for i in range(max_retries):
        try:
            return await func()
        except Exception as e:
            if i == max_retries - 1:
                raise e
            wait_time = (2 ** i) + random.random()
            time.sleep(wait_time)

Monitoring and Observability

Monitoring and observability are essential for maintaining a healthy gateway. By tracking metrics like latency, error rates, and token usage, you can identify performance bottlenecks and optimize resource allocation. Implementing distributed tracing allows you to follow a request through the gateway and into the underlying model, providing visibility into where delays occur and helping you pinpoint issues quickly.

Logs should capture key details such as the model used, request size, response time, and status code. This data helps in debugging issues and understanding usage patterns. Regularly reviewing these metrics ensures that your gateway remains efficient and reliable, allowing you to make data-driven decisions about model selection, scaling, and cost optimization strategies.

Metrics Collection

Metrics collection involves tracking key performance indicators (KPIs) like request latency, error rates, and token consumption. These metrics provide insights into the gateway's health and performance, allowing you to set alerts and thresholds for proactive management and ensure that your infrastructure meets your application's requirements.

Distributed Tracing

Distributed tracing follows a request through multiple services, providing a visual representation of the request flow. This is crucial for identifying bottlenecks and understanding the impact of each component on overall performance. Tools like Jaeger or OpenTelemetry can be integrated to enable comprehensive tracing and provide deep insights into system behavior.

  • Track latency, error rates, and token usage
  • Implement distributed tracing for request flow
  • Set up alerts for critical metrics
  • Regularly review logs for pattern analysis
import time

def track_metrics(start_time, status_code):
    duration = time.time() - start_time
    print(f"Status: {status_code}, Duration: {duration}s")
Network diagram of model routing
Visualizing request flow through the gateway

Security and Access Control

Security is paramount when building a gateway that handles multiple API keys and user requests. Implementing access control ensures that only authorized users can route requests to specific models. This can be achieved through API keys, JWT tokens, or IP whitelisting. By restricting access, you prevent unauthorized usage and reduce the risk of abuse, ensuring that your resources are used efficiently and securely.

Additionally, the gateway should validate input data to prevent injection attacks and ensure that requests conform to the expected schema. Sanitizing input reduces the risk of malformed requests causing errors or security vulnerabilities. Regular security audits and updates keep your gateway resilient against emerging threats, ensuring that your application remains secure as new vulnerabilities are discovered.

API Key Management

API key management involves securely storing and rotating keys for each model. Using a vault service like HashiCorp Vault or AWS Secrets Manager ensures that keys are encrypted and accessible only to authorized services. Regular rotation reduces the risk of key compromise and ensures that your gateway remains secure over time.

Input Validation

Input validation ensures that requests conform to the expected schema and do not contain malicious payloads. By validating input at the gateway level, you reduce the load on downstream models and prevent potential security issues. Tools like Pydantic can be used for robust schema validation, ensuring that only valid requests are processed.

  • Implement API key authentication for access control
  • Validate input data against a schema
  • Rotate keys regularly to prevent compromise
  • Conduct regular security audits
from pydantic import BaseModel, validator

class RequestSchema(BaseModel):
    model: str
    messages: list

    @validator('model')
    def model_must_exist(cls, v):
        allowed_models = ['deepseek', 'qwen', 'glm']
        if v not in allowed_models:
            raise ValueError('Model not supported')
        return v

Testing and Deployment

Testing your gateway thoroughly before deployment ensures that it performs reliably under various conditions. Use load testing tools to simulate high traffic and identify bottlenecks. Test different models and configurations to ensure that routing logic works as expected. Automated tests can catch regressions and ensure that updates do not break existing functionality, providing confidence in your deployment process.

Deployment strategies like blue-green or canary releases allow you to roll out updates gradually, minimizing risk. By monitoring performance during the release, you can quickly rollback if issues arise. A well-tested and carefully deployed gateway ensures a smooth transition for your users and maintains service continuity, ensuring that your application remains available and responsive.

Load Testing

Load testing simulates high traffic to identify performance limits and bottlenecks. Tools like k6 or Locust can generate realistic traffic patterns, helping you understand how your gateway scales. This data is crucial for planning infrastructure and optimizing resource allocation, ensuring that your gateway can handle peak loads without degradation.

Deployment Strategies

Deployment strategies like blue-green or canary releases minimize risk by gradually rolling out changes. Blue-green deployment switches traffic between two identical environments, while canary releases route a small percentage of traffic to the new version. Both strategies allow for quick rollbacks if issues are detected, ensuring minimal disruption to users.

  • Conduct load testing to identify bottlenecks
  • Implement automated tests for regression detection
  • Use blue-green or canary deployment strategies
  • Monitor performance during deployment
import locust

class GatewayLoadTest(locust.HttpUser):
    @locust.task
    def send_request(self):
        self.client.post('/v1/chat/completions', json={'model': 'test', 'messages': []})
Dashboard showing gateway metrics
Observability dashboard for gateway monitoring
Try the free API

Test a bot reply before writing any code using our keyless DeepSeek API access.

Read also