Building a Protocol Adapter Gateway for AI Coding Tools

    AI coding tools often speak a native streaming protocol, while many model services expose a generic chat-completion API. This article explains how to build a stateless adapter gateway that translates requests, responses, streaming events, and errors so those tools can call interchangeable compatible model services without changing the client.

    1. The real constraint is connectivity, not procurement

    Discussions about adopting AI coding tools often focus on how to obtain and pay for them. From an engineering perspective, the harder problem is usually technical. Three gaps commonly block a clean integration:

    1. Protocol coupling. Many coding tools expect their own message protocol: a separate system prompt, content as an array of blocks, structured tool-call blocks, and a final event that carries the stop reason and usage. Most model services instead use a generic chat-completion contract: a messages array, choices, and incremental delta chunks. Field layout, event order, and error semantics do not match.
    2. Capability differences. Context limits, streaming support, tool calling (function calling / tool use), concurrency, and rate limits vary by service. Swapping a backend without accounting for those differences breaks the toolchain.
    3. Stability and compliance. Cross-network latency jitter, key management, and retention of code and prompt data in logs all need to be designed in advance.

    This article treats the problem as a general engineering task: build a protocol adapter gateway so a tool that only speaks its native protocol can transparently use any model service that implements a compatible chat-completion API. The design is not tied to a specific vendor and can be moved to any compatible service.

    2. Architecture: three decoupled layers

    1. [AI coding tool / IDE plugin / CLI proxy]
    2. │ native protocol (HTTPS + streaming)
    3. ▼
    4. [Protocol adapter gateway] ← stateless, horizontally scalable
    5. request conversion → forward → response conversion (including a streaming state machine)
    6. │ generic chat-completion protocol
    7. ▼
    8. [Model service layer] ← replaceable

    Four design rules apply. The gateway is stateless: session state stays with the client so multiple replicas can run. Protocol conversion is separate from product semantics: the translation layer does not interpret tool-specific business meaning. Upstreams are pluggable: endpoints and model mappings change through configuration. The path is observable: structured logs, metrics, and trace identifiers are passed through.

    3. Environment: hard requirements and layered dependencies

    The runtime version is a hard constraint. The conversion layer uses async concurrency for many simultaneous streams, structured type annotations, and pattern matching. A runtime older than 3.10 will fail on syntax or type checks. Typical install paths are the official installer, the OS package manager (with the usual commands on macOS and Linux distributions), or a general version manager. In production, pin the runtime in a container image so local success does not turn into a runtime error after deploy.

    Install the tool side the same way: prefer a package manager or container image. Copying binaries by hand causes version drift and painful upgrades.

    Install dependencies in four layers by responsibility (the example uses a Python package manager; swap the ecosystem if you use another language):

    Layer Role Notes
    Web framework Routing and request validation Schema checks keep invalid payloads out of conversion logic
    ASGI server Production serving and concurrency Multiple workers plus connection reuse
    Async HTTP client Forwarding to the upstream Must support streaming reads and a connection pool
    Config and logging Environment loading and structured output Secrets come only from the environment or a secrets manager
    1. python -m venv .venv && source .venv/bin/activate
    2. pip install -r requirements.txt # pin every dependency; do not allow floating ranges

    Suggested layout:

    1. adapter-gateway/
    2. ├── app/main.py # entrypoint and routes
    3. ├── app/convert/request.py # native request → generic chat request
    4. ├── app/convert/response.py# generic response → native response (including streaming)
    5. ├── app/clients/upstream.py# upstream client: timeouts, retries, connection pool
    6. ├── app/config.py # configuration and secret loading
    7. ├── requirements.txt
    8. └── Dockerfile

    4. Three classes of facts to confirm before coding

    Fix the upstream contract before writing the first line of conversion code. Changing it later is expensive.

    • API key: confirm scope (allowed models, concurrency quota, rate limit) and whether tool calling is permitted.
    • Endpoint: confirm the base URL and chat-completion path, and whether the service is a compatibility layer. Some compatibility layers drop tool calling or streaming.
    • Model name mapping: upstream model IDs often differ from the tool’s default IDs. Use an explicit map. Do not pass through unknown names.
    • Extra contract details: context window, maximum output length, streaming support, parallel tool calls, rate-limit status codes, and recommended retry intervals.
    1. MODEL_MAP = {"tool-default-model": "vendor-model-a"} # explicit map; reject unknown models

    5. Request conversion: field alignment

    A typical native request includes model, max_tokens, a separate system prompt, messages (content may be text or an array of multimodal blocks), tools, tool_choice, and stream. A generic chat request carries every role inside messages, and tools are described as function schemas.

    Conversion rules:

    1. Place the system prompt as a leading system-role message, or write it into the upstream’s separate system field if that is what the contract requires.
    2. Flatten multimodal blocks into the string or array shape the upstream accepts. Unsupported block types must raise a clear error; do not drop them silently.
    3. Convert tools to function schemas. Map the three tool_choice states—required, forbidden, and named—one by one. If a state cannot be expressed, fall back to a prompt constraint and log it.
    4. Write tool results back as messages on the matching role. Call identifiers must match the request exactly.
    1. def to_upstream(req: NativeRequest, model_map: dict[str, str]) -> UpstreamRequest:
    2. msgs: list[dict] = []
    3. if req.system:
    4. msgs.append({"role": "system", "content": req.system})
    5. for m in req.messages:
    6. msgs.append({"role": m.role, "content": flatten_blocks(m.content)})
    7. return UpstreamRequest(
    8. model=model_map.get(req.model, ""),
    9. messages=msgs,
    10. max_tokens=req.max_tokens,
    11. tools=[t.to_function_schema() for t in (req.tools or [])],
    12. stream=req.stream,
    13. )

    6. Non-streaming responses and error semantics

    A non-streaming response must rebuild id, role, the content-block array, the stop reason, and usage. Stop reasons are the least compatible field, so map them explicitly:

    Upstream stop reason Native stop reason Client behavior
    stop end_turn Normal completion
    length max_tokens Truncated; continuation is possible
    tool_calls tool_use Run the tool and send the result back
    content_filter refusal Stop and surface a refusal

    Map error shapes as well: upstream 401/403 become authentication failures, 404 means the model or path does not exist, 429 means overload and should include a retry hint, and 5xx means the service is unavailable. Do not pass the raw upstream error body through. It can leak endpoint details and will often fail client parsing.

    7. Streaming conversion: the easiest place to get it wrong

    Streaming is the hard part. The native protocol is an ordered event stream: message_start → content_block_start → many content_block_delta events → content_block_stop → message_delta (stop reason and usage) → message_stop. The upstream only sends a sequence of incremental chunks. An explicit state machine must track whether the stream has started, the current content-block index, tool-call indexes, and buffered argument fragments.

    1. class StreamTranslator:
    2. def __init__(self, msg_id: str, model: str):
    3. self.msg_id, self.model = msg_id, model
    4. self.started = False
    5. self.block = 0
    6. self.tool_slots: dict[int, int] = {} # upstream index -> native index
    7. self.args_buf: dict[int, list[str]] = {}
    8. def on_chunk(self, c: UpstreamChunk) -> list[Event]:
    9. out: list[Event] = []
    10. if not self.started:
    11. out += [Event("message_start", {"message": {"id": self.msg_id, "model": self.model}}),
    12. Event("content_block_start", {"index": 0, "content_block": {"type": "text", "text": ""}})]
    13. self.started = True
    14. if c.text:
    15. out.append(Event("content_block_delta",
    16. {"index": 0, "delta": {"type": "text_delta", "text": c.text}}))
    17. for tc in c.tool_calls: # tool arguments arrive as JSON fragments; buffer them
    18. idx = self.tool_slots.setdefault(tc.index, len(self.tool_slots) + 1)
    19. self.args_buf.setdefault(idx, []).append(tc.arguments or "")
    20. out.append(Event("content_block_delta",
    21. {"index": idx, "delta": {"type": "input_json_delta",
    22. "partial_json": tc.arguments or ""}}))
    23. return out
    24. def on_end(self, reason: str, usage: Usage) -> list[Event]:
    25. return [Event("message_delta", {"delta": {"stop_reason": MAP[reason]},
    26. "usage": {"input_tokens": usage.prompt,
    27. "output_tokens": usage.completion}}),
    28. Event("message_stop", {})]

    Operational details: emit heartbeat comment frames on the stream so idle intermediaries do not drop the connection. If the upstream fails mid-stream, still emit the terminating events; otherwise the client waits forever. If a tool-call argument buffer is empty at the end, send {} rather than an empty string so the client’s JSON parser does not crash.

    8. Stability, security, and observability

    Stability. Reuse a connection pool. Retry only idempotent connection errors and 429/5xx responses, with exponential backoff. Once a streaming response has started, do not retry it. Set both a total timeout and a time-to-first-byte timeout. Budget-trim oversized context while keeping the system prompt and the most recent turns.

    Security. Inject secrets only from environment variables or a secrets manager. Do not put them in source or images. Authenticate the gateway itself, bind it to a private address, and use TLS end to end. Redact or hash prompts and code snippets in logs. Assess cross-border data flows against the rules of the relevant jurisdiction.

    Observability. Emit structured logs with request ID, model, time to first byte, total latency, input and output tokens, stop reason, and error code, and propagate trace IDs. The gateway can run as a container on a container platform, with a logging service and alerting. If you use Baidu AI Cloud’s container platform, logging, and monitoring products, those services can collect metrics and raise threshold alerts without a custom collection pipeline.

    9. Acceptance checklist and common failures

    Validate in order: non-streaming plain text → multi-turn chat → streaming plain text → tool calls (including parallel calls) → long-context truncation → rate limits and timeouts → authentication failure. Finish each stage before the next so failures do not stack.

    Common mappings: 401/403 usually means a bad key or insufficient scope; 404 usually means a wrong path or a missing model mapping; 400 often comes from flattened content blocks or an invalid tool schema; a silent stream should be checked for heartbeats and intermediary buffering; failed tool calls should be checked for call-ID consistency and argument buffering; context-limit errors should be checked to confirm the trim policy still keeps the system prompt.

    In short, an adapter gateway turns a product-access problem into a protocol-contract problem. If field mapping, the event state machine, error semantics, and operational controls are solid, an AI coding tool can reliably reuse any compatible model service and move between vendors.