Introduction to AI SDKs and Environment Setup

Make your first model call in Node.js using an AIHubMix API key and the official OpenAI JavaScript SDK.

🎯 Introduction

When building an AI application, you send the user's question to a large language model and receive its generated answer. In this article, you will make your first model call in Node.js using the official OpenAI JavaScript SDK to send requests and AIHubMix as the model API provider.

You will learn how SDKs, API aggregation platforms, and models differ, and how to obtain an API key, configure the endpoint, run the code, and troubleshoot connection failures. This article covers only the first request; later articles cover multi-turn conversations and streaming.


🧱 SDKs, AIHubMix, and Models

First, distinguish these three roles:

NameResponsibilityUsed in this article
OpenAI SDKBuild and send requests and read responses in JavaScriptThe openai npm package
AIHubMixReceive requests and forward them to available model serviceshttps://aihubmix.com/v1
Large language modelGenerate answers from the inputgpt-4o-mini

A model API is an interface provided by a platform. You can access it through HTTP requests directly or through an SDK. The SDK handles sending requests, passing the API key, and processing responses, so you can call JavaScript methods directly. AIHubMix, which receives the request, validates the API key.

The flow is straightforward: a Node.js program uses the OpenAI SDK to send a request to AIHubMix. The platform calls the specified model and returns the result to the program.

AIHubMix is an API aggregation platform, rather than a model itself. Its OpenAI-compatible interface lets you use the familiar openai package without installing a dedicated AIHubMix SDK. Here, compatibility primarily refers to the agreed request format; it does not imply identical support for every model, parameter, or advanced capability.

Throughout this course, we use the OpenAI SDK's Chat Completions API to call models. It accepts a list of messages as input and returns the model's answer. Later articles use the same approach for multi-turn conversations, streaming, and other features.


🔑 Sign Up for AIHubMix and Obtain an API Key

Open the AIHubMix website, register or sign in, and find the API key creation option in the console to generate your key.

Third-party interfaces may change. Follow the labels and locations in the current interface. Keep your API key on your own machine or server; do not include it in frontend code, commit it to Git, or share it with others.

Alipay Top-Ups and Costs

AIHubMix supports Alipay top-ups. According to its Alipay top-up guide, you can select Alipay on the account credit page and follow the instructions to add a small amount of credit.

Adding USD 1 of credit does not mean Alipay will charge only its RMB equivalent at the current exchange rate. For example, one USD 1 top-up cost RMB 9, a premium of approximately 34.9% against the reference market exchange rate at the time. This applies only to that transaction and does not mean the platform charges a fixed 34.9% fee. Check the payment page for the actual amount.

Top-ups add account credit, which is deducted at the platform's model rates when you call paid models. AIHubMix also offers some free models with usage limits. Check the platform's current information for availability and restrictions.


🛠 Create a Project and Send Your First Request

First, check your Node.js version:

node -v

The examples in this course use Node.js 24.x. If your version differs, switch to the required version before creating the project.

Create a directory, initialize the project, and install the specified OpenAI SDK version:

mkdir ai-sdk-course
cd ai-sdk-course
npm init -y
npm install --save-exact openai@7.62.0

Save the Model Configuration

Create a .env file in the project root to store your AIHubMix API key, endpoint, and model name:

AI_API_KEY=your-aihubmix-api-key
AI_BASE_URL=https://aihubmix.com/v1
AI_MODEL=gpt-4o-mini

These three settings mean:

  • AI_API_KEY: A key generated by AIHubMix, rather than your ChatGPT login credentials or an OpenAI platform key.
  • AI_BASE_URL: The destination for API requests, pointing to AIHubMix's OpenAI-compatible endpoint.
  • AI_MODEL: The model ID to use. Here, gpt-4o-mini is a paid model, so calls consume account credit. Free allowances offered by the platform apply only to specified models.

The .env file stores configuration locally. Load it with --env-file=.env when running the program so you do not need to set the environment variables again each time.

