Integrating Multiple Models into Your Editor: Configuration, API Keys, and Quota Tracking in Practice

    This article presents a practical approach to connecting multiple Large Language Models (LLMs) to your code editor for code generation, chat, and edits. It covers the essential setup steps, including a structured configuration file, secure API key injection through environment variables, a Python wrapper with timeout and retry logic, and an error-code troubleshooting guide. The article also introduces a quota tracking ledger and a simple scoring method to help you manage usage allowances and select the most appropriate model for specific development tasks.

    I. Prerequisites and Scope

    Many programming tasks benefit from using multiple AI models. Some models excel at generating well-structured code, others are better at understanding long contexts, and some support image inputs. By integrating these models directly into your editor, you can handle chat, code completion, and code modification in one environment, saving you the time spent switching between your editor and a web browser or manually copying context between tools.

    Before proceeding, ensure you have the following:

    • Editor: An extension that supports reading custom model endpoint configurations. The field names used in this article are examples; always refer to your extension’s documentation for actual field requirements.
    • Runtime Environment: Python 3.10 or higher with the requests library (version 2.31 or higher) installed.
    • Network: The machine must be able to access the service provider’s endpoint via HTTPS. If you are behind a corporate proxy, you need to allow the corresponding domain names.
    • Account: An API key created in the service provider’s console, and the target model must be activated.
    • API Compatibility: The service must be compatible with the OpenAI chat format, meaning it accepts model, messages, and max_tokens parameters and returns text in choices[0].message.content.
    • Permissions: The configuration file must be readable and writable by your user. The API key should be injected from your shell’s configuration or a CI secret store.

    This article focuses exclusively on non-streaming calls, where you make a request and wait for the complete response. Streaming output, which involves handling partial data chunks, is not covered here.

    Your editor extension can connect to the service provider directly or through a local gateway proxy. When connecting directly, the endpoint is set to the provider’s address, and the extension reads the API key from an environment variable. When using a gateway, the endpoint is the gateway’s address, and the key is stored within the gateway itself; the editor only needs the gateway address. The examples in this article show the direct connection method.

    If your service’s request structure differs from the OpenAI format, you will need an adaptation layer before the inference service to convert your requests and responses to the standard format.

    When using a corporate proxy, set the proxy variables in your environment. The requests library will read these two environment variables:

    1. export HTTPS_PROXY="http://proxy.example.com:8080"
    2. export NO_PROXY="localhost,127.0.0.1"

    Do not include usernames or passwords in the proxy address, for example, do not write http://user:key@proxy....

    II. Configuration File Structure

    The configuration file describes which model to call and how to call it, but it does not store the API key in plaintext. The endpoint, model id, and displayName in the example are placeholders and must be replaced with real values from your provider’s documentation.

    1. {
    2. "providerName": "multi-model-gateway",
    3. "endpoint": "https://<your-endpoint>/v1/chat/completions",
    4. "apiKeyRef": "env:LLM_API_KEY",
    5. "timeoutSeconds": 30,
    6. "maxRetries": 2,
    7. "models": [
    8. {
    9. "id": "example-large-model",
    10. "displayName": "Example Large Model",
    11. "contextWindow": 256000,
    12. "maxOutputTokens": 8192,
    13. "capabilities": {
    14. "toolCalling": true,
    15. "vision": false
    16. }
    17. },
    18. {
    19. "id": "example-small-model",
    20. "displayName": "Example Fast Model",
    21. "contextWindow": 32000,
    22. "maxOutputTokens": 4096,
    23. "capabilities": {
    24. "toolCalling": true,
    25. "vision": false
    26. }
    27. }
    28. ]
    29. }

    Here is a breakdown of each field:

    Field Required Example Description Troubleshooting
    providerName Yes multi-model-gateway A unique name to distinguish this endpoint. Duplicate names can cause configuration conflicts.
    endpoint Yes https://<your-endpoint>/v1/chat/completions The complete HTTPS address. The path must match your provider’s documentation. A missing /v1 or an incorrect path often results in a 404 error.
    apiKeyRef Yes env:LLM_API_KEY The name of an environment variable, prefixed with env:. Never write the key itself in this file. Storing a plaintext key is bad practice. If this happens, rotate the key immediately in your provider console.
    timeoutSeconds No 30 Maximum time to wait for a response. A value between 10 and 120 seconds is recommended; use a higher value for long outputs. The default is 30. A timeout that is too short may terminate the request before the model finishes, resulting in a timeout exception.
    maxRetries No 2 Number of retries on failure. A value between 0 and 3 is recommended. The default is 0. Only 429 and 5xx errors are retried. A high number can increase quota consumption and total wait time.
    models[].id Yes example-large-model Must exactly match the model name in your provider’s documentation (case-sensitive). Spelling errors typically return a 400 or 404 error.
    models[].displayName No Example Large Model Only used for display purposes in the UI. Does not affect API calls.
    models[].contextWindow Yes 256000 The maximum number of input and output tokens the model can handle in a single request. Ensure you reserve tokens for the output. If the input exceeds this limit, you need to truncate the context to avoid a 400 error.
    models[].maxOutputTokens Yes 8192 The maximum number of tokens for a single output. This should not exceed the provider’s limit or the contextWindow. Setting this too high might be rejected by the provider with a 400 error.
    models[].capabilities.toolCalling No true Indicates whether the model supports tool calling. If set to true but the model doesn’t support it, tool calls will fail.
    models[].capabilities.vision No false Indicates whether the model supports image inputs. If set to false, the extension should not send images.

    III. Injecting the API Key via Environment Variables

    The API key should have only one storage location: the environment variables. Never include it in configuration files, code, logs, screenshots, or chat records.

    First, create a dedicated environment file in your shell with restricted permissions:

    1. mkdir -p ~/.config/llm
    2. touch ~/.config/llm/env
    3. chmod 600 ~/.config/llm/env

    Open this file in an editor and add your API key:

    1. export LLM_API_KEY="<your-api-key-from-the-provider-console>"

    This method prevents the key from being saved to your command history. Next, load this file in your ~/.bashrc or ~/.zshrc:

    1. [ -f ~/.config/llm/env ] && . ~/.config/llm/env

    If your environment file is inside a project directory, be sure to add it to your .gitignore.

    In a CI (Continuous Integration) environment, store the key as a secret with the same name and grant access only to the pipelines that need it. Never use echo to print the variable in a pipeline script.

    To check if the variable is set, use a command that does not print its value:

    1. if [ -n "$LLM_API_KEY" ]; then echo "Set"; else echo "Not set"; fi

    The Python client will read the variable using the env: prefix and strip any leading or trailing whitespace. Extra newlines or spaces are a common cause of 401 errors.

    1. import os
    2. def resolve_api_key(api_key_ref: str) -> str:
    3. if not api_key_ref.startswith("env:"):
    4. raise ValueError("apiKeyRef must start with 'env:'")
    5. var_name = api_key_ref[len("env:"):]
    6. value = os.environ.get(var_name, "").strip()
    7. if not value:
    8. raise RuntimeError(f"Environment variable {var_name} is not set or is empty")
    9. return value

    The HTTP request header should look like this. The value is read from the environment variable at runtime and should never be hardcoded:

    1. POST /v1/chat/completions HTTP/1.1
    2. Host: <your-endpoint>
    3. Authorization: Bearer <value-read-from-environment>
    4. Content-Type: application/json

    Adhere to the following rules:

    • Never hardcode API keys.
    • Never commit keys. Configuration files and environment files should not be committed to your repository.
    • Never log keys. This includes printing request headers during debugging. Log only the URL and HTTP status code.
    • If you suspect a key has been leaked, revoke it immediately in the provider console and generate a new one.

    IV. Timeout/Retry Wrapper and Error Code Troubleshooting

    The wrapper function below loads the configuration, sends the request, and handles retries according to the rules.

    1. import json
    2. import time
    3. from pathlib import Path
    4. import requests
    5. RETRYABLE_STATUS = {429, 500, 502, 503, 504}
    6. def load_config(path: str = "llm_config.json") -> dict:
    7. return json.loads(Path(path).read_text(encoding="utf-8"))
    8. def chat(cfg: dict, model_id: str, messages: list, max_tokens: int = 1024) -> str:
    9. api_key = resolve_api_key(cfg["apiKeyRef"])
    10. headers = {
    11. "Authorization": f"Bearer {api_key}",
    12. "Content-Type": "application/json",
    13. }
    14. payload = {
    15. "model": model_id,
    16. "messages": messages,
    17. "max_tokens": max_tokens,
    18. }
    19. timeout = cfg.get("timeoutSeconds", 30)
    20. max_retries = cfg.get("maxRetries", 0)
    21. for attempt in range(max_retries + 1):
    22. resp = requests.post(
    23. cfg["endpoint"],
    24. headers=headers,
    25. json=payload,
    26. timeout=timeout,
    27. )
    28. if resp.status_code == 200:
    29. return resp.json()["choices"][0]["message"]["content"]
    30. is_last = attempt == max_retries
    31. if resp.status_code not in RETRYABLE_STATUS or is_last:
    32. # Only log the status code and endpoint, not the request headers
    33. raise RuntimeError(f"Request failed: HTTP {resp.status_code}, URL {cfg['endpoint']}")
    34. time.sleep(2 ** attempt) # Backoff interval: 1s, 2s, 4s
    35. raise RuntimeError("Retry count exhausted")

    Example usage:

    1. cfg = load_config()
    2. reply = chat(
    3. cfg,
    4. model_id="example-small-model",
    5. messages=[{"role": "user", "content": "Explain idempotency in one sentence."}],
    6. max_tokens=256,
    7. )
    8. print(reply)

    Here’s how the configuration items affect behavior:

    • timeoutSeconds is passed to the timeout parameter of the requests call. If the time to receive a full response exceeds this value, a timeout exception is raised. The wrapper does not automatically retry on timeout; that decision is left to the caller.
    • maxRetries determines the number of retry attempts. The total number of requests will be maxRetries + 1.
    • Only status codes 429 and 5xx are retried. Other 4xx errors indicate a problem with the request itself, and retrying is not useful.
    • The backoff interval grows exponentially. If a 429 response includes an integer-valued Retry-After header, you should use that value as the wait time instead of the default backoff.

    Be careful of two risks when implementing retries. First, on a 5xx response, the server may have already processed the request, and a retry could consume quota a second time. Second, a non-streaming request that receives partial output before an error should not be retried, as this could lead to duplicated or truncated content.

    Refer to the table below for common HTTP error codes and troubleshooting steps:

    Status Code Common Causes Troubleshooting Steps
    400 Incorrect model name; max_tokens exceeds maxOutputTokens; input exceeds contextWindow; messages role not accepted. 1. Verify models[].id against your provider’s docs. 2. Ensure max_tokens is not greater than maxOutputTokens. 3. Use only system, user, and assistant roles in messages. 4. Shorten the input.
    401 Environment variable not set or empty; API key is invalid or revoked; key has leading/trailing spaces or newlines. 1. Run the if check command to confirm the variable is set. 2. Reload your environment file in a new terminal. 3. Confirm the key is still valid in the provider console; regenerate it if necessary. 4. Check for extra newlines in your environment file.
    403 Account does not have the model enabled; permission or quota restrictions; regional policy restrictions. 1. Verify in the provider console that the model is active. 2. Check your account permissions. 3. Contact the provider for regional policy details.
    404 Incorrect endpoint path (e.g., missing /v1); model does not exist. 1. Verify the full address against the documentation. 2. Use the curl command below to test the path.
    429 Request frequency limit exceeded; quota exhausted. 1. Check your quota balance. 2. Reduce concurrency and add delays between requests. 3. If a Retry-After header is present, wait that long. 4. Check if maxRetries is set too high.
    5xx Server-side failure or overload. 1. Check the provider’s status page. 2. The wrapper will retry automatically. 3. If it keeps failing, switch to a backup model and note the time.

    You can use the following curl command to test your endpoint path. If the path is correct but the API key is missing, you’ll usually get a 401. If the path is wrong, you’ll get a 404. The -v flag is omitted to avoid printing headers to the terminal:

    1. curl -s -o /dev/null -w "%{http_code}\n" -X POST "https://<your-endpoint>/v1/chat/completions" -H "Content-Type: application/json"

    V. Quota Tracking and Model Selection

    Many providers offer trial or promotional credits that expire, metered by tokens or requests. If you only use models in a few scenarios, these credits may go unused before they expire. A quota ledger helps you assign ownership and visibility to every credit, ensuring it is used before its expiration date.

    The ledger should be sorted by expiration date, with the earliest expiration at the top. The fields are as follows:

    Field Description
    Provider The name of the service provider for the credit.
    Credit Name The name of the credit as shown in the provider console.
    Unit The unit of measurement (e.g., tokens or requests).
    Total Credits The total amount granted, as per the provider console.
    Start Date The date the credit becomes available.
    Expiration Date The date the credit expires.
    Used The amount used as of the last update.
    Remaining Calculated as Total Credits minus Used.
    Owner The person responsible for following up on this credit.
    Planned Action e.g., Prioritize use, migrate to a different task, request an extension, or review before expiration.
    Notes Any other relevant information.

    Example entry (values are placeholders):

    Provider Credit Name Unit Total Credits Start Date Expiration Date Used Remaining Owner Planned Action Notes
    <Provider A> <Credit Name> token <Total> 2026-01-01 2026-12-31 <Used> <Remaining> <Name> Prioritize use Update usage weekly

    Rules for maintaining the ledger:

    • Update the “Used” and “Remaining” columns weekly.
    • If credits remain 30 days before expiration, mark them as “to be used” and schedule a specific task to consume them.
    • After a credit expires, record why it went unused in a review and decide whether to migrate it to another task.
    • Track the date when a credit is fully exhausted to help debug potential 429 errors.

    When selecting a model for a task, a scoring system can help you make objective decisions instead of relying on intuition. The weights in the table below are examples; your team should adjust them based on your specific needs. Always measure latency in your own network environment, don’t rely on data from others.

    Dimension Example Weight Scoring Method
    Capability Fit 40% Test with representative tasks and record the pass rate.
    Context Length 20% Compare the contextWindow against the longest input for your tasks.
    Credit Validity 20% Check if the remaining credits and expiration date align with your task volume.
    Output Limit 10% Compare maxOutputTokens against the output length required by your tasks.
    Latency 10% Take multiple measurements and use the median value.

    Score each model using this table, select the highest-scoring model as the default for your task, and record the rationale for your choice in the configuration file.