How to Connect AI Coding Tools to Third-Party LLMs: A Protocol Translation Proxy
This article explains why AI coding tools that follow the Anthropic Messages protocol cannot directly call OpenAI-compatible Chat Completions endpoints, and how to build a lightweight protocol translation proxy to bridge them. It covers environment setup, required provider information, forward and reverse format conversion, streaming event handling, security and compliance practices, stability optimizations, and a troubleshooting order for common errors.
1. Background: Why You Need a Protocol Translation Layer
By 2026, AI coding tools have become a standard part of the development workflow. However, many teams hit a practical constraint during adoption: the tool’s native model channel is restricted, or its default model does not fit the team’s needs in Chinese-language contexts, private coding standards, or specific language ecosystems. A natural next step is to switch to a third-party LLM service that the team has procured or self-hosted.
The problem is that mainstream AI coding tools generally follow the Messages protocol proposed by Anthropic, while the vast majority of third-party model services — including LLM services from major cloud providers and compatibility wrappers around open-source models — expose an OpenAI-compatible Chat Completions protocol. The two differ in request structure, system prompt placement, tool calling (Function Calling) representation, streaming event format, and stop_reason semantics. Simply changing the base_url will not work; you need an intermediate layer that translates in both directions.
This article calls that intermediate layer a protocol translation proxy. It is a lightweight service deployed locally or on an internal network, with a clear scope of responsibility: receive tool-side requests, convert them to a common compatible format, forward them, and convert the responses back.
2. Prerequisites: Prepare the Environment and Information
2.1 Runtime Environment
Python 3.10 or later is a hard requirement. The conversion scripts make heavy use of asynchronous I/O, X | None type annotations, and structural pattern matching, so older interpreters will fail with syntax errors. You can install Python from the official installer, a system package manager, or an Anaconda distribution, then confirm with python3 --version.
Installing the AI coding tool itself through a system package manager is recommended, as it makes unified upgrades and removal easier. There are three core dependencies: a web framework (to run the local service), an ASGI server (to host the async service), and an HTTP client (to forward requests). You can list them in requirements.txt and install them in one pass:
fastapi>=0.110uvicorn>=0.29httpx>=0.27pydantic>=2.6
2.2 Three Things to Confirm with the Model Provider
- API key: Must have permission to call the target model. Keep test and production keys separate.
- Endpoint URL: Usually in the form
https://<service-domain>/v1/chat/completions. Confirm whether HTTPS is mandatory and whether an internal network endpoint is available. - Model identifier: The model name defined by the provider. It must match the documentation exactly and is case-sensitive.
It is also worth confirming three additional items: the maximum context length per request, the per-minute request and token quota, and whether streaming responses and tool calling are supported. These three directly determine how you design rate limiting and fallback strategies later.
3. Core Implementation: Four Stages of the Format Translation Proxy
3.1 Breaking Down Responsibilities
The proxy’s processing chain has four steps: receive the tool-side request → convert the request body forward → forward it and handle authentication → convert the response back (including streaming).
3.2 Service Skeleton
from fastapi import FastAPI, Request, Headerfrom fastapi.responses import JSONResponse, StreamingResponseimport httpx, json, osapp = FastAPI()UPSTREAM = os.environ["MODEL_API_URL"]KEY = os.environ["MODEL_API_KEY"]@app.post("/v1/messages")async def messages(req: Request, x_api_key: str | None = Header(default=None)):body = await req.json()payload = to_openai(body) # forward conversionheaders = {"Authorization": f"Bearer {KEY}"}async with httpx.AsyncClient(timeout=120) as client:if body.get("stream"):return StreamingResponse(stream_upstream(client, payload, headers),media_type="text/event-stream")r = await client.post(UPSTREAM, json=payload, headers=headers)return JSONResponse(to_anthropic(r.json()))
3.3 Key Mappings for Forward Conversion
- System prompt: Anthropic treats
systemas a top-level field in the request body, while the OpenAI-compatible format treats it as the first message withrole="system", so it must be inserted at the front. - Message content: Anthropic’s
contentis a “block array” (text blocks, image blocks, tool result blocks) that must be flattened into a string or a compatible multimodal array. - Tool definitions:
input_schemamaps toparameters, and tool call results must be rewritten from blocks inside a user message into standalonerole="tool"messages, linked viatool_call_id. - Parameter mapping:
max_tokensis preserved;stop_sequencesmaps tostop;temperatureandtop_ppass through under the same names. - Authentication adaptation: Different providers require either
Authorization: Bearer {key}or a custom header (such asapi-keyorx-api-key), so this must be a configurable switch rather than hard-coded.
3.4 Reverse Conversion and Streaming
For non-streaming responses, choices[0].message must be restored into a content block array, and finish_reason must be mapped back to semantics such as end_turn, max_tokens, and tool_use.
Streaming is the part most likely to cause problems in practice. The tool side expects an event sequence such as message_start, content_block_start, content_block_delta, content_block_stop, message_delta, and message_stop, while the upstream sends incremental fragments in the form data: {...}. The proxy needs to maintain a lightweight state machine: synthesize message_start when the first fragment arrives, convert text increments into content_block_delta, accumulate tool call argument fragments by index, emit the closing events together at the end, and explicitly send data: [DONE].
4. Security and Compliance: A Layer You Cannot Skip
- Never hard-code keys: Inject keys through environment variables or a key management service, and never commit them to a repository. Credentials passed in from the tool side should be ignored or validated against a whitelist, so the proxy does not become an open internal proxy.
- Listen on the loopback address only: Bind to
127.0.0.1by default. If internal network sharing is required, access control and transport encryption must be added. - Data export and compliance: Before sending code snippets to an external service, confirm the provider’s data retention and training usage policies. For sensitive scenarios such as finance and government, prefer a compliant LLM service or a self-hosted deployment.
- Observability: Log the request ID, model name, token usage, time to first token, and error codes for each call, but do not log full prompt content.
5. Stability and Experience Optimization
- Timeouts and retries: Set connection and read timeouts separately, and apply exponential backoff retries only to idempotent connection errors to avoid duplicate billing.
- Rate limiting and queuing: Maintain a token bucket on the client side, and return an explicit error when the quota limit is hit so the tool side can take a fallback path instead of failing silently.
- Context trimming: When the input exceeds the upstream window, trim by “keeping the system prompt and the most recent turns while compressing the middle history,” which is more usable than returning an error outright.
- Prompt adaptation: Models differ considerably in how they follow instructions, so you can inject unified output constraints at the conversion layer (for example, “return only the complete modified file content”) to reduce repeated tuning.
- Caching: Short-term hash caching for identical request bodies can significantly reduce the cost of repeated explanation-style calls.
6. Common Failures and Troubleshooting Order
- 401/403: The authentication header format does not match the provider’s requirement, or the key lacks permission for that model.
- 400 invalid parameters: Usually caused by an incorrect tool definition structure or incomplete flattening of content blocks.
- No streaming output: SSE is not forwarded correctly,
[DONE]is missing, or the reverse event order does not match expectations. - Garbled or truncated Chinese text: Check the
max_tokensmapping and character encoding settings. - Missing response fields: The upstream returned an error body that was not handled by a separate branch, so accessing
choicesdirectly caused an exception.
When troubleshooting, first send a minimal non-streaming request to the proxy from the command line to confirm the chain works, then enable streaming and tool calling to narrow the problem down layer by layer.
7. Summary
Connecting a third-party model to an AI coding tool is essentially a problem of protocol adaptation and engineering governance: the conversion layer handles semantic alignment, the configuration layer handles switchable authentication and parameters, and the governance layer handles key security, quota control, and observability. Making these three layers solid lets coding tools use model capabilities that better fit the team’s needs, in a compliant, controllable, and maintainable way. For teams with highly sensitive data, combining a compliant LLM service with a self-hosted deployment on a container platform is the safer path.
