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:

    1. Routing layer: selects upstream configuration based on path, tenant, or model name.
    2. Protocol conversion layer: converts inbound requests to upstream requests and converts upstream responses back to the inbound format.
    3. Streaming layer: handles SSE events, including deltas, completion, errors, and usage.
    4. Session state layer: maintains the mapping between previous_response_id and 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:

    1. node --version
    2. <package-manager> --version
    3. command -v <package-manager>
    4. 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:

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

    1. # Pin the version to avoid supply-chain drift
    2. <package-manager> install -g <adapter-package>@1.2.3
    3. # Verify source and integrity
    4. sha256sum <package-cache>/<adapter-package>-1.2.3.tgz
    5. # If the package provides a signature, verify the signature or source repository
    6. # Build the native bridge binary
    7. cd <global-modules>/<adapter-package>
    8. <package-manager> run build:bridge
    9. # Copy to the global executable directory
    10. sudo cp <build-output>/adapter-bridge /usr/local/bin/adapter-bridge
    11. chmod 755 /usr/local/bin/adapter-bridge
    12. adapter-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:

    1. <package-manager> uninstall -g <adapter-package>
    2. 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:

    1. [routers.upstream_a]
    2. incoming_url = "http://127.0.0.1:8787/upstream_a/v1/responses"
    3. upstream_url = "https://<your-endpoint>/v1/chat/completions"
    4. upstream_wire = "chat"
    5. upstream_model = "<mapped-model-name>"
    6. drop_tool_types = ["tool_search", "namespace"]
    7. timeout_seconds = 60
    8. retry_max = 2
    9. retry_on = ["429", "502", "503"]
    10. auth_secret_ref = "env:UPSTREAM_A_TOKEN"
    11. log_redaction = true
    12. [routers.upstream_a.features]
    13. enable_previous_response_id = true
    14. enable_extended_stream_events = true
    15. enable_reasoning_stream_events = true
    16. enable_tool_argument_stream_events = true
    17. tool_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

    1. def normalize(item):
    2. t = item.get("type")
    3. if t in ("input_text", "message"):
    4. return {
    5. "role": item.get("role", "user"),
    6. "content": item.get("text") or item.get("content") or ""
    7. }
    8. if t == "input_image":
    9. return {
    10. "role": "user",
    11. "content": [{
    12. "type": "image_url",
    13. "image_url": {"url": item["image_url"]}
    14. }]
    15. }
    16. if t == "function_call_output":
    17. return {
    18. "role": "tool",
    19. "tool_call_id": item.get("call_id"),
    20. "content": str(item.get("output", ""))
    21. }
    22. if t == "function_call":
    23. return {
    24. "role": "assistant",
    25. "tool_calls": [{
    26. "id": item.get("call_id"),
    27. "type": "function",
    28. "function": {
    29. "name": item.get("name"),
    30. "arguments": item.get("arguments", "{}")
    31. }
    32. }]
    33. }
    34. raise ValueError(f"unsupported input item: {t}")

    2. map_model: Model Name Mapping

    1. MODEL_MAP = {
    2. "gpt-4.1": "upstream-general",
    3. "claude-sonnet": "upstream-a",
    4. }
    5. def map_model(name):
    6. if not name:
    7. return "upstream-default"
    8. 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

    1. def convert_tools(tools, drop_types=()):
    2. result = []
    3. for tool in tools:
    4. if tool.get("type") in drop_types:
    5. continue
    6. fn = tool.get("function", tool)
    7. result.append({
    8. "type": "function",
    9. "function": {
    10. "name": fn.get("name"),
    11. "description": fn.get("description", ""),
    12. "parameters": fn.get("parameters", {})
    13. }
    14. })
    15. return result

    4. Header Adaptation: Only Changing Compatibility Fields

    Examples of headers that can be safely adjusted or normalized:

    • Content-Type: application/json
    • Accept: text/event-stream
    • User-Agent: protocol-adapter/1.2.3
    • X-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

    1. def transform_stream(chunk):
    2. if "error" in chunk:
    3. yield {
    4. "type": "error",
    5. "error": chunk["error"]
    6. }
    7. return
    8. if chunk.get("usage"):
    9. yield {
    10. "type": "usage",
    11. "usage": chunk["usage"]
    12. }
    13. choices = chunk.get("choices") or []
    14. if not choices:
    15. finish = chunk.get("finish_reason")
    16. if finish:
    17. yield {
    18. "type": "message_stop",
    19. "finish_reason": finish
    20. }
    21. return
    22. delta = choices[0].get("delta") or {}
    23. if delta.get("content"):
    24. yield {
    25. "type": "content_block_delta",
    26. "delta": {"text": delta["content"]}
    27. }
    28. reasoning = delta.get("reasoning_content") or delta.get("reasoning")
    29. if reasoning:
    30. yield {
    31. "type": "reasoning_delta",
    32. "delta": {"text": reasoning}
    33. }
    34. for tc in delta.get("tool_calls", []):
    35. function = tc.get("function") or {}
    36. yield {
    37. "type": "tool_argument_delta",
    38. "index": tc.get("index", 0),
    39. "delta": function.get("arguments", "")
    40. }
    41. finish = choices[0].get("finish_reason")
    42. if finish:
    43. yield {
    44. "type": "message_stop",
    45. "finish_reason": finish
    46. }

    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:

    1. curl -N http://127.0.0.1:8787/upstream_a/v1/responses \
    2. -H "Content-Type: application/json" \
    3. -d '{
    4. "model": "gpt-4.1",
    5. "input": [{"type": "input_text", "role": "user", "text": "你好"}],
    6. "stream": true
    7. }'

    Expected response fragment:

    1. data: {"type":"content_block_delta","delta":{"text":"你好"}}
    2. 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.