Building a Proxy to Integrate Third-Party LLMs with AI Coding Tools
This article provides a proxy solution for developers looking to integrate command-line AI coding tools with third-party large language models (LLMs). It covers environment setup, credential verification, protocol translation, streaming output, error handling, and security configuration to help you successfully route native tool requests to your desired models.
This article is for developers who want to enable command-line AI coding tools to call third-party large language models (LLMs). The native request formats used here are hypothetical examples; actual fields should be based on packet captures or logs from your specific tool. The complete solution covers environment preparation, credential verification, protocol translation, streaming output, error handling, and security configuration. Following these steps in order will get your setup running.
1. Environment Checklist
Before starting, confirm the following conditions:
- Python version 3.10 or higher. Run
python --versionto check. The example code uses runtime-evaluated type hints likestr | None, which will cause errors on interpreters older than 3.10. - The command-line tool can be invoked directly. Run
which tool_name(orwhere tool_nameon Windows) to locate the executable. Installation methods follow official documentation, typically via system package managers or official scripts. - Create an isolated virtual environment to avoid dependency conflicts:
python -m venv .venvsource .venv/bin/activate # On Windows use .venv\Scripts\activatepip install fastapi uvicorn httpx
FastAPI automatically installs pydantic, so a separate installation is unnecessary for this example. httpx is an asynchronous HTTP client responsible for sending requests to the third-party API.
2. Fetch and Verify Third-Party Model Credentials
Calling a third-party model requires three pieces of information. Verify each item before writing it into the code.
| Credential | Purpose | Format | Verification Point | Storage |
|---|---|---|---|---|
| API Key | Authenticates caller identity and serves as a billing basis | Depends on the provider’s console, usually a fixed prefix plus random characters | Check if the account has access to the target model and sufficient quota | Store only in environment variables or a secret management service |
| API URL | Endpoint address for the model | Typically provider domain plus a path like /v1/chat/completions |
Ensure the version and path match the provider’s documentation | Can be stored in config, but must not contain the API key |
| Model Name | Specifies the exact model to call | Use the exact name from the provider’s model list | Verify the name is available for the current account | Can be stored in config |
A common issue is an incorrect API URL path. Missing a version segment or adding an extra slash will result in a 404 error. Cross-check the full address against the provider’s documentation character by character.
3. Protocol Differences and Translation Strategy
AI coding tools typically use their own native formats, while most third-party services adopt standard compatible formats. The two differ in the following areas:
- System prompt location: Native formats might place it in a top-level field, while standard formats usually treat it as a message with the
systemrole. - Message content shape: Native formats might use a list of content blocks, whereas standard formats generally use a string.
- Role enums: The names and allowed values for roles may differ.
- Parameter naming: Fields like temperature or maximum generation length may have different names.
- Response structure: Standard formats place text in
choices[0].message.content, while native tools might expect a different nesting level. - Streaming events: SSE event names and data structures differ.
- Authentication: Some services use the
Authorization: Bearerheader, while others useapi-keyorx-api-key.
The proxy workflow consists of four steps:
- Request interception: The proxy listens on a local port and receives the native request from the tool.
- Forward translation: Parses the native request, extracts the system prompt, conversation history, and user input, and assembles it into the standard format.
- Request forwarding: Adds authentication headers and sends the translated request to the third-party endpoint.
- Reverse translation: Rewrites the standard format response back into the native format the tool expects, and returns it.
4. Field Mapping and Translation Functions
The following table lists the mapping rules used in the example. Native field names are hypothetical; replace them with the actual fields captured from your tool.
| Native Field (Example) | Standard Field | Translation Rule | Default Value |
|---|---|---|---|
| system (top-level string) | A message with role system | Insert at the beginning of the message list if not empty | None |
| messages role | messages role | Only user and assistant are allowed; others throw an error |
user |
| messages content (string or list of content blocks) | messages content (string) | If a list, extract and concatenate text from blocks where type is text | Empty string |
| temperature | temperature | Pass through directly | 0.7 |
| max_tokens | max_tokens | Pass through directly; provider will return error if exceeded | 4096 |
| stream | stream | Boolean | false |
| model (name passed by tool) | model | Ignored; uniformly use MODEL_NAME from config | None |
The proxy.py below implements the translation above, including auth configuration, retries, and error mapping. All sensitive values are read from environment variables.
import asyncioimport jsonimport osfrom typing import Anyimport httpxfrom fastapi import FastAPI, Requestfrom fastapi.responses import JSONResponse, StreamingResponseAPI_URL = os.environ["THIRD_PARTY_API_URL"]API_KEY = os.environ["THIRD_PARTY_API_KEY"]MODEL_NAME = os.environ["THIRD_PARTY_MODEL"]AUTH_MODE = os.environ.get("THIRD_PARTY_AUTH_MODE", "bearer") # bearer | api-key | x-api-keyDEFAULT_MAX_TOKENS = 4096DEFAULT_TEMPERATURE = 0.7MAX_RETRIES = 3RETRY_STATUS = {429, 500, 502, 503, 504}STOP_REASON_MAP = {"stop": "end_turn", "length": "max_tokens"}class UpstreamError(Exception):def __init__(self, status: int, detail: str):super().__init__(detail)self.status = statusself.detail = detaildef build_auth_headers(mode: str, key: str) -> dict[str, str]:if mode == "bearer":return {"Authorization": f"Bearer {key}"}if mode == "api-key":return {"api-key": key}if mode == "x-api-key":return {"x-api-key": key}raise ValueError(f"Unsupported auth mode: {mode}")def convert_request(native: dict[str, Any]) -> dict[str, Any]:messages: list[dict[str, str]] = []system_prompt = native.get("system")if system_prompt:messages.append({"role": "system", "content": system_prompt})for msg in native.get("messages", []):role = msg.get("role", "user")if role not in ("user", "assistant"):raise ValueError(f"Unrecognized role: {role}")content = msg.get("content", "")if isinstance(content, list):content = "".join(block.get("text", "")for block in contentif block.get("type") == "text")messages.append({"role": role, "content": content})return {"model": MODEL_NAME,"messages": messages,"temperature": native.get("temperature", DEFAULT_TEMPERATURE),"max_tokens": native.get("max_tokens", DEFAULT_MAX_TOKENS),"stream": bool(native.get("stream", False)),}async def forward_request(payload: dict[str, Any]) -> dict[str, Any]:headers = {"Content-Type": "application/json", **build_auth_headers(AUTH_MODE, API_KEY)}timeout = httpx.Timeout(60.0, connect=5.0)async with httpx.AsyncClient(timeout=timeout) as client:for attempt in range(MAX_RETRIES):is_last = attempt == MAX_RETRIES - 1try:resp = await client.post(API_URL, headers=headers, json=payload)except httpx.TransportError as exc: # Includes timeout and connection failureif is_last:raise UpstreamError(504, f"Upstream network error: {exc}") from excawait asyncio.sleep(2 ** attempt)continueif resp.status_code < 400:return resp.json()if resp.status_code in RETRY_STATUS and not is_last:await asyncio.sleep(2 ** attempt)continueraise UpstreamError(resp.status_code, resp.text[:500])raise UpstreamError(502, "Retries exhausted")def convert_response(upstream: dict[str, Any]) -> dict[str, Any]:choice = upstream["choices"][0]text = choice["message"].get("content") or ""usage = upstream.get("usage", {})finish = choice.get("finish_reason", "stop")return {"id": upstream.get("id", ""),"type": "message","role": "assistant","model": MODEL_NAME,"content": [{"type": "text", "text": text}],"stop_reason": STOP_REASON_MAP.get(finish, finish),"usage": {"input_tokens": usage.get("prompt_tokens", 0),"output_tokens": usage.get("completion_tokens", 0),},}def error_response(status: int, message: str) -> JSONResponse:return JSONResponse(status_code=status,content={"type": "error", "error": {"type": "proxy_error", "message": message}},)app = FastAPI()@app.post("/v1/messages")async def proxy(request: Request):try:native = await request.json()payload = convert_request(native)except ValueError as exc: # Includes JSON parsing errorsreturn error_response(400, str(exc))if payload["stream"]:return StreamingResponse(stream_upstream(payload), media_type="text/event-stream")try:upstream = await forward_request(payload)return JSONResponse(convert_response(upstream))except UpstreamError as exc:return error_response(exc.status, exc.detail)except (KeyError, IndexError) as exc:return error_response(502, f"Abnormal upstream response structure: {exc}")
The principle of error handling is to distinguish three scenarios. The first is client errors, such as invalid roles or JSON formatting errors, which return a 400 immediately without retry. The second is temporary failures, such as 429, 5xx, and timeouts, which are retried with exponential backoff up to three times. The third is permanent errors, like 401 or 404, which return immediately since retries won’t change the outcome.
5. Streaming Output Handling
In streaming mode, the standard API will return
