Calling a Cloud LLM API from Windows 11: A Practical Guide with Node.js
A step-by-step guide to calling an OpenAI-compatible cloud large language model API from a local script on Windows 11. It covers environment checks, configuration, secure API key storage, three-step verification, and troubleshooting by HTTP status code.
1. Scope and Out-of-Scope Scenarios
This guide is for developers who want to debug locally, validate a prototype, or build a small personal tool on Windows 11. The goal is a minimal working path: run a local script, send a question to a cloud LLM, and receive a text reply.
This approach fits the following situations:
- The machine has network access and can reach the provider’s HTTPS API.
- The current account can write to its user directory and set user-level environment variables.
- You need to confirm that the API is reachable, the key is valid, and the request parameters take effect.
The following situations are outside the scope of this guide:
- Offline inference. All model computation happens in the cloud, so the script stops working without a network connection.
- Devices under strict enterprise policy that prohibit installing software or changing environment variables.
- High-concurrency production services. The script has no rate limiting, retry queue, or log rotation, so do not use it directly for live traffic.
This guide does not depend on a vendor-specific SDK. It calls an OpenAI-compatible HTTP API directly. As a result, you can switch to another provider that offers a compatible API by replacing the baseUrl and model fields.
2. Environment Check
2.1 System and PowerShell Version
Windows 11 includes PowerShell 5.1. The commands in this guide run on both 5.1 and 7.x. Open a terminal and run the following command to check the version:
$PSVersionTable.PSVersion
2.2 Install Node.js
The script uses the built-in fetch function in Node.js to send HTTP requests, so you do not need to install any third-party npm packages. Node.js 20.x or 22.x LTS is recommended. The minimum supported version is 18.17.
Windows 11 usually includes winget. You can install the Node.js LTS release with this command:
winget install --id OpenJS.NodeJS.LTS -e
After the installation finishes, open a new terminal and run the following commands to verify it:
node -vnpm -v
node -v should print a version number such as v22.x.x. If you see an error saying the term “node” is not recognized as the name of a cmdlet, function, script file, or operable program, the PATH variable has usually not refreshed yet. Close the terminal and open it again.
If winget is unavailable, download the Windows Binary (.zip) version from nodejs.org, extract it to a user directory such as C:\Users\<username>\tools\node, and add that directory to the user-level PATH.
2.3 Permissions
The steps in this guide do not require administrator rights. You can place the Node.js zip files, the script, and the environment variables all within your current user directory. If the winget installation shows a User Account Control (UAC) prompt, click “Yes”. If you cannot approve the UAC prompt, use the zip version of Node.js instead.
This guide runs the script by launching node.exe on a .mjs file. It does not involve the PowerShell execution policy, so you do not need to change ExecutionPolicy. Do not loosen the execution policy just to run this script.
2.4 Network Connectivity
Check whether your machine can reach the provider’s HTTPS port. The example below uses DeepSeek:
Test-NetConnection api.deepseek.com -Port 443
If TcpTestSucceeded is True in the output, the network path is open. If it is False, check your proxy settings or your corporate network policy.
3. Create the Directory, Configuration File, and Script
3.1 Create a Working Directory
Run the following command in the terminal:
New-Item -ItemType Directory -Force -Path "$HOME\llm-cli"
$HOME usually points to C:\Users\<username>. All files in this guide go under C:\Users\<username>\llm-cli.
3.2 Configuration File
The configuration file is C:\Users\<username>\llm-cli\config.json. Its contents are:
{"provider": {"baseUrl": "https://api.deepseek.com","apiKeyEnv": "LLM_API_KEY","model": "deepseek-chat"},"options": {"timeout": 60000,"maxTokens": 512,"temperature": 0.7}}
The fields are as follows:
baseUrl: The root address of the service. The script appends/chat/completionsautomatically, so do not include that path here.apiKeyEnv: The name of the environment variable that stores the key. Put only the variable name in the configuration file, never the key itself.model: The model identifier. Check the model list in the provider’s official documentation.timeout: The timeout for a single request, in milliseconds. 60000 means 60 seconds. For long text generation, set at least 30 seconds so that generation is not cut off before it finishes.maxTokens: The maximum output length of a single reply. It directly affects cost, so you can keep it low during debugging.temperature: The sampling temperature. Higher values make replies more varied.
When you save the file, choose UTF-8 encoding. Some versions of Windows Notepad write a byte order mark (BOM). The script handles this, but saving as UTF-8 is still the safer choice.
3.3 Script File
The script is at C:\Users\<username>\llm-cli\chat.mjs. Its contents are:
import { readFile } from "node:fs/promises";import { homedir } from "node:os";import { join } from "node:path";const configPath = join(homedir(), "llm-cli", "config.json");// Strip the UTF-8 BOM, which some editors add and which can break JSON parsingconst raw = (await readFile(configPath, "utf8")).replace(/^\uFEFF/, "");const config = JSON.parse(raw);const keyName = config.provider.apiKeyEnv;const apiKey = process.env[keyName];if (!apiKey) {console.error(`Environment variable ${keyName} is not set. Set it and reopen the terminal.`);process.exit(1);}const prompt = process.argv.slice(2).join(" ") || "Introduce yourself in one sentence.";const url = `${config.provider.baseUrl}/chat/completions`;const controller = new AbortController();const timer = setTimeout(() => controller.abort(), config.options.timeout);try {const res = await fetch(url, {method: "POST",headers: {"Content-Type": "application/json",Authorization: `Bearer ${apiKey}`,},body: JSON.stringify({model: config.provider.model,messages: [{ role: "user", content: prompt }],max_tokens: config.options.maxTokens,temperature: config.options.temperature,}),signal: controller.signal,});if (!res.ok) {const text = await res.text();console.error(`HTTP ${res.status}: ${text.slice(0, 300)}`);process.exit(1);}const data = await res.json();console.log(data.choices[0].message.content);} catch (err) {if (err.name === "AbortError") {console.error("Request timed out. Increase timeout in config.json.");} else {console.error("Network error:", err.message);}process.exit(1);} finally {clearTimeout(timer);}
The script has four key points. First, it reads the key only from an environment variable, so the key never appears in the configuration file or the script. Second, it prints only the first 300 characters of an error response body, so a long response does not flood the screen. Third, it enforces the timeout with AbortController. When the timeout hits, the script exits immediately with a non-zero exit code, which makes it easy to call from other automation workflows.
4. Store the API Key
4.1 Create a Key
Sign in to the DeepSeek open platform and create a new key on the API keys page. Add a note describing its purpose, such as “local debugging”. Create separate keys for local debugging and for any later production use, so each one can be revoked on its own.
The key is displayed only once, at creation time. Save it directly to an environment variable. Do not paste it into a chat window, ticket, screenshot, or document.
4.2 Write the Key to a User-Level Environment Variable
If you pass the key as a command-line argument, PowerShell saves it to the command history on disk. Use Read-Host with secure input instead:
$secure = Read-Host "Enter your API key" -AsSecureString$bstr = [Runtime.InteropServices.Marshal]::SecureStringToBSTR($secure)$plain = [Runtime.InteropServices.Marshal]::PtrToStringBSTR($bstr)[Environment]::SetEnvironmentVariable("LLM_API_KEY", $plain, "User")[Runtime.InteropServices.Marshal]::ZeroFreeBSTR($bstr)Remove-Variable plain, secure, bstr
After you run this, the characters you type are not shown on screen. The variable is written to the “User” scope, so it applies only to the current Windows user.
Environment variables take effect only in newly started processes. Terminals that are already open do not update automatically, so close them and open new ones. To confirm the variable is set in a new terminal without printing the key, run:
if ($env:LLM_API_KEY) { "Set" } else { "Not set" }
4.3 Key Security Requirements
- Do not write the real key into
config.json,chat.mjs, a Git repository, chat logs, or screenshots. - If a key is exposed, delete or disable it in the console immediately. Then create a new key and replace the environment variable.
- You can revoke keys on the same API keys page. After a key is deleted, requests that use it return HTTP 401.
5. End-to-End Verification
Verification has three steps, from simple to complex. Each step lists the expected output. If the output does not match, check the troubleshooting table in Section 6 first.
5.1 Step 1: Minimal Request
Call the API directly with PowerShell’s built-in Invoke-RestMethod, bypassing the script. This isolates the problem to the API itself:
$body = @{model = "deepseek-chat"messages = @(@{ role = "user"; content = "ping" })max_tokens = 16} | ConvertTo-Json -Depth 5$r = Invoke-RestMethod -Uri "https://api.deepseek.com/chat/completions" `-Method Post `-Headers @{ Authorization = "Bearer $env:LLM_API_KEY" } `-ContentType "application/json" `-Body $body$r.model$r.choices[0].message.content$r.choices[0].finish_reason
Expected results:
$r.modelprintsdeepseek-chat.$r.choices[0].message.contentprints a short text reply, which may be “pong” or another brief response.$r.choices[0].finish_reasonprintsstop, which means the model finished normally.
If the request fails, Invoke-RestMethod throws an exception that includes the HTTP status code. Use that code to find the cause in the troubleshooting table in Section 6.
5.2 Step 2: Run the Script
node "$HOME\llm-cli\chat.mjs" "Introduce Windows 11 in one sentence"echo $LASTEXITCODE
Expected results: the terminal prints a one-sentence reply, and $LASTEXITCODE prints 0.
If you run the script without arguments, it uses the default prompt “Introduce yourself in one sentence.”
5.3 Step 3: Error Path
Use an invalid key on purpose to check whether the script returns a readable error message. This overrides the variable only in the current terminal session and leaves the user-level variable unchanged:
$env:LLM_API_KEY = "invalid-key-for-test"node "$HOME\llm-cli\chat.mjs" "test"echo $LASTEXITCODERemove-Item Env:LLM_API_KEY
Expected results: the terminal prints an error similar to HTTP 401: ..., and $LASTEXITCODE is 1. After Remove-Item Env:LLM_API_KEY, the session reads the user-level variable again. If errors continue, close the terminal and open a new one.
This step confirms that the error path works. When a problem appears in production, readable error messages like these make troubleshooting much faster.
6. Troubleshooting Table
The table below lists the most common failures in this approach. The exact meaning of error text and error codes is defined in the provider’s official documentation.
| Symptom | Common Cause | Fix | How to Verify |
|---|---|---|---|
| Environment variable not set | The variable was never set, or the terminal was not reopened after setting it | Repeat the command in Section 4.2, then close and reopen the terminal | $env:LLM_API_KEY is not empty |
| HTTP 401 | The key is wrong, has been deleted, or has leading or trailing spaces | Create a new key in the console and write it to the environment variable again | The minimal request in Section 5.1 returns stop |
| HTTP 402 | Insufficient account balance or exhausted quota | Check the balance in the console, then top up or switch accounts | The request succeeds after the balance is restored |
| HTTP 404 | baseUrl includes a path, or the model name is wrong |
Check config.json against the official model list |
The minimal request returns normal content |
| HTTP 429 | Request rate exceeds the limit | Reduce call frequency and retry after a wait | The request succeeds after an interval |
| HTTP 5xx | Temporary server-side failure | Check the provider’s status page and try again later | The request succeeds after the service recovers |
| Request timed out | Slow network, or long generated output | Increase timeout, or reduce maxTokens |
The script prints output normally |
fetch failed or network error |
The server is unreachable, or a proxy is blocking the request | Run the connectivity check in Section 2.4 and check proxy settings | TcpTestSucceeded is True |
| JSON parsing error | A comma or quotation mark is wrong in config.json, or the encoding is incorrect |
Validate the file with a JSON tool and save it again as UTF-8 | The script reads the configuration and sends the request |
node command not found |
PATH has not refreshed, or the installation did not finish | Reopen the terminal. If the problem persists, check the installation path | node -v prints a version number |
When troubleshooting, work in order: confirm the environment variable, confirm the minimal request, then check the script. This quickly shows which layer is causing the problem.
7. Cost and Quota
Cloud LLM services usually charge based on the number of input and output tokens. The script limits output length through maxTokens, which is the most direct way to control cost.
Whether the provider offers free quota, how much it is, and how long it lasts are defined on the provider’s current official pages. This guide makes no commitments on these points, and you should not rely on any specific figure for capacity planning.
To estimate cost, check the usage field in the JSON response. prompt_tokens is the number of input tokens, and completion_tokens is the number of output tokens. During debugging, you can temporarily print these fields from the script and calculate the cost per call using the official pricing:
$r.usage
Record usage for each debugging session and observe how consumption changes with prompt length. This gives you a more accurate picture of cost before you use the service for real work.
8. Pre-Production Checklist
Before you use this script for anything beyond personal debugging, confirm each of the following:
- The key exists only in an environment variable or a secrets management service, never in code, configuration files, or repositories.
- Logs do not record the
Authorizationheader or the full key. - Logs record timestamps, latency, and HTTP status codes, and redact user input such as phone numbers, email addresses, and national ID numbers.
- Local debugging and production use separate keys.
- You know how to delete or disable a key in the console.
- An alert notifies the responsible person when the quota or balance approaches its limit.
- For long-text scenarios, you have set
timeoutbased on the actual generation time
