How to Connect OpenAI-Compatible APIs to LLM Coding Assistants with a Local Proxy Script
This article explains how to bridge a command-line AI coding assistant and any OpenAI-compatible model service using a lightweight local proxy. It covers why protocol conversion is needed, how to prepare the environment and gather model credentials, how to design and implement the proxy (message mapping, auth headers, streaming, tool calls), and how to validate and harden the setup for real-world use.
1. Background: Why You Need a Protocol Conversion Proxy
Command-line AI coding assistants typically communicate with models using a proprietary request/response format. In contrast, most mainstream model services and open-source inference servers expose the industry-standard OpenAI-compatible interface. The two differ in message structure, role definitions, tool-call representation, and how streaming output is framed, so a direct connection simply won’t work.
The solution is straightforward: run a lightweight HTTP service locally to act as a “translator.” The coding assistant sends requests to this local service, which converts the protocol, forwards the request to the real model endpoint, then converts the model’s response back and returns it to the assistant. From the tool’s perspective, it is still talking in a familiar protocol; from the model’s perspective, it receives a standard-format request. The whole process is transparent to both ends.
2. Environment Preparation
Before writing the script, get the base environment and model-side details ready.
2.1 Runtime Requirements
- Python version: 3.10 or later is recommended. The scripts use newer async syntax and type-annotation features, and older interpreters may throw syntax errors outright.
- Coding assistant tool: Install it per the official documentation and confirm it launches from the terminal. Make sure it supports a custom endpoint URL—this is the prerequisite for the whole approach, and most such tools support specifying it via environment variables or a config option.
- Dependencies: Install three core libraries with
pip install fastapi uvicorn httpx—FastAPI to build the local service, uvicorn as the ASGI runner, and httpx to forward requests with native streaming support.
2.2 Gather Key Model Information
Get the following three items from your model provider; none can be skipped:
- API Key: The credential used for authentication. Confirm your account has access to the model, and keep it secure—do not hardcode it into files that get committed to a repository.
- Endpoint URL: Usually a path like
https://<host>/v1/chat/completions. Note the difference between organization-level and application-level addresses. - Model name: The exact model identifier the provider supports. Some platforms require a full version number or a prefixed name; an incorrect value causes a “model not found” error.
3. Designing and Implementing the Proxy Script
3.1 Core Workflow
The proxy script closes a four-step loop:
- Receive the request: Listen on a local port (e.g.,
127.0.0.1:8080) and accept requests from the coding assistant. - Convert the format: Map the tool-side request body (message list, system prompt, tool definitions, sampling parameters, etc.) into the OpenAI-compatible format.
- Forward the request: Send it to the third-party endpoint via httpx with the correct auth headers.
- Convert the response back: Turn the returned OpenAI-format response (including streaming chunks) back into a structure the tool understands.
3.2 Key Implementation Points
- Message structure differences: The tool side often uses a standalone
systemfield, while in the target format the system prompt is an entry withrole: "system"inside the message list. During conversion, merge it into the beginning of the message array. - Auth header adaptation: Provider authentication generally falls into two mainstream styles:
Authorization: Bearer {key}andapi-key/x-api-key: {key}. The script should pick the right one for the actual provider, and ideally make it configurable. - Streaming response handling: Coding assistants generally rely on streaming output for a typewriter experience. The proxy must pass chunks through with
StreamingResponseand convert chunk by chunk between the two formats. End markers on either side (message-stop events,finish_reason,[DONE]) must be mapped correctly, or the tool will either wait indefinitely or disconnect early. - Tool-call mapping: To support the assistant running commands or editing files, the function/tool-call representations on the two sides differ and require extra structural mapping. The first version can get plain-text conversation working, then fill this in incrementally.
A minimal skeleton example (non-streaming path):
from fastapi import FastAPI, Requestimport httpxapp = FastAPI()API_URL = "https://your-provider/v1/chat/completions"API_KEY = "sk-xxxx" # Always use a real, valid configuration@app.post("/v1/messages")async def proxy(request: Request):body = await request.json()messages = [{"role": "system", "content": body.get("system", "")}]messages += body.get("messages", [])payload = {"model": "your-model-name","messages": messages,"max_tokens": body.get("max_tokens", 2048),}headers = {"Authorization": f"Bearer {API_KEY}"}async with httpx.AsyncClient(timeout=120) as client:resp = await client.post(API_URL, json=payload, headers=headers)data = resp.json()text = data["choices"][0]["message"]["content"]return {"id": data.get("id", "msg_0"),"content": [{"type": "text", "text": text}],"role": "assistant","stop_reason": "end_turn",}
Start it with uvicorn proxy:app --host 127.0.0.1 --port 8080.
4. Integration and Validation
- Point the coding assistant’s endpoint URL to
http://127.0.0.1:8080, and fill in the corresponding model name and API Key in its config. - First hit the local proxy directly with curl to verify the basic conversion logic is correct.
- Then start a simple conversation in the coding assistant and check the proxy logs to confirm both the request-in and response-out paths work.
- Finally, test real scenarios like long conversations, code generation, and multi-turn context, paying special attention to streaming cadence and whether session state is preserved.
5. Stability and Optimization Tips
- Error pass-through and retries: Detect upstream 429 (rate limit) and 5xx errors, return structured errors, and consider exponential-backoff retries to avoid crashing the tool side.
- Log redaction: Record metrics like request latency and token usage for troubleshooting, but never log the API Key or full conversation content in plaintext.
- Timeout configuration: Long-context inference can far exceed the default timeout, so set the httpx client read timeout to 120 seconds or more.
- Security boundary: Have the local service listen only on 127.0.0.1, and avoid exposing an unauthenticated proxy to the local network.
6. Summary
With a local proxy script of just over a hundred lines, you can free a command-line AI coding tool from a single model protocol and connect it to any OpenAI-compatible model service. The key to the whole approach comes down to three things: accurately understanding the field differences between the two protocols, correctly handling streaming frames, and properly managing credentials and the error path. Once you master this method, you can switch flexibly among multiple providers as needed and match your coding assistant with the model capabilities best suited to your scenario.
