Building a Protocol Adapter Gateway for LLMs: Architecture and Streaming Implementation
This article explains how to build a protocol adapter gateway between API callers and model services, focusing on translating the Responses protocol to the Chat Completions protocol. It covers a field-level comparison of both protocols, a four-layer gateway architecture, environment setup, bridge service installation and rollback, TOML configuration, core conversion logic for inputs, models, tools, and streaming events, session state continuity, and deployment troubleshooting. Readers will find practical code examples and configuration patterns for maintaining stable access to heterogeneous upstream models.
1. Why Add a Gateway Between Callers and Model Services?
When IDE plugins, coding assistants, or custom AI agents need to call different model services, a common problem is that the caller uses the Responses protocol while the backend only supports the Chat Completions protocol. The two protocols differ significantly in request bodies, streaming events, tool calls, and session state. Modifying business code directly only increases coupling. A more robust approach is to add a protocol adapter gateway at the local or reverse-proxy layer, so callers keep using their familiar protocol while the gateway handles translation, routing, and stream conversion.
2. Field-Level Comparison of the Two Protocols
| Dimension | Responses | Chat Completions |
|---|---|---|
| Request body | Built around input items, which can include text, images, and function call results |
Built around a messages array of role-based messages |
| State continuity | Can reference the previous turn via previous_response_id |
Usually requires the caller to send the full history every time |
| Streaming events | More granular event types, such as content deltas, reasoning deltas, and tool argument deltas | Mainly uses a unified delta increment |
| Tool calls | Newer structures for tool declarations, call arguments, and result回传 | Commonly uses the tools + tool_calls function structure |
The value of the gateway is to make these field and event mappings testable and configurable, rather than scattering the differences across every business request.
3. Designing a Four-Layer Gateway Architecture
At minimum, split the gateway into four layers:
- Routing layer: selects upstream configuration based on path, tenant, or model name.
- Protocol conversion layer: converts inbound requests to upstream requests and converts upstream responses back to the inbound format.
- Streaming layer: handles SSE events, including deltas, completion, errors, and usage.
- Session state layer: maintains the mapping between
previous_response_idand upstream responses, and reconstructs history when the upstream does not support chained state.
After layering, each layer can be tested independently: routing tests whether forwarding is correct, conversion tests whether fields are mapped, streaming tests boundary events, and the state layer tests multi-turn context consistency.
4. Preparing the Runtime Environment and Checking PATH
If the gateway consists of a script-language main service and a native bridge binary, prepare the following:
- JS runtime and package manager: prefer an LTS version, such as Node 20.
- System-level build toolchain: used to compile the bridge binary.
- Operating system: Ubuntu 22.04/24.04 or macOS 13+; Windows users should prefer WSL2.
Environment readiness check commands:
node --version<package-manager> --versioncommand -v <package-manager>echo "$PATH"
If the compiler or build tools are not in PATH, compiling the bridge service will fail. You can temporarily add them to PATH:
export PATH="/opt/toolchain/bin:$PATH"
In production, write this into the shell configuration or system environment variables, and confirm that new terminals recognize it.
5. Installing, Building, Verifying, and Rolling Back the Bridge Service
The following flow applies to Linux, macOS, or WSL2. For other systems, use the officially supported executable directory.
# Pin the version to avoid supply-chain drift<package-manager> install -g <adapter-package>@1.2.3# Verify source and integritysha256sum <package-cache>/<adapter-package>-1.2.3.tgz# If the package provides a signature, verify the signature or source repository# Build the native bridge binarycd <global-modules>/<adapter-package><package-manager> run build:bridge# Copy to the global executable directorysudo cp <build-output>/adapter-bridge /usr/local/bin/adapter-bridgechmod 755 /usr/local/bin/adapter-bridgeadapter-bridge --version
Permission requirements: installing to a system-level directory usually requires write access; if using a user-level directory, ensure ~/.local/bin is in PATH. If the build fails, first check whether the compiler is installed, whether PATH includes the build tools, whether the dependency cache is corrupted, and whether the package version matches the runtime. Rollback or uninstall:
<package-manager> uninstall -g <adapter-package>sudo rm -f /usr/local/bin/adapter-bridge
Back up the old binary and configuration before upgrading, so you can recover if the new version fails.
6. Writing a Maintainable TOML Configuration
The configuration should cover routing, model mapping, tool filtering, timeouts, retries, credential references, and log redaction:
[routers.upstream_a]incoming_url = "http://127.0.0.1:8787/upstream_a/v1/responses"upstream_url = "https://<your-endpoint>/v1/chat/completions"upstream_wire = "chat"upstream_model = "<mapped-model-name>"drop_tool_types = ["tool_search", "namespace"]timeout_seconds = 60retry_max = 2retry_on = ["429", "502", "503"]auth_secret_ref = "env:UPSTREAM_A_TOKEN"log_redaction = true[routers.upstream_a.features]enable_previous_response_id = trueenable_extended_stream_events = trueenable_reasoning_stream_events = trueenable_tool_argument_stream_events = truetool_conversion_mode = "legacy_convert"
auth_secret_ref should be read from environment variables or a secret management system; do not write real tokens into the configuration file. When log_redaction is enabled, authorization, API keys, user content, and tool arguments should be masked.
7. Implementing Core Capabilities Verifiably
1. normalize: Normalizing Input Items into Messages
def normalize(item):t = item.get("type")if t in ("input_text", "message"):return {"role": item.get("role", "user"),"content": item.get("text") or item.get("content") or ""}if t == "input_image":return {"role": "user","content": [{"type": "image_url","image_url": {"url": item["image_url"]}}]}if t == "function_call_output":return {"role": "tool","tool_call_id": item.get("call_id"),"content": str(item.get("output", ""))}if t == "function_call":return {"role": "assistant","tool_calls": [{"id": item.get("call_id"),"type": "function","function": {"name": item.get("name"),"arguments": item.get("arguments", "{}")}}]}raise ValueError(f"unsupported input item: {t}")
2. map_model: Model Name Mapping
MODEL_MAP = {"gpt-4.1": "upstream-general","claude-sonnet": "upstream-a",}def map_model(name):if not name:return "upstream-default"return MODEL_MAP.get(name, name)
If the caller sends a model name that the upstream does not recognize, map it to a name the upstream recognizes; if mapping is impossible, return a clear error instead of failing silently.
3. convert_tools: Tool Structure Conversion
def convert_tools(tools, drop_types=()):result = []for tool in tools:if tool.get("type") in drop_types:continuefn = tool.get("function", tool)result.append({"type": "function","function": {"name": fn.get("name"),"description": fn.get("description", ""),"parameters": fn.get("parameters", {})}})return result
4. Header Adaptation: Only Changing Compatibility Fields
Examples of headers that can be safely adjusted or normalized:
Content-Type: application/jsonAccept: text/event-streamUser-Agent: protocol-adapter/1.2.3X-Request-ID: <uuid>Accept-Encoding: identity(temporarily useful during debugging)
Do not modify or forge Authorization, API keys, cookies, Host, Origin, Referer, or other fields used for authentication, authorization, or origin validation. Header adaptation is only for protocol compatibility and observability; it must not be used to bypass authentication, access control, or service limits.
5. Streaming Event Conversion: Handling Empty choices, Errors, and usage
def transform_stream(chunk):if "error" in chunk:yield {"type": "error","error": chunk["error"]}returnif chunk.get("usage"):yield {"type": "usage","usage": chunk["usage"]}choices = chunk.get("choices") or []if not choices:finish = chunk.get("finish_reason")if finish:yield {"type": "message_stop","finish_reason": finish}returndelta = choices[0].get("delta") or {}if delta.get("content"):yield {"type": "content_block_delta","delta": {"text": delta["content"]}}reasoning = delta.get("reasoning_content") or delta.get("reasoning")if reasoning:yield {"type": "reasoning_delta","delta": {"text": reasoning}}for tc in delta.get("tool_calls", []):function = tc.get("function") or {}yield {"type": "tool_argument_delta","index": tc.get("index", 0),"delta": function.get("arguments", "")}finish = choices[0].get("finish_reason")if finish:yield {"type": "message_stop","finish_reason": finish}
This prevents streaming parsing from crashing when the upstream returns only usage, empty choices, an error block, or terminates early.
6. Session State Continuity
When the upstream does not support previous_response_id, the gateway should store the inbound session ID, upstream response ID, message history, and tool result mapping. When the next request arrives, retrieve the history based on previous_response_id and append it to messages.
8. Deployment, Verification, and Quick Troubleshooting
Minimal request example:
curl -N http://127.0.0.1:8787/upstream_a/v1/responses \-H "Content-Type: application/json" \-d '{"model": "gpt-4.1","input": [{"type": "input_text", "role": "user", "text": "你好"}],"stream": true}'
Expected response fragment:
data: {"type":"content_block_delta","delta":{"text":"你好"}}data: {"type":"message_stop","finish_reason":"stop"}
Common error reference:
| Symptom | Possible cause | Resolution |
|---|---|---|
| Model name not recognized | upstream_model mapping not configured |
Add the mapping in MODEL_MAP |
| Tool arguments not closed | Upstream chunk ended before arguments were complete | Accumulate arguments by index, then validate after receiving finish_reason |
| Empty choices | Upstream returns only usage or a heartbeat | Ignore empty chunks, but record usage and finish_reason |
| 401/403 | Credentials not injected or mistakenly modified | Check auth_secret_ref; do not modify authentication headers |
| 429/503 | Upstream rate limiting or instability | Retry a limited number of times per retry_max with exponential backoff |
previous_response_id invalid |
Local session mapping lost | Fall back to sending full history and log a warning |
Deployment recommendation: first run a single request locally through the full chain, then connect real tools. Observability should at least record request ID, upstream latency, error codes, streaming event counts, and usage. For security, back up configuration files and restrict permissions; logs should be redacted. If the upstream officially provides a compatible gateway or reverse proxy, it can serve as an alternative; a custom gateway is better suited to scenarios requiring deep protocol translation, model mapping, and stream transformation.
9. Conclusion
A protocol adapter gateway converges the differences of heterogeneous model interfaces into a middle layer. As long as model mapping, input normalization, tool conversion, streaming boundaries, configuration validation, and rollback procedures are solid, callers can reliably connect to different upstreams and maintain maintainability as protocols evolve.
