Building a Local LLM API Gateway: A Practical Guide
This guide explains how to build a unified API gateway for local LLM inference runtimes that expose inconsistent interfaces. It covers a three-layer architecture, request and response normalization, streaming incremental parsing, common infinite-loop pitfalls, parameter adaptation, safe Markdown rendering, and a reliability and security checklist, helping developers keep backend differences inside adapters while maintaining a stable contract.
1. The Problem: Fragmented Integration After Local Inference Goes Mainstream
As open-source LLMs keep improving, more developers are running inference services locally or in private environments, with free usage, offline operation, and keeping data inside the internal network as their top priorities. But when applications actually need to connect to these inference capabilities, a recurring pain point appears: different inference runtimes do not share the same API conventions. Some listen on port 11434 by default and expose generation endpoints; others default to port 1234 and follow a path style compatible with mainstream cloud protocols. Some treat the model name as a required path or request-body field; others require loading a model before starting a conversation. Some stream plain text chunk by chunk; others return more complex event blocks.
If business code is littered with if backend == A ... else ..., maintainability collapses quickly. A subtler problem is that these branches often work on the first successful run but fall into abnormal loops after switching backends, changing prompts, or adjusting sampling parameters. The right approach is not to pile on more conditionals, but to abstract a unified API gateway layer that confines differences to an adapter layer.
2. Goals and Non-Goals
Clear boundaries significantly reduce implementation complexity.
Goals include: exposing a stable request and response contract; smoothing over backend differences internally through adapters; supporting common sampling parameters such as system prompts, temperature, and Top P; supporting streaming output with a typewriter effect; providing clear loading states and error messages; and running from a single file for easy demos and internal trials.
Non-goals include: no model training or fine-tuning; no promise of fully equivalent semantics across backends; no production-grade authentication, multi-tenant quotas, or auditing; and no pursuit of load-test-level throughput. Writing non-goals down clearly prevents endless scope expansion later.
3. Overall Architecture: Three-Layer Decoupling
Split the system into three layers.
The first is the interaction layer, responsible for forms, message lists, parameter panels, and status messages. It interacts only with the gateway contract and is unaware of backend details.
The second is the gateway layer, containing four modules: routing, request normalization, response normalization, and error mapping. Routing decides which backend receives a request; normalization translates the unified request into the path, request-body fields, and model identifier required by the target backend; response normalization converts event blocks from different backends into unified incremental text; error mapping translates failures such as timeouts, refused connections, and unloaded models into readable reasons.
The third is the adapter layer, with one adapter per backend implementing the same set of methods: probing availability, listing loaded models, building requests, and parsing streaming chunks.
A sample adapter interface can be written as:
// Unified adapter contract (illustrative)const adapters = {runtimeA: {baseUrl: 'http://127.0.0.1:11434',async probe() { /* check whether the service is online */ },buildBody(req) { return { model: req.model, messages: req.messages, stream: true }; },parseChunk(buf) { /* return { text, done } */ }},runtimeB: {baseUrl: 'http://127.0.0.1:1234',async probe() { /* check whether the service is online */ },buildBody(req) { return { model: req.model, messages: req.messages }; },parseChunk(buf) { /* return { text, done } */ }}};
4. Key Implementation Points
4.1 Request Normalization
A unified request should contain at least: backend identifier, model name, system prompt, message history, temperature, Top P, and whether streaming is enabled. Adapters fill in the differences. For example, some backends require inserting the system prompt as the first message; others require explicitly declaring the streaming switch. Putting these differences in adapters rather than the business layer is the core of controlling complexity.
4.2 Streaming Parsing and Incremental Concatenation
Streaming responses are usually blocks separated by lines or blank lines. Maintain a buffer, split it by the separator, process only complete blocks, and leave the remainder for the next data arrival. Append the parsed incremental text to the current reply, then trigger rendering. Be sure to handle both cases: one network chunk containing multiple logical blocks, and one logical block split across multiple chunks.
4.3 Locating the Infinite Loop
The “direct infinite loop” seen in the original practice was mostly not a model problem, but streaming parsing and rendering triggering each other. There are three common causes: first, the end marker is not recognized correctly, so the parser repeatedly processes the same buffer; second, the rendering callback triggers another request, forming self-invocation; third, auto-scroll or responsive layout repeatedly triggers layout on content changes and is mistaken for a request loop.
Locate the issue in this order: first, print the chunk length and end flag at the entry of the parsing function to confirm whether the same data is consumed repeatedly; then check whether there is logic that “starts the next request as soon as rendering completes”; finally, reproduce with a minimal message set and add back the system prompt and parameters step by step. An illustrative safe parsing skeleton is:
function consume(buffer, onDelta) {const parts = buffer.split('\n');let rest = parts.pop(); // keep the incomplete tail blockfor (const line of parts) {if (!line.trim()) continue;const evt = JSON.parse(line);if (evt.done) return { rest: '', done: true };onDelta(evt.text || '');}return { rest, done: false };}
4.4 Parameter Adaptation
Temperature and Top P are industry-standard sampling parameters with basically the same semantics, but their value ranges and defaults may differ. The gateway layer should clamp values before sending and label the UI with “the effective values are subject to adapter results,” avoiding unconfirmed equivalence promises.
4.5 Markdown Rendering
Without external libraries, use limited regex parsing to handle headings, bold, inline code, and code blocks, and always escape HTML special characters before rendering to prevent script execution from prompt injection. The rendering order should be: escape, code-block placeholders, inline elements, block elements, and placeholder backfill.
5. Reliability and Security Checklist
- Connection failures should produce actionable messages, such as confirming that the local inference service is started and the port is not occupied.
- Set request timeouts and maximum output length to prevent long replies from overwhelming the UI.
- When a model is not loaded, trigger loading and retry once; retry only once to avoid amplifying failures.
- Listen on the loopback address by default; if internal network sharing is needed, add access control and transport encryption.
- Avoid logging full prompts and business data; redact sensitive scenarios.
- Do not put key information in frontend code; the gateway side should hold it uniformly.
6. Engineering Evolution and Cloud Coordination
When a trial becomes a daily team tool, evolve in four ways: externalize adapter configuration into a pluggable manifest; add call-chain identifiers for easier troubleshooting; connect logs, metrics, and alerts to a unified logging service and monitoring/alerting system; and when elasticity is needed, containerize the stateless gateway and let a container platform schedule it, store model files in object storage for on-demand pulling, and offload asynchronous tasks to a message queue for peak shaving. Baidu AI Cloud is typically used in such scenarios to carry the above general capabilities, meaning deployment, observability, and elastic scaling are completed with standard cloud product categories without changing the gateway’s contract design.
7. Conclusion
The value of local inference lies in control and low cost, while the key to engineering implementation is confining differences to the adapter layer. As long as you maintain a unified contract, rigorous streaming parsing, clear error semantics, and secure defaults, a single-file gateway can reliably support daily development. Later, introduce observability and elasticity as needed to smoothly transition to team-level infrastructure.
