Building a Protocol Translation Proxy for LLM APIs: A Practical Guide
This guide explains how to build a lightweight protocol translation proxy that lets AI coding tools work with model services using a different API format. It covers the required runtime environment, upstream service details, the four steps of bidirectional request and response mapping, key engineering pitfalls such as streaming and tool calls, and a verification checklist for common errors.
1. Why You Need a Protocol Translation Proxy
Many development teams run into the same situation: their AI coding tool natively supports only one vendor’s model API protocol, but cost, data compliance, or specific model capabilities push them toward a model service from a different provider.
The problem is that mainstream model services generally fall into two API design styles. One uses a request structure centered on messages, with system as a separate field. The other follows the OpenAI-compatible format, where the system prompt is placed inside the messages array, and tool calls and streaming output use different field names.
When the tool and the model service speak different protocols, changing the configuration alone will not connect them. The most reliable engineering approach is to deploy a lightweight protocol translation proxy locally or on an internal network. The proxy exposes the interface shape the tool expects and performs two-way translation of requests and responses internally.
This proxy is essentially an adapter. It carries no business logic and only handles semantically equivalent protocol mapping. As a result, it is cheap to implement, easy to maintain, and a convenient place to add unified logging, rate limiting, and key management later.
2. Prerequisites: Three Categories of Preparation
2.1 Runtime Environment
The proxy relies on features such as asynchronous I/O and type annotations, so a runtime version of Python 3.10 or later is recommended to avoid syntax compatibility issues. You can install it from the official installer, a system-level package manager (common on macOS), or an Anaconda distribution. Installing the tool itself through a system package manager also makes later upgrades and removal easier.
A minimal working dependency set usually includes a web framework (to expose the interface), an ASGI server (to host the service), and an HTTP client (to forward upstream requests). Example install command:
pip install fastapi uvicorn httpx
2.2 Upstream Model Service Information
You need three key pieces of information from the model service provider, and none can be missing:
- API key: used for authentication; confirm that the key has permission to call the target model.
- Endpoint: usually in the form
https://<host>/v1/chat/completions. - Model name: the specific model identifier the provider publicly supports; it must match the documentation exactly and is case-sensitive.
2.3 Pointing the Client Configuration
Point the AI coding tool’s base URL at the local proxy (for example, http://127.0.0.1:8787) and use a placeholder value for the key. The real key exists only inside the proxy. This keeps keys from being scattered across multiple client configuration files.
3. Core Principle: Four Steps of Bidirectional Mapping
The proxy’s workflow breaks down into four steps, and understanding them covers all the essentials:
- Receive the request: listen on a local port and accept the native-format request body from the client.
- Convert the request: fold the standalone
systemfield into the message array, rename fields such as tool definitions and tool call results into the shape the upstream recognizes, and setstreamas needed. - Forward upstream: call the third-party endpoint with the authentication header. Note that authentication may be
Authorization: Bearer <key>or a custom header such asx-api-key, depending on the provider. - Convert the response back: reassemble the upstream
choicesstructure into thecontent,stop_reason,usage, and other fields the client expects. For streaming responses, translate each incremental chunk block by block while keeping event order and the termination marker consistent.
Sample Code (Structure Only, Not a Complete Implementation)
from fastapi import FastAPI, Request, Headerfrom fastapi.responses import JSONResponseimport httpxapp = FastAPI()UPSTREAM = "https://<host>/v1/chat/completions"REAL_KEY = "<your-key>"MODEL = "<model-name>"def to_openai(body: dict) -> dict:msgs = []if body.get("system"):msgs.append({"role": "system", "content": body["system"]})for m in body.get("messages", []):msgs.append({"role": m["role"], "content": m.get("content", "")})return {"model": MODEL, "messages": msgs,"max_tokens": body.get("max_tokens", 2048),"stream": bool(body.get("stream"))}@app.post("/v1/messages")async def proxy(req: Request, x_api_key: str = Header(None)):body = await req.json()payload = to_openai(body)async with httpx.AsyncClient(timeout=120) as c:r = await c.post(UPSTREAM, json=payload,headers={"Authorization": f"Bearer {REAL_KEY}"})data = r.json()text = data["choices"][0]["message"]["content"]return JSONResponse({"id": "msg_local", "type": "message","role": "assistant","content": [{"type": "text", "text": text}],"stop_reason": "end_turn","usage": data.get("usage", {})})
4. Engineering Details That Are Easy to Overlook
- Streaming: a non-streaming implementation can only return the complete result, and some clients time out on long tasks. You need to parse the upstream incremental chunks, convert them into the client’s event sequence, and emit a final termination event.
- Tool calls: field names for tool definitions and parameter serialization differ on the two sides. If the model side does not support tools, the proxy should degrade gracefully by folding the tool descriptions into the prompt.
- Context length: when the client’s declared maximum context does not match the upstream model, the proxy should truncate or return an explicit error to avoid hard-to-diagnose 400 errors.
- Error pass-through: normalizing the upstream status code and error message into a structure the client can recognize is more helpful for troubleshooting than throwing an exception directly.
- Keys and observability: keep the real key only on the proxy side, and use logging and monitoring alerts to record request volume, latency, and failure rate. If you need multiple instances, you can deploy them on a container platform for unified release.
5. Verification and Troubleshooting Checklist
After starting the service with uvicorn app:app --port 8787, first verify connectivity with a minimal request, then enable streaming and tool calls step by step. Common failures map as follows: 401/403 usually indicate a key or permission problem; 404 typically means the endpoint is missing the /v1 prefix; a mismatched model name returns a parameter error; and when missing response fields cause client parsing to fail, first check whether the response conversion function covers all fields the client requires.
6. Summary
The value of a protocol translation proxy is decoupling “tool bound to model” into “tool programmed against a standard interface.” By focusing on the four essentials—environment, information, mapping, and authentication—you can build a stable, reusable model access layer in the time it takes to spend a modest amount of money. If you prefer to reduce self-built maintenance, you can also evaluate model services and gateway-style general capabilities offered by cloud vendors such as Baidu AI Cloud, using a unified access layer to handle protocol adaptation and key hosting.
