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:
- 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
messagesarray,choices, and incrementaldeltachunks. Field layout, event order, and error semantics do not match. - 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.
- 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
[AI coding tool / IDE plugin / CLI proxy]│ native protocol (HTTPS + streaming)▼[Protocol adapter gateway] ← stateless, horizontally scalablerequest conversion → forward → response conversion (including a streaming state machine)│ generic chat-completion protocol▼[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 |
python -m venv .venv && source .venv/bin/activatepip install -r requirements.txt # pin every dependency; do not allow floating ranges
Suggested layout:
adapter-gateway/├── app/main.py # entrypoint and routes├── app/convert/request.py # native request → generic chat request├── app/convert/response.py# generic response → native response (including streaming)├── app/clients/upstream.py# upstream client: timeouts, retries, connection pool├── app/config.py # configuration and secret loading├── requirements.txt└── 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.
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:
- Place the
systemprompt as a leading system-role message, or write it into the upstream’s separate system field if that is what the contract requires. - 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.
- Convert
toolsto function schemas. Map the threetool_choicestates—required, forbidden, and named—one by one. If a state cannot be expressed, fall back to a prompt constraint and log it. - Write tool results back as messages on the matching role. Call identifiers must match the request exactly.
def to_upstream(req: NativeRequest, model_map: dict[str, str]) -> UpstreamRequest:msgs: list[dict] = []if req.system:msgs.append({"role": "system", "content": req.system})for m in req.messages:msgs.append({"role": m.role, "content": flatten_blocks(m.content)})return UpstreamRequest(model=model_map.get(req.model, ""),messages=msgs,max_tokens=req.max_tokens,tools=[t.to_function_schema() for t in (req.tools or [])],stream=req.stream,)
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.
class StreamTranslator:def __init__(self, msg_id: str, model: str):self.msg_id, self.model = msg_id, modelself.started = Falseself.block = 0self.tool_slots: dict[int, int] = {} # upstream index -> native indexself.args_buf: dict[int, list[str]] = {}def on_chunk(self, c: UpstreamChunk) -> list[Event]:out: list[Event] = []if not self.started:out += [Event("message_start", {"message": {"id": self.msg_id, "model": self.model}}),Event("content_block_start", {"index": 0, "content_block": {"type": "text", "text": ""}})]self.started = Trueif c.text:out.append(Event("content_block_delta",{"index": 0, "delta": {"type": "text_delta", "text": c.text}}))for tc in c.tool_calls: # tool arguments arrive as JSON fragments; buffer themidx = self.tool_slots.setdefault(tc.index, len(self.tool_slots) + 1)self.args_buf.setdefault(idx, []).append(tc.arguments or "")out.append(Event("content_block_delta",{"index": idx, "delta": {"type": "input_json_delta","partial_json": tc.arguments or ""}}))return outdef on_end(self, reason: str, usage: Usage) -> list[Event]:return [Event("message_delta", {"delta": {"stop_reason": MAP[reason]},"usage": {"input_tokens": usage.prompt,"output_tokens": usage.completion}}),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.
