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 input as the unified input, output as the structured response, and SSE streaming events;
    • The backend only offers a “chat-completions-style” specification, using a messages array as input and choices as 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:

    1. Request translation: convert the inbound request into an upstream request;
    2. Response translation: convert the upstream response into an inbound response;
    3. 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:

    1. 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:

    1. python3 --version
    2. python3 -c "import sys; assert sys.version_info >= (3, 11), sys.version"
    3. 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:

    1. 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

    1. mkdir -p ~/projects/responses-chat-bridge
    2. cd ~/projects/responses-chat-bridge
    3. python3 -m venv .venv
    4. source .venv/bin/activate
    5. python3 -m pip install --upgrade pip==24.2
    6. python3 -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.

    1. import asyncio
    2. import json
    3. import os
    4. import tomllib
    5. from pathlib import Path
    6. from urllib.parse import urlsplit
    7. import httpx
    8. from fastapi import FastAPI, HTTPException, Request
    9. from fastapi.responses import JSONResponse, StreamingResponse
    10. CONFIG_PATH = os.environ.get("BRIDGE_CONFIG", "config.toml")
    11. CONFIG = tomllib.loads(Path(CONFIG_PATH).read_text(encoding="utf-8"))
    12. ROUTES = {
    13. urlsplit(route["incoming_url"]).path: route
    14. for route in CONFIG.get("routes", [])
    15. }
    16. app = FastAPI()
    17. def check_inbound(route, request):
    18. env_name = route.get("inbound_token_env")
    19. if not env_name:
    20. return
    21. expected = os.environ.get(env_name, "")
    22. if not expected:
    23. return
    24. if request.headers.get("authorization", "") != f"Bearer {expected}":
    25. raise HTTPException(status_code=401, detail="invalid inbound token")
    26. def translate_request(payload, route):
    27. messages = []
    28. system = payload.get("system")
    29. if system:
    30. messages.append({"role": "system", "content": system})
    31. input_value = payload.get("input", "")
    32. if isinstance(input_value, str):
    33. messages.append({"role": "user", "content": input_value})
    34. elif isinstance(input_value, list):
    35. for item in input_value:
    36. if isinstance(item, str):
    37. messages.append({"role": "user", "content": item})
    38. elif isinstance(item, dict):
    39. role = item.get("role", "user")
    40. content = item.get("content", "")
    41. if isinstance(content, list):
    42. content = "".join(
    43. part.get("text", "")
    44. for part in content
    45. if part.get("type") in ("input_text", "text")
    46. )
    47. messages.append({"role": role, "content": content})
    48. if not messages:
    49. messages = [{"role": "user", "content": ""}]
    50. upstream = {
    51. "model": payload.get("model") or route.get("default_model", "gpt-4o-mini"),
    52. "messages": messages,
    53. "stream": bool(payload.get("stream", route.get("stream", True))),
    54. "temperature": payload.get("temperature", route.get("temperature", 0.7)),
    55. }
    56. max_tokens = payload.get("max_output_tokens") or route.get("max_tokens")
    57. if max_tokens:
    58. upstream["max_tokens"] = int(max_tokens)
    59. return upstream
    60. async def forward(route, upstream):
    61. headers = {"content-type": "application/json"}
    62. key_env = route.get("api_key_env")
    63. api_key = os.environ.get(key_env, "") if key_env else ""
    64. if api_key:
    65. headers["authorization"] = f"Bearer {api_key}"
    66. timeout = httpx.Timeout(
    67. route.get("timeout_secs", 120),
    68. connect=10.0,
    69. read=route.get("first_byte_timeout_secs", 30),
    70. )
    71. attempts = int(route.get("max_retries", 0)) + 1
    72. retry_status = {429, 500, 502, 503, 504}
    73. last_exc = None
    74. for attempt in range(attempts):
    75. try:
    76. async with httpx.AsyncClient(timeout=timeout) as client:
    77. request = client.build_request(
    78. "POST",
    79. route["upstream_url"],
    80. json=upstream,
    81. headers=headers,
    82. )
    83. response = await client.send(request, stream=True)
    84. if response.status_code in retry_status and attempt < attempts - 1:
    85. await response.aclose()
    86. await asyncio.sleep(0.5)
    87. continue
    88. return response
    89. except httpx.TransportError as exc:
    90. last_exc = exc
    91. if attempt < attempts - 1:
    92. await asyncio.sleep(0.5)
    93. continue
    94. raise
    95. if last_exc:
    96. raise last_exc
    97. raise RuntimeError("forward failed")
    98. @app.post("/{full_path:path}")
    99. async def bridge(full_path: str, request: Request):
    100. route = ROUTES.get("/" + full_path)
    101. if route is None:
    102. return JSONResponse(
    103. status_code=404,
    104. content={"error": "route_not_found"},
    105. )
    106. check_inbound(route, request)
    107. try:
    108. payload = await request.json()
    109. except Exception:
    110. return JSONResponse(
    111. status_code=400,
    112. content={"error": "invalid_json"},
    113. )
    114. upstream = translate_request(payload, route)
    115. try:
    116. response = await forward(route, upstream)
    117. except Exception as exc:
    118. return JSONResponse(
    119. status_code=502,
    120. content={"error": "upstream_unreachable", "detail": str(exc)},
    121. )
    122. if response.status_code >= 400:
    123. raw = await response.aread()
    124. await response.aclose()
    125. return JSONResponse(
    126. status_code=502,
    127. content={
    128. "error": "upstream_error",
    129. "upstream_status": response.status_code,
    130. "detail": raw.decode("utf-8", errors="replace")[:2000],
    131. },
    132. )
    133. if not upstream["stream"]:
    134. raw = await response.aread()
    135. await response.aclose()
    136. data = json.loads(raw)
    137. choices = data.get("choices", [])
    138. text = ""
    139. if choices:
    140. text = choices[0].get("message", {}).get("content", "")
    141. return {
    142. "id": data.get("id", "resp_local"),
    143. "object": "response",
    144. "created_at": data.get("created", 0),
    145. "output": [
    146. {
    147. "type": "message",
    148. "role": "assistant",
    149. "content": [
    150. {
    151. "type": "output_text",
    152. "text": text,
    153. }
    154. ],
    155. }
    156. ],
    157. }
    158. async def event_stream():
    159. try:
    160. async for line in response.aiter_lines():
    161. if not line.startswith("data:"):
    162. continue
    163. data_str = line[5:].strip()
    164. if data_str == "[DONE]":
    165. yield "event: response.completed\ndata: {}\n\n"
    166. break
    167. try:
    168. chunk = json.loads(data_str)
    169. delta = chunk.get("choices", [{}])[0].get("delta", {}).get("content", "")
    170. except Exception:
    171. continue
    172. if delta:
    173. event_data = json.dumps(
    174. {
    175. "type": "response.output_text.delta",
    176. "delta": delta,
    177. },
    178. ensure_ascii=False,
    179. )
    180. yield f"event: response.output_text.delta\ndata: {event_data}\n\n"
    181. finally:
    182. await response.aclose()
    183. 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:

    1. cd ~/projects/responses-chat-bridge
    2. touch config.toml

    Write in the following content:

    1. [[routes]]
    2. name = "chat"
    3. incoming_url = "http://127.0.0.1:8787/chat/v1/responses"
    4. upstream_url = "https://api.openai.com/v1/chat/completions"
    5. api_key_env = "UPSTREAM_API_KEY"
    6. inbound_token_env = "BRIDGE_INBOUND_TOKEN"
    7. default_model = "gpt-4o-mini"
    8. timeout_secs = 120
    9. first_byte_timeout_secs = 30
    10. max_retries = 2
    11. stream = true
    12. temperature = 0.7
    13. max_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_secs to 60–120 seconds;
    • For streaming requests, pay special attention to first_byte_timeout_secs, typically 20–30 seconds;
    • Set max_retries to 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

    1. cd ~/projects/responses-chat-bridge
    2. export UPSTREAM_API_KEY="sk-demo-123456"
    3. export BRIDGE_INBOUND_TOKEN="local-demo-token"
    4. 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:

    1. uvicorn app:app --host 127.0.0.1 --port 8787

    Background run with logging:

    1. 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:

    1. curl -i http://127.0.0.1:8787/chat/v1/responses \
    2. -H "Authorization: Bearer local-demo-token" \
    3. -H "Content-Type: application/json" \
    4. -d '{"input":"hello","stream":false}'

    Success criteria:

    • The HTTP status code is 200;
    • Content-Type is application/json;
    • The response contains "object":"response";
    • The response contains an output array;
    • output[0].content[0].text contains the model’s returned text.

    7.4 Verify a Streaming Request

    1. curl -N http://127.0.0.1:8787/chat/v1/responses \
    2. -H "Authorization: Bearer local-demo-token" \
    3. -H "Content-Type: application/json" \
    4. -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.completed appears;
    • 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:

    1. tail -n 100 logs/bridge.log

    Common troubleshooting commands:

    1. ss -lntp | grep 8787
    2. printenv UPSTREAM_API_KEY
    3. printenv 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:

    1. Request translation: convert inbound fields into upstream fields;
    2. Response translation: convert upstream responses into the client protocol’s structure;
    3. 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.