Your .env contains a real API key. Do not commit it to Git or share it. Create a .gitignore file in the project root with the following contents:
.env
node_modules/

Create index.mjs:

import OpenAI from "openai";

const client = new OpenAI({
    apiKey: process.env.AI_API_KEY,
    baseURL: process.env.AI_BASE_URL
});

const response = await client.chat.completions.create({
    model: process.env.AI_MODEL,
    messages: [
        {
            role: "user",
            content: "Write a short, one-sentence product introduction for a to-do app."
        }
    ]
});

console.log("Model:", response.model);
console.log("Model reply:", response.choices[0].message.content);
console.log("Token usage:", response.usage);

Here are the key parts of the code:

  1. new OpenAI() creates the client. Explicitly passing apiKey and baseURL sends requests to AIHubMix rather than the official OpenAI endpoint.
  2. chat.completions.create() sends a message to the model. In messages, role: "user" identifies the user's question.
  3. response.choices[0].message.content reads the text returned by the model.
  4. response.usage shows the input and output token counts for the request. Later, we will combine these with model pricing to calculate costs. If the platform omits fields, use the actual response as your reference.

Run the Program

If your network can reach AIHubMix directly, run:

node --env-file=.env index.mjs

--env-file=.env reads the configuration file in the project root before startup and makes its variables available through process.env.

If a direct connection times out and you have enabled a local HTTP proxy, run the following with Node.js 24.x, which supports environment proxy configuration:

HTTPS_PROXY=http://127.0.0.1:7890 NODE_USE_ENV_PROXY=1 node --env-file=.env index.mjs

NODE_USE_ENV_PROXY=1 tells Node.js to read proxy environment variables. 7890 is the local HTTP proxy port; use the port configured in your proxy software.

Your terminal might display:

Model: gpt-4o-mini-2024-07-18
Model reply: Keep track of daily to-dos and see your tasks at a glance.
Token usage: { prompt_tokens: 25, completion_tokens: 19, total_tokens: 44 }

The reply and token counts vary. If you receive text relevant to your question, your first call has succeeded.


🪤 Common Errors and Troubleshooting

SymptomCheck first
401Is the API key correct, and did you accidentally use another platform's key?
403Account permissions, credit status, and the platform's specific error details
404 or model not foundIs AI_MODEL an exact model ID currently supported by the platform?
429Model usage allowances or rate limits; avoid retrying continuously
Connection timeoutNetwork connectivity, proxy port, and whether Node.js loaded the proxy configuration

If you suspect .env was not loaded, check whether the program received the API key without printing the key itself:

node --env-file=.env -e 'console.log(process.env.AI_API_KEY ? "API key loaded" : "API key not loaded")'

If you see "API key not loaded", check the .env filename, location, and configuration entries.

If requests still time out, confirm that your proxy software is running and that 127.0.0.1:7890 is its HTTP proxy address. If you do not use a proxy, remove the proxy prefix and try again.


❓ Knowledge Check

Q1: Why can we use the OpenAI SDK without an API key from OpenAI?

Because baseURL points to AIHubMix, AIHubMix receives and authenticates the SDK's requests. You therefore need a key issued by AIHubMix.

Q2: Does adding USD 1 of credit restrict me to OpenAI models?

No. AIHubMix supports multiple model providers, but availability, API compatibility, and pricing vary by model. The top-up adds platform credit; check the model list to see which models are supported.


🧪 Exercise

Replace the question in index.mjs with "Write a short, one-sentence product introduction for a weather app", run it again, and observe whether the reply changes.

Next, temporarily set AI_MODEL to a nonexistent model ID and run the program again. Note the error type, then restore the correct ID. Finally, explain why the code uses the OpenAI SDK even though the key comes from AIHubMix.


🎉 You have configured AIHubMix, installed the OpenAI SDK, and made your first model call. Next, you will learn about text generation parameters and response data.