Building an LLM API Protocol Adapter Bridge: A Practical Guide
As enterprises adopt large language models, a common engineering problem emerges: an application is built against one API specification, but the available model service follows a different one. They overlap in capability but differ in request structure, response events, authentication, and streaming protocols, so they cannot connect directly. This article explains why this mismatch happens, compares the two dominant interface styles—Chat Completions and Responses—and shows how to build a protocol adapter (or bridge) layer between the client and the upstream service. It includes a runnable Node.js example, a detailed look at streaming event repackaging, routing and configuration practices, troubleshooting tips, and observability guidance for production use. You will learn how to let existing clients talk to new upstream services without heavy rewrites while keeping selection freedom for the models you use.
1. Why LLM APIs Don’t Match
In enterprise AI applications, an increasingly common engineering problem is this: the application side has been developed against one interface specification, while the actually available model service follows a different interface convention. The two are semantically similar and overlap in capability, but because of differences in request body structure, response event format, authentication, and streaming protocol, they cannot be connected directly.
Many teams’ first reaction is “just switch to another model,” but in practice they are often constrained by cost, region, compliance, and provider availability, and must make an “existing client” work with a “new upstream service.” The essence of this problem is not model capability—it is a mismatch at the interface protocol level.
The solution is to insert a protocol adapter layer between the client and the upstream, also known as an Adapter or Bridge. It masquerades as the interface the client expects on the top side, and issues calls according to the upstream’s real interface on the bottom side. This way, neither end’s code needs major changes, and the adaptation logic is centralized in one place, making it easier to maintain, test, and reuse.
2. Differences Between the Two Dominant Interface Styles
To understand why adaptation is necessary, you first need to understand two common interface styles: the chat-completions-style interface and the responses-style interface. Before integrating, it is recommended to check the official documentation for Chat Completions and Responses to confirm field and event definitions, avoiding misunderstandings caused by version differences.
| Dimension | Chat Completions Style | Responses Style |
|---|---|---|
| State management | Usually stateless, one question one answer | More stateful and structured |
| Core request body | messages, model, sampling parameters |
input, model, structured input items |
| Tool calls | tools converted to function calls |
Built-in tool calls and structured events |
| Reasoning content | Relies on extension fields | Emphasizes thinking/reasoning |
| Streaming response | choices[].delta |
Events like response.output_text.delta |
| Use cases | Quick migration, existing ecosystem compatibility | Complex interactions, fine-grained event control |
The chat-completions-style interface is intuitive in semantics and mature in ecosystem; the responses-style interface is more expressive, but it differs markedly from the former in field naming, event models, and streaming chunk format. Therefore, when the client only understands the responses-style interface but the upstream only supports the chat-completions-style interface, an adaptation layer is needed.
3. Core Design Ideas of the Adapter Layer
A usable bridge service is typically built around three conversion stages:
- Inbound request conversion: Receive the client’s responses-style request and map its fields into the request body required by the upstream chat-completions-style interface. For example, convert input messages into a
messagesarray, merge system instructions into a system role, translate tool definitions into the upstream function schema, and pass through sampling parameters such astemperatureandmax_tokens. - Outbound upstream call: Issue the request with the correct authentication header, using the path and method the upstream expects. Keys should be injected from environment variables or a key management service, avoiding writing them in plaintext into code or configuration files.
- Return-path response conversion: Re-package the upstream result into the responses-style format the client expects. Non-streaming scenarios are relatively simple; streaming scenarios are the real focus.
4. Minimal Runnable Example: Building a Bridge Service with Node.js
Below is a real, runnable Node.js bridge example. It converts a simplified responses-style request into a Chat Completions request and repackages the upstream streaming result into downstream events. The example focuses on the main path; in production you can build on it to add multimodal support, tool calls, complex errors, and concurrency control.
1. Install Dependencies
mkdir bridge && cd bridgenpm init -ynpm install express axios cors toml
2. Write the Configuration File config.toml
[upstream]upstream_url = "https://<upstream-service-url>/v1/chat/completions"api_key_env = "UPSTREAM_API_KEY"stream = true
3. Write server.js
const express = require('express');const axios = require('axios');const cors = require('cors');const fs = require('fs');const toml = require('toml');const app = express();app.use(express.json({ limit: '4mb' }));app.use(cors());const cfg = toml.parse(fs.readFileSync('config.toml', 'utf8')).upstream;const apiKey = process.env[cfg.api_key_env || 'UPSTREAM_API_KEY'];function toChatRequest(body) {const messages = Array.isArray(body.input)? body.input.map(x => ({role: x.role || 'user',content: typeof x.content === 'string' ? x.content : JSON.stringify(x.content)})): body.messages || [];return {model: body.model,messages,temperature: body.temperature,max_tokens: body.max_tokens,stream: !!body.stream};}function sseWrite(res, event, data) {res.write(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`);}app.post('/v1/responses', async (req, res) => {try {const upstreamPayload = toChatRequest(req.body);const headers = { 'Content-Type': 'application/json' };if (apiKey) headers.Authorization = `Bearer ${apiKey}`;if (upstreamPayload.stream) {res.status(200);res.setHeader('Content-Type', 'text/event-stream');res.setHeader('Cache-Control', 'no-cache');res.setHeader('Connection', 'keep-alive');const up = await axios.post(cfg.upstream_url, upstreamPayload, {headers,responseType: 'stream'});let buffer = '';let completed = false;function complete(data) {if (completed) return;completed = true;sseWrite(res, 'response.completed', data);res.end();}up.data.on('data', chunk => {buffer += chunk.toString('utf8');const parts = buffer.split('\n\n');buffer = parts.pop();for (const part of parts) {const line = part.split('\n').find(l => l.startsWith('data:'));if (!line) continue;const raw = line.slice(5).trim();if (raw === '[DONE]') {complete({ done: true });return;}try {const obj = JSON.parse(raw);const delta = obj.choices?.[0]?.delta?.content;if (delta) {sseWrite(res, 'response.output_text.delta', { delta });}const usage = obj.usage;const finish = obj.choices?.[0]?.finish_reason;if (usage || finish) {complete({ finish_reason: finish || 'stop', usage: usage || {} });}} catch (e) {// Ignore unparseable keep-alive or non-standard events}}});up.data.on('end', () => complete({ done: true }));up.data.on('error', err => {if (!res.headersSent) {res.status(502).json({ error: String(err) });} else {complete({ done: true });}});} else {const r = await axios.post(cfg.upstream_url, upstreamPayload, { headers });const text = r.data.choices?.[0]?.message?.content || '';res.json({id: r.data.id || 'resp_local',object: 'response',output: [{type: 'message',role: 'assistant',content: [{ type: 'output_text', text }]}],usage: r.data.usage || {}});}} catch (err) {const status = err.response?.status || 502;res.status(status).json({error: {message: err.message,upstream: err.response?.data || null}});}});const port = process.env.PORT || 8080;app.listen(port, '0.0.0.0', () => {console.log(`adapter listening on ${port}`);});
4. Start and Test
export UPSTREAM_API_KEY='your-upstream-key'node server.js
The client can call it like this:
curl -N http://127.0.0.1:8080/v1/responses \-H 'Content-Type: application/json' \-d '{"model": "example-model","input": [{"role": "user", "content": "你好"}],"stream": true}'
5. Streaming Response Conversion: The Hardest and Most Critical Part
LLM conversations almost always return via streaming SSE. The adapter layer cannot simply pass through; it must perform “event repackaging”:
| Upstream Chat Completions event | Adapter handling | Downstream Responses event |
|---|---|---|
delta.content |
Read the text increment | response.output_text.delta |
tool_calls fragments |
Aggregate arguments by index | response.function_call.* |
usage statistics |
Map fields and position | response.completed |
finish_reason |
Align completion semantics | response.completed |
Key edge cases to handle include:
- Tool call argument fragment aggregation: The upstream often splits the arguments JSON into multiple chunks, so you need to accumulate
id,name, andargumentsbyindex, and invoke the callback only after receiving the completion marker. - Reasoning content passthrough: If the upstream returns reasoning/thinking fields, choose to pass them through or filter them according to the client’s capabilities.
- Error event normalization: Uniformly convert upstream error codes into an error structure the client can recognize, preventing the client from crashing on unknown events.
- Completion event alignment: Ensure at least one of
[DONE],finish_reason, orusagetriggers the final completion event.
6. Routing and Configuration Practices
A clear routing configuration should explicitly declare the “inbound-to-outbound” mapping and support multiple upstreams. Below is an example configuration; the addresses are placeholders, so replace them with actual values:
[router.upstream_a]incoming_url = "http://127.0.0.1:8080/v1/responses"upstream_url = "https://<upstream-service-url>/v1/chat/completions"inbound_protocol = "responses"outbound_protocol = "chat_completions"required = true[router.upstream_a.auth]api_key_env = "UPSTREAM_API_KEY"[router.upstream_a.streaming]enabled = truerepackage_events = true
Configuration practice points:
- Externalize keys: Inject them through environment variables or a key management service, following the principle of least privilege.
- Multiple upstreams in parallel: Mount multiple backends under different
routersections to enable canary switching and failover. - Timeouts and retries: Set reasonable timeouts for upstream calls, and perform a limited number of retries only for idempotent requests.
- Clear required fields:
upstream_urlandapi_key_envare usually required, whilestreamingcan be enabled as needed.
7. Common Troubleshooting
- Connection refused: Confirm that the adapter’s listening address matches the address the client accesses, and check whether the port is occupied.
- 401/403 authentication failure: Confirm the key has been injected and is visible to the process, and check whether the environment variable is empty.
- No streaming output or premature end: Check whether the upstream
[DONE]orfinish_reasonis correctly recognized. - Tool call arguments are null: Usually fragments were not aggregated; wait for the tool call completion marker before invoking the callback.
- High latency: Check whether a new connection is established for every request; you can introduce connection reuse and Keep-Alive.
- Client reports unknown events: Confirm whether downstream event types strictly match the client protocol; error events need to be normalized.
8. Observability and Production Readiness
The adapter layer sits between the application and the model and is the “bottleneck” of the whole path, so observability must be done well. It is recommended to uniformly collect the following metrics:
- Request volume (QPS)
- Success rate and error code distribution
- P50/P95/P99 latency
- Token consumption
- Upstream timeouts, rate-limit hits, and authentication failures
- Streaming repackaging exception counts
Example alerts you can set:
- P99 latency exceeds 5 seconds for 5 consecutive minutes
- Error rate exceeds 1% for 5 consecutive minutes
- A sudden spike in 401/403, suggesting a compromised key
- An increase in the missing-completion-event rate for streaming responses
On the deployment side, you can leverage the log services, monitoring and alerting, key management, and container orchestration capabilities offered by mainstream cloud platforms to achieve centralized collection and alerting, without building the entire infrastructure stack yourself. At the same time, make the adapter layer a stateless, horizontally scalable service, combined with health checks and auto-scaling, so it can handle production traffic fluctuations.
Conclusion
Protocol incompatibility may seem trivial, but it is a high-frequency obstacle in landing AI engineering. Rather than repeatedly compromising between the client and the upstream, it is better to build a protocol adapter bridge with a single responsibility that is testable and observable. By focusing on the three main lines—request mapping, call forwarding, and streaming repackaging—and supplementing them with proper key management, multi-upstream routing, and production-grade monitoring, you can make heterogeneous LLM services interoperate smoothly and preserve maximum selection freedom for your upstream applications.
