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
requestslibrary (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, andmax_tokensparameters and returns text inchoices[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:
export HTTPS_PROXY="http://proxy.example.com:8080"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.
{"providerName": "multi-model-gateway","endpoint": "https://<your-endpoint>/v1/chat/completions","apiKeyRef": "env:LLM_API_KEY","timeoutSeconds": 30,"maxRetries": 2,"models": [{"id": "example-large-model","displayName": "Example Large Model","contextWindow": 256000,"maxOutputTokens": 8192,"capabilities": {"toolCalling": true,"vision": false}},{"id": "example-small-model","displayName": "Example Fast Model","contextWindow": 32000,"maxOutputTokens": 4096,"capabilities": {"toolCalling": true,"vision": false}}]}
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:
mkdir -p ~/.config/llmtouch ~/.config/llm/envchmod 600 ~/.config/llm/env
Open this file in an editor and add your API key:
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:
[ -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:
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.
import osdef resolve_api_key(api_key_ref: str) -> str:if not api_key_ref.startswith("env:"):raise ValueError("apiKeyRef must start with 'env:'")var_name = api_key_ref[len("env:"):]value = os.environ.get(var_name, "").strip()if not value:raise RuntimeError(f"Environment variable {var_name} is not set or is empty")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:
POST /v1/chat/completions HTTP/1.1Host: <your-endpoint>Authorization: Bearer <value-read-from-environment>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.
import jsonimport timefrom pathlib import Pathimport requestsRETRYABLE_STATUS = {429, 500, 502, 503, 504}def load_config(path: str = "llm_config.json") -> dict:return json.loads(Path(path).read_text(encoding="utf-8"))def chat(cfg: dict, model_id: str, messages: list, max_tokens: int = 1024) -> str:api_key = resolve_api_key(cfg["apiKeyRef"])headers = {"Authorization": f"Bearer {api_key}","Content-Type": "application/json",}payload = {"model": model_id,"messages": messages,"max_tokens": max_tokens,}timeout = cfg.get("timeoutSeconds", 30)max_retries = cfg.get("maxRetries", 0)for attempt in range(max_retries + 1):resp = requests.post(cfg["endpoint"],headers=headers,json=payload,timeout=timeout,)if resp.status_code == 200:return resp.json()["choices"][0]["message"]["content"]is_last = attempt == max_retriesif resp.status_code not in RETRYABLE_STATUS or is_last:# Only log the status code and endpoint, not the request headersraise RuntimeError(f"Request failed: HTTP {resp.status_code}, URL {cfg['endpoint']}")time.sleep(2 ** attempt) # Backoff interval: 1s, 2s, 4sraise RuntimeError("Retry count exhausted")
Example usage:
cfg = load_config()reply = chat(cfg,model_id="example-small-model",messages=[{"role": "user", "content": "Explain idempotency in one sentence."}],max_tokens=256,)print(reply)
Here’s how the configuration items affect behavior:
timeoutSecondsis passed to thetimeoutparameter of therequestscall. 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.maxRetriesdetermines the number of retry attempts. The total number of requests will bemaxRetries + 1.- Only status codes
429and5xxare retried. Other4xxerrors indicate a problem with the request itself, and retrying is not useful. - The backoff interval grows exponentially. If a
429response includes an integer-valuedRetry-Afterheader, 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:
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
429errors.
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.
