Heterogeneous API Protocol Bridging: Making Incompatible Interfaces Work Together
As AI coding assistants, model services, and internal platforms multiply, developers frequently hit a compatibility wall: a client and a backend may implement different API protocols and simply cannot talk to each other. This article explains how to build a protocol bridging service that translates requests and responses between a Responses-style API and a Chat Completions-style API in both directions. You will learn how the two protocols differ in request fields, response shapes, and SSE streaming events; how a minimal, stateless bridge built on FastAPI, Uvicorn, and HTTPX can translate traffic; and how to configure routes, run local verification, and troubleshoot common issues. The guide also covers the security and deployment boundaries of protocol bridging, including when it is appropriate and when a full production gateway is required.
1. Background: Why Protocol Bridging Is Needed
As AI coding assistants, model services, and internal platforms keep multiplying, developers integrating different backends often run into one recurring problem: the client and the backend support different interface protocols, so requests cannot pass through directly.
Typical situations include:
- The client only supports a “responses-style” specification, using
inputas the unified input,outputas the structured response, and SSE streaming events; - The backend only offers a “chat-completions-style” specification, using a
messagesarray as input andchoicesas output; - One side upgrades and switches its default protocol, and the official documentation clearly states that the two protocols are not yet compatible.
Rather than waiting for one side to change, a more practical approach is to add a protocol bridging service in the middle layer to perform bidirectional conversion of request and response formats. Using the example project responses-chat-bridge, this article shows how to convert Responses-style requests into Chat Completions-style requests, and convert Chat Completions-style responses back into a format the client can recognize.
The applicable boundaries also matter: protocol bridging suits intranet debugging, low-concurrency integration, transitional compatibility, and local development. It is not suitable as a high-throughput production gateway on its own. A production-grade gateway additionally requires horizontal scaling, circuit breaking, rate limiting, fine-grained authentication, audit logging, and distributed tracing.
2. Protocol Difference Analysis
To bridge correctly, you must first understand the structural differences between the two protocols. This article uses two common interface types as an example: inbound is Responses-style, and the upstream is Chat Completions-style.
2.1 Request Structure Differences
| Inbound field or semantics | Upstream field or semantics | Conversion notes |
|---|---|---|
input string |
user message in messages |
Wrap the string as a user message |
input array |
messages array |
Convert roles and content item by item |
system |
system message in messages |
If the inbound request provides a system instruction, convert it to a system message first |
temperature |
temperature |
Same semantics, can be passed through directly |
max_output_tokens |
max_tokens |
Different field names, mapping required |
stream |
stream |
Determines whether SSE streaming is enabled |
| Tool calls, multimodal parts | Upstream extension fields | Not mapped in the example; must be extended separately in production |
2.2 Response Structure Differences
| Upstream field | Inbound field | Conversion notes |
|---|---|---|
choices[0].message.content |
output[0].content[0].text |
Non-streaming responses must be reassembled |
choices[0].delta.content |
response.output_text.delta event |
Streaming increments must be converted chunk by chunk |
data: [DONE] |
response.completed event |
The termination marker must be mapped, otherwise the client may wait indefinitely |
2.3 Streaming Event Differences
The two protocols differ in SSE event naming, chunk format, termination markers, and error events. The bridge cannot simply pass events through; it must perform event semantic mapping. The core work breaks down into three steps:
- Request translation: convert the inbound request into an upstream request;
- Response translation: convert the upstream response into an inbound response;
- Streaming event alignment: convert upstream SSE chunks into events the client protocol can recognize.
3. Overall Architecture
The bridging service typically runs as a local process, exposing an inbound endpoint and forwarding the converted request to the real upstream. The data flow is as follows:
Client → inbound address (local) → request format conversion → upstream address → response format conversion → client
Deployment recommendations:
- The client accesses
127.0.0.1:8787, avoiding direct exposure to the public internet; - The bridge listens only on the local loopback address;
- The upstream key is injected through environment variables;
- The inbound token is also injected through environment variables for simple verification;
- Logs are written to a local file for easier troubleshooting;
- If remote access is needed later, add an authentication layer, access control, TLS, and gateway policies.
Key design principles:
- Prefer stateless: the bridge layer should avoid storing session context, reducing complexity;
- Normalize errors: convert upstream errors into structures the client protocol can recognize;
- Stream compatibility: convert chunk by chunk to preserve first-byte latency and incremental pacing;
- Key isolation: upstream keys are never written to config files or printed to logs.
4. Preparing the Environment
This article’s example uses a local bridging service named responses-chat-bridge with the following stack:
- Bridge service:
responses-chat-bridge; - Runtime: Python 3.11 or later;
- Package manager: pip 24.2 or later;
- Web framework: FastAPI 0.115.6;
- ASGI server: Uvicorn 0.34.0;
- HTTP client: HTTPX 0.28.1;
- Build toolchain: no additional build toolchain is required, since the Python example does not need local binary compilation.
Version verification commands:
python3 --versionpython3 -c "import sys; assert sys.version_info >= (3, 11), sys.version"python3 -m pip --version
If your Python version is below 3.11, upgrade to 3.11 or later first. If your pip version is too old, run:
python3 -m pip install --upgrade pip==24.2
5. Installing the Bridge Service
The following commands use a macOS or Linux environment as an example. On Windows, use python -m venv .venv and activate it with .venv\Scripts\activate.
5.1 Create the Project Directory and Install Dependencies
mkdir -p ~/projects/responses-chat-bridgecd ~/projects/responses-chat-bridgepython3 -m venv .venvsource .venv/bin/activatepython3 -m pip install --upgrade pip==24.2python3 -m pip install fastapi==0.115.6 uvicorn==0.34.0 httpx==0.28.1
5.2 Create the Example Source Code
Create app.py in the project root and write in the following content. This file implements a minimal, runnable protocol bridging service: it receives Responses-style requests, converts them into Chat Completions-style requests, and converts the upstream responses back into a format the client can recognize.
import asyncioimport jsonimport osimport tomllibfrom pathlib import Pathfrom urllib.parse import urlsplitimport httpxfrom fastapi import FastAPI, HTTPException, Requestfrom fastapi.responses import JSONResponse, StreamingResponseCONFIG_PATH = os.environ.get("BRIDGE_CONFIG", "config.toml")CONFIG = tomllib.loads(Path(CONFIG_PATH).read_text(encoding="utf-8"))ROUTES = {urlsplit(route["incoming_url"]).path: routefor route in CONFIG.get("routes", [])}app = FastAPI()def check_inbound(route, request):env_name = route.get("inbound_token_env")if not env_name:returnexpected = os.environ.get(env_name, "")if not expected:returnif request.headers.get("authorization", "") != f"Bearer {expected}":raise HTTPException(status_code=401, detail="invalid inbound token")def translate_request(payload, route):messages = []system = payload.get("system")if system:messages.append({"role": "system", "content": system})input_value = payload.get("input", "")if isinstance(input_value, str):messages.append({"role": "user", "content": input_value})elif isinstance(input_value, list):for item in input_value:if isinstance(item, str):messages.append({"role": "user", "content": item})elif isinstance(item, dict):role = item.get("role", "user")content = item.get("content", "")if isinstance(content, list):content = "".join(part.get("text", "")for part in contentif part.get("type") in ("input_text", "text"))messages.append({"role": role, "content": content})if not messages:messages = [{"role": "user", "content": ""}]upstream = {"model": payload.get("model") or route.get("default_model", "gpt-4o-mini"),"messages": messages,"stream": bool(payload.get("stream", route.get("stream", True))),"temperature": payload.get("temperature", route.get("temperature", 0.7)),}max_tokens = payload.get("max_output_tokens") or route.get("max_tokens")if max_tokens:upstream["max_tokens"] = int(max_tokens)return upstreamasync def forward(route, upstream):headers = {"content-type": "application/json"}key_env = route.get("api_key_env")api_key = os.environ.get(key_env, "") if key_env else ""if api_key:headers["authorization"] = f"Bearer {api_key}"timeout = httpx.Timeout(route.get("timeout_secs", 120),connect=10.0,read=route.get("first_byte_timeout_secs", 30),)attempts = int(route.get("max_retries", 0)) + 1retry_status = {429, 500, 502, 503, 504}last_exc = Nonefor attempt in range(attempts):try:async with httpx.AsyncClient(timeout=timeout) as client:request = client.build_request("POST",route["upstream_url"],json=upstream,headers=headers,)response = await client.send(request, stream=True)if response.status_code in retry_status and attempt < attempts - 1:await response.aclose()await asyncio.sleep(0.5)continuereturn responseexcept httpx.TransportError as exc:last_exc = excif attempt < attempts - 1:await asyncio.sleep(0.5)continueraiseif last_exc:raise last_excraise RuntimeError("forward failed")@app.post("/{full_path:path}")async def bridge(full_path: str, request: Request):route = ROUTES.get("/" + full_path)if route is None:return JSONResponse(status_code=404,content={"error": "route_not_found"},)check_inbound(route, request)try:payload = await request.json()except Exception:return JSONResponse(status_code=400,content={"error": "invalid_json"},)upstream = translate_request(payload, route)try:response = await forward(route, upstream)except Exception as exc:return JSONResponse(status_code=502,content={"error": "upstream_unreachable", "detail": str(exc)},)if response.status_code >= 400:raw = await response.aread()await response.aclose()return JSONResponse(status_code=502,content={"error": "upstream_error","upstream_status": response.status_code,"detail": raw.decode("utf-8", errors="replace")[:2000],},)if not upstream["stream"]:raw = await response.aread()await response.aclose()data = json.loads(raw)choices = data.get("choices", [])text = ""if choices:text = choices[0].get("message", {}).get("content", "")return {"id": data.get("id", "resp_local"),"object": "response","created_at": data.get("created", 0),"output": [{"type": "message","role": "assistant","content": [{"type": "output_text","text": text,}],}],}async def event_stream():try:async for line in response.aiter_lines():if not line.startswith("data:"):continuedata_str = line[5:].strip()if data_str == "[DONE]":yield "event: response.completed\ndata: {}\n\n"breaktry:chunk = json.loads(data_str)delta = chunk.get("choices", [{}])[0].get("delta", {}).get("content", "")except Exception:continueif delta:event_data = json.dumps({"type": "response.output_text.delta","delta": delta,},ensure_ascii=False,)yield f"event: response.output_text.delta\ndata: {event_data}\n\n"finally:await response.aclose()return StreamingResponse(event_stream(), media_type="text/event-stream")
Before starting the service, complete the configuration file described in the next section.
6. Configuration File and Route Mapping
The bridging service defines routes through config.toml. Each route represents a mapping between one inbound address and one upstream address. Create the configuration file:
cd ~/projects/responses-chat-bridgetouch config.toml
Write in the following content:
[[routes]]name = "chat"incoming_url = "http://127.0.0.1:8787/chat/v1/responses"upstream_url = "https://api.openai.com/v1/chat/completions"api_key_env = "UPSTREAM_API_KEY"inbound_token_env = "BRIDGE_INBOUND_TOKEN"default_model = "gpt-4o-mini"timeout_secs = 120first_byte_timeout_secs = 30max_retries = 2stream = truetemperature = 0.7max_tokens = 1024
Configuration field descriptions:
| Field | Type | Default | Required | Description |
|---|---|---|---|---|
name |
string | none | No | Route name, for easier identification |
incoming_url |
string | none | Yes | The inbound address the client accesses; the example uses http://127.0.0.1:8787/chat/v1/responses |
upstream_url |
string | none | Yes | The real upstream service address; the example uses the Chat Completions interface |
api_key_env |
string | none | Yes | The environment variable name holding the upstream key; the example uses UPSTREAM_API_KEY |
inbound_token_env |
string | none | No | The environment variable name holding the inbound token; the example uses BRIDGE_INBOUND_TOKEN |
default_model |
string | gpt-4o-mini |
No | The default model used when the request does not specify one |
timeout_secs |
integer | 120 | No | Request timeout in seconds |
first_byte_timeout_secs |
integer | 30 | No | First-byte or per-read timeout in streaming scenarios, in seconds |
max_retries |
integer | 0 | No | Number of retries on failure, excluding the first request; a value of 2 is recommended |
stream |
boolean | true |
No | Whether to enable streaming responses by default |
temperature |
float | 0.7 | No | Default temperature parameter |
max_tokens |
integer | none | No | Default maximum generation length |
Timeout and retry recommendations:
- For ordinary requests, set
timeout_secsto 60–120 seconds; - For streaming requests, pay special attention to
first_byte_timeout_secs, typically 20–30 seconds; - Set
max_retriesto 1–2 to avoid infinite retries; - Once a streaming response has begun outputting, retries are not recommended, as they may cause duplicate content;
- If the upstream frequently returns 429, combine rate limiting and backoff strategies rather than simply increasing the retry count.
7. Startup and Verification
7.1 Inject Environment Variables
cd ~/projects/responses-chat-bridgeexport UPSTREAM_API_KEY="sk-demo-123456"export BRIDGE_INBOUND_TOKEN="local-demo-token"mkdir -p logs
Here, UPSTREAM_API_KEY is the upstream service key, and BRIDGE_INBOUND_TOKEN is the local token clients use when accessing the bridge service. The example values are for demonstration only; use real keys and tokens in actual environments.
7.2 Start the Service
Foreground debugging:
uvicorn app:app --host 127.0.0.1 --port 8787
Background run with logging:
nohup uvicorn app:app --host 127.0.0.1 --port 8787 > logs/bridge.log 2>&1 &
7.3 Verify a Non-Streaming Request
Run this in another terminal:
curl -i http://127.0.0.1:8787/chat/v1/responses \-H "Authorization: Bearer local-demo-token" \-H "Content-Type: application/json" \-d '{"input":"hello","stream":false}'
Success criteria:
- The HTTP status code is
200; Content-Typeisapplication/json;- The response contains
"object":"response"; - The response contains an
outputarray; output[0].content[0].textcontains the model’s returned text.
7.4 Verify a Streaming Request
curl -N http://127.0.0.1:8787/chat/v1/responses \-H "Authorization: Bearer local-demo-token" \-H "Content-Type: application/json" \-d '{"input":"Describe protocol bridging in one sentence.","stream":true}'
Success criteria:
- The response headers include
Content-Type: text/event-stream; - You can continuously see
event: response.output_text.delta; - Each
data:line contains JSON with incremental text; - Finally,
event: response.completedappears; - The client does not keep waiting due to a missing termination event.
7.5 Check Logs on Failure
If you started in the foreground, check the terminal output directly. If you started in the background, run:
tail -n 100 logs/bridge.log
Common troubleshooting commands:
ss -lntp | grep 8787printenv UPSTREAM_API_KEYprintenv BRIDGE_INBOUND_TOKEN
8. Common Issues and Troubleshooting Table
| Symptom | Possible cause | Check command | Fix | |
|---|---|---|---|---|
| Excessive first-byte latency | Bridge-layer buffering, slow upstream first packet, or unreasonable network timeout settings | curl -N http://127.0.0.1:8787/chat/v1/responses -H "Authorization: Bearer local-demo-token" -H "Content-Type: application/json" -d '{"input":"hello","stream":true}' |
Disable unnecessary buffering and forward chunk by chunk; adjust first_byte_timeout_secs; confirm upstream streaming capability |
|
| Streaming interrupted | Termination event not mapped, upstream disconnects early, or read timeout | tail -n 100 logs/bridge.log |
Confirm [DONE] is converted to response.completed; check network stability; adjust the read timeout appropriately |
|
| Authentication failure | Upstream key not injected, incorrect inbound token, or key printed/leaked | printenv UPSTREAM_API_KEY, printenv BRIDGE_INBOUND_TOKEN, curl -i http://127.0.0.1:8787/chat/v1/responses -H "Authorization: Bearer local-demo-token" -H "Content-Type: application/json" -d '{"input":"hello","stream":false}' |
Confirm environment variables are exported; confirm the request header uses the correct token; avoid printing keys in logs | |
| Missing fields | Incomplete request or response field mapping; tool calls or multimodal content not handled | Compare the request body with upstream logs; check logs/bridge.log |
Add field mappings in translate_request; add dedicated conversion logic for tool calls and multimodal content |
|
| Port in use | Port 8787 is already occupied by another process | `ss -lntp | grep 8787` | Stop the occupying process, or change the listening port and update incoming_url accordingly |
| Route not found | The request path does not match the incoming_url path |
curl -i http://127.0.0.1:8787/chat/v1/responses |
Confirm the client request path exactly matches incoming_url in the config |
|
| Security boundary risk | The bridge listens on a public address, or has no access control | `ss -lntp | grep 8787` | Listen only on 127.0.0.1; for remote access, add authentication, least privilege, log redaction, and access control |
Security best practices:
- Inject the upstream key only through environment variables; never write it into config files;
- Never print full keys, tokens, or sensitive request bodies in logs;
- The inbound token should be used only by controlled clients;
- The bridge service should listen only on the local loopback address by default;
- If remote access is required, add TLS, gateway authentication, access control, and least-privilege policies;
- Apply length limits to tool calls, multimodal content, and long text to prevent resource abuse.
9. Summary and FAQ
The essence of protocol bridging is to build a “translation middleware” layer between heterogeneous interfaces. Its value is not to replace either side’s capabilities, but to solve compatibility problems at a small engineering cost, allowing the client to cooperate smoothly with different backends.
Once you master the following three core capabilities, you can quickly apply them to similar protocol mismatch scenarios:
- Request translation: convert inbound fields into upstream fields;
- Response translation: convert upstream responses into the client protocol’s structure;
- Streaming event alignment: convert upstream SSE chunks into an event stream the client can recognize.
FAQ: What is heterogeneous API protocol bridging?
Heterogeneous API protocol bridging is a middle-layer adaptation approach. It receives the client’s request in its original protocol, converts it into a protocol the backend service understands, then converts the backend’s result back into a format the client can recognize.
FAQ: What scenarios is bridging suited for?
It is suited for intranet debugging, low-concurrency integration, transitional compatibility, local development, and temporary integration. It is not suitable as a high-throughput production gateway unless rate limiting, circuit breaking, monitoring, authentication, and horizontal scaling are added.
FAQ: How do you choose the right bridging solution?
Prefer solutions that are stateless, easy to configure, observable, and support stream conversion. Focus on four points: whether protocol mapping is complete, whether errors are normalized, whether keys are injected securely, and whether logs are easy to troubleshoot.
FAQ: What is the most common error during bridging?
The most common problems are missing fields, missing streaming termination events, authentication failures, and an overly broad security boundary. When troubleshooting, first confirm the request path, environment variables, log output, and field mapping table, then check network and timeout settings.
FAQ: What should you pay attention to in production?
In production, bring the bridging service into a unified observability system, including logs, metrics, alerting, and auditing; manage keys, tokens, timeouts, retries, rate limiting, and access control in a standardized way; and avoid exposing the bridging service directly to the public internet.
