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 --version to check. The example code uses runtime-evaluated type hints like str | None, which will cause errors on interpreters older than 3.10.
    • The command-line tool can be invoked directly. Run which tool_name (or where tool_name on 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:
    1. python -m venv .venv
    2. source .venv/bin/activate # On Windows use .venv\Scripts\activate
    3. pip 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 system role.
    • 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: Bearer header, while others use api-key or x-api-key.

    The proxy workflow consists of four steps:

    1. Request interception: The proxy listens on a local port and receives the native request from the tool.
    2. Forward translation: Parses the native request, extracts the system prompt, conversation history, and user input, and assembles it into the standard format.
    3. Request forwarding: Adds authentication headers and sends the translated request to the third-party endpoint.
    4. 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.

    1. import asyncio
    2. import json
    3. import os
    4. from typing import Any
    5. import httpx
    6. from fastapi import FastAPI, Request
    7. from fastapi.responses import JSONResponse, StreamingResponse
    8. API_URL = os.environ["THIRD_PARTY_API_URL"]
    9. API_KEY = os.environ["THIRD_PARTY_API_KEY"]
    10. MODEL_NAME = os.environ["THIRD_PARTY_MODEL"]
    11. AUTH_MODE = os.environ.get("THIRD_PARTY_AUTH_MODE", "bearer") # bearer | api-key | x-api-key
    12. DEFAULT_MAX_TOKENS = 4096
    13. DEFAULT_TEMPERATURE = 0.7
    14. MAX_RETRIES = 3
    15. RETRY_STATUS = {429, 500, 502, 503, 504}
    16. STOP_REASON_MAP = {"stop": "end_turn", "length": "max_tokens"}
    17. class UpstreamError(Exception):
    18. def __init__(self, status: int, detail: str):
    19. super().__init__(detail)
    20. self.status = status
    21. self.detail = detail
    22. def build_auth_headers(mode: str, key: str) -> dict[str, str]:
    23. if mode == "bearer":
    24. return {"Authorization": f"Bearer {key}"}
    25. if mode == "api-key":
    26. return {"api-key": key}
    27. if mode == "x-api-key":
    28. return {"x-api-key": key}
    29. raise ValueError(f"Unsupported auth mode: {mode}")
    30. def convert_request(native: dict[str, Any]) -> dict[str, Any]:
    31. messages: list[dict[str, str]] = []
    32. system_prompt = native.get("system")
    33. if system_prompt:
    34. messages.append({"role": "system", "content": system_prompt})
    35. for msg in native.get("messages", []):
    36. role = msg.get("role", "user")
    37. if role not in ("user", "assistant"):
    38. raise ValueError(f"Unrecognized role: {role}")
    39. content = msg.get("content", "")
    40. if isinstance(content, list):
    41. content = "".join(
    42. block.get("text", "")
    43. for block in content
    44. if block.get("type") == "text"
    45. )
    46. messages.append({"role": role, "content": content})
    47. return {
    48. "model": MODEL_NAME,
    49. "messages": messages,
    50. "temperature": native.get("temperature", DEFAULT_TEMPERATURE),
    51. "max_tokens": native.get("max_tokens", DEFAULT_MAX_TOKENS),
    52. "stream": bool(native.get("stream", False)),
    53. }
    54. async def forward_request(payload: dict[str, Any]) -> dict[str, Any]:
    55. headers = {"Content-Type": "application/json", **build_auth_headers(AUTH_MODE, API_KEY)}
    56. timeout = httpx.Timeout(60.0, connect=5.0)
    57. async with httpx.AsyncClient(timeout=timeout) as client:
    58. for attempt in range(MAX_RETRIES):
    59. is_last = attempt == MAX_RETRIES - 1
    60. try:
    61. resp = await client.post(API_URL, headers=headers, json=payload)
    62. except httpx.TransportError as exc: # Includes timeout and connection failure
    63. if is_last:
    64. raise UpstreamError(504, f"Upstream network error: {exc}") from exc
    65. await asyncio.sleep(2 ** attempt)
    66. continue
    67. if resp.status_code < 400:
    68. return resp.json()
    69. if resp.status_code in RETRY_STATUS and not is_last:
    70. await asyncio.sleep(2 ** attempt)
    71. continue
    72. raise UpstreamError(resp.status_code, resp.text[:500])
    73. raise UpstreamError(502, "Retries exhausted")
    74. def convert_response(upstream: dict[str, Any]) -> dict[str, Any]:
    75. choice = upstream["choices"][0]
    76. text = choice["message"].get("content") or ""
    77. usage = upstream.get("usage", {})
    78. finish = choice.get("finish_reason", "stop")
    79. return {
    80. "id": upstream.get("id", ""),
    81. "type": "message",
    82. "role": "assistant",
    83. "model": MODEL_NAME,
    84. "content": [{"type": "text", "text": text}],
    85. "stop_reason": STOP_REASON_MAP.get(finish, finish),
    86. "usage": {
    87. "input_tokens": usage.get("prompt_tokens", 0),
    88. "output_tokens": usage.get("completion_tokens", 0),
    89. },
    90. }
    91. def error_response(status: int, message: str) -> JSONResponse:
    92. return JSONResponse(
    93. status_code=status,
    94. content={"type": "error", "error": {"type": "proxy_error", "message": message}},
    95. )
    96. app = FastAPI()
    97. @app.post("/v1/messages")
    98. async def proxy(request: Request):
    99. try:
    100. native = await request.json()
    101. payload = convert_request(native)
    102. except ValueError as exc: # Includes JSON parsing errors
    103. return error_response(400, str(exc))
    104. if payload["stream"]:
    105. return StreamingResponse(stream_upstream(payload), media_type="text/event-stream")
    106. try:
    107. upstream = await forward_request(payload)
    108. return JSONResponse(convert_response(upstream))
    109. except UpstreamError as exc:
    110. return error_response(exc.status, exc.detail)
    111. except (KeyError, IndexError) as exc:
    112. 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