How to Use an AI API with JavaScript: Complete Developer Guide
How to Use an AI API with JavaScript: Complete Developer Guide
JavaScript is one of the most widely used languages for building web applications.
If you are building a chatbot, AI writing tool, customer support application, study assistant or any other AI-powered product, you will eventually need to connect your JavaScript application to an AI API.
The good news is that you do not need a complicated setup.
With Node.js, an API key and a few lines of JavaScript, you can send a prompt to an AI model and receive a response.
In this guide, we will build the connection step by step.
You will learn how to:
- Set up a JavaScript project
- Install the required package
- Create an AI API key
- Store the API key safely
- Connect JavaScript to Velona
- Send your first AI request
- Read the response
- Handle errors
- Use the OpenAI-compatible API
- Stream AI responses
- Build a simple command line AI application
What Is an AI API?
An AI API allows your application to communicate with an artificial intelligence model.
Your JavaScript application sends information to the API.
JavaScript Application
|
| Prompt
v
AI API
|
| Request
v
AI Model
|
| Response
v
AI API
|
v
JavaScript Application
For example, your application could send:
Explain quantum computing in simple terms.
The AI model processes the request and sends a response back to your JavaScript application.
Your application can then display that response to the user.
Why Use JavaScript for AI Applications?
JavaScript is particularly useful because it can power both the frontend and backend of a web application.
With Node.js, JavaScript can also make API requests directly from a server.
This makes it possible to build applications such as:
- AI chatbots
- AI writing assistants
- Customer support systems
- Document summarizers
- AI search applications
- Study assistants
- Content generation tools
- Developer tools
- AI agents
You can start with a very small JavaScript program and gradually turn it into a complete application.
What You Need Before Starting
For this tutorial, you need three things.
- Node.js installed on your computer
- A Velona account
- A Velona API key
Velona provides access to 300+ AI models through a unified API gateway. The platform supports both a native API and an OpenAI-compatible API. :contentReference[oaicite:1]{index=1}
You can therefore start with a simple JavaScript project without building separate integrations for every model provider.
Step 1: Install Node.js
If Node.js is not already installed on your computer, install it first.
You can check whether it is installed by opening your terminal and running:
node --version
You should see something similar to:
v22.x.x
The exact version can be different.
You can also check npm:
npm --version
npm is the package manager commonly used with Node.js projects.
Step 2: Create a New JavaScript Project
Create a folder for your project.
mkdir my-ai-app
cd my-ai-app
Now initialize a Node.js project.
npm init -y
This creates a package.json file.
Your project now has the basic structure needed for installing JavaScript packages.
Step 3: Install the OpenAI JavaScript SDK
Velona provides an OpenAI-compatible API endpoint, which means you can use the official OpenAI JavaScript SDK with a Velona API key by changing the API base URL. :contentReference[oaicite:2]{index=2}
Install the SDK:
npm install openai
You can also install dotenv if you want to load your API key from a .env file.
npm install dotenv
Your project now has the packages needed for the first example.
Step 4: Create Your API Key
Open your Velona dashboard and go to the API Keys section.
Create a new API key.
Copy the key when it is shown.
According to the current Velona documentation, the raw API key is shown only once, so store it securely when you create it. :contentReference[oaicite:3]{index=3}
Do not paste your real API key into a public GitHub repository.
Do not put your production API key directly into frontend JavaScript either.
Step 5: Create an Environment File
Create a file named:
.env
Add your API key:
VELONA_API_KEY=YOUR_API_KEY
You can also store the base URL:
VELONA_API_KEY=YOUR_API_KEY
VELONA_BASE_URL=https://velona.in/v1
The environment file keeps your credentials outside your application source code.
Step 6: Add .env to .gitignore
If you are using Git, create a .gitignore file.
Add:
.env
node_modules
This prevents your environment file from accidentally being committed to your repository.
This small step can prevent a major security problem later.
Step 7: Create Your First JavaScript File
Create a file called:
index.js
Add the following code:
import OpenAI from "openai"
import dotenv from "dotenv"
dotenv.config()
const client = new OpenAI({
apiKey: process.env.VELONA_API_KEY,
baseURL: "https://velona.in/v1"
})
const response = await client.chat.completions.create({
model: "openai/gpt-4o-mini",
messages: [
{
role: "user",
content: "Explain APIs in simple terms."
}
]
})
console.log(response.choices[0].message.content)
This is enough to make your first AI request.
Step 8: Enable ES Modules
The previous example uses JavaScript's modern import syntax.
Add the following to your package.json:
{
"name": "my-ai-app",
"version": "1.0.0",
"type": "module",
"scripts": {
"start": "node index.js"
}
}
Now Node.js will understand the import syntax.
Step 9: Run Your First AI Request
Run:
npm start
Your terminal should print the model's response.
The complete flow looks like this:
.env
|
| API key
v
index.js
|
| JavaScript request
v
Velona API
|
| model request
v
AI model
|
| generated response
v
index.js
|
v
Terminal
You have now connected JavaScript to an AI API.
Understanding the JavaScript Code
Let's break the example into smaller pieces.
Import the SDK
import OpenAI from "openai"
This loads the OpenAI JavaScript SDK.
Load Environment Variables
import dotenv from "dotenv"
dotenv.config()
This loads values from your .env file.
Create the Client
const client = new OpenAI({
apiKey: process.env.VELONA_API_KEY,
baseURL: "https://velona.in/v1"
})
The API key authenticates your application.
The baseURL tells the SDK where to send the API request.
Velona's current OpenAI-compatible base URL is:
https://velona.in/v1
The official documentation lists this as the OpenAI-compatible API surface. :contentReference[oaicite:4]{index=4}
Create a Chat Completion
const response = await client.chat.completions.create({
model: "openai/gpt-4o-mini",
messages: [
{
role: "user",
content: "Explain APIs in simple terms."
}
]
})
The model identifies which AI model should process the request.
The messages array contains the conversation.
The role tells the model what type of message it is.
Understanding the Message Roles
AI chat APIs normally use different message roles.
User
A user message represents something sent by the person using your application.
{
role: "user",
content: "What is machine learning?"
}
System
A system message can provide instructions that define how the model should behave.
{
role: "system",
content: "You are a helpful science tutor."
}
Assistant
An assistant message represents an earlier response from the AI.
{
role: "assistant",
content: "Machine learning is a way..."
}
Combining these messages allows you to build multi-turn conversations.
Build a Simple AI Chat
Now let's make the example more useful.
import OpenAI from "openai"
import dotenv from "dotenv"
import readline from "readline/promises"
dotenv.config()
const client = new OpenAI({
apiKey: process.env.VELONA_API_KEY,
baseURL: "https://velona.in/v1"
})
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
})
const question = await rl.question("You: ")
const response = await client.chat.completions.create({
model: "openai/gpt-4o-mini",
messages: [
{
role: "user",
content: question
}
]
})
console.log("\nAI:", response.choices[0].message.content)
rl.close()
Now you can type a question directly into your terminal.
For example:
You: Explain photosynthesis in five lines.
The AI response will appear below it.
Build a Multi-Turn Conversation
A real chatbot needs to remember the messages from the current conversation.
You can store them in an array.
const messages = [
{
role: "system",
content: "You are a helpful assistant."
}
]
messages.push({
role: "user",
content: "My name is Rahul."
})
messages.push({
role: "assistant",
content: "Nice to meet you, Rahul."
})
messages.push({
role: "user",
content: "What is my name?"
})
You can then send the complete conversation to the model.
const response = await client.chat.completions.create({
model: "openai/gpt-4o-mini",
messages
})
The model receives the previous conversation as context.
How a JavaScript Chatbot Works
User types message
|
v
JavaScript application
|
v
Add message to conversation
|
v
Send request to Velona
|
v
AI model
|
v
Receive response
|
v
Add response to conversation
|
v
Display response to user
This simple architecture is enough to create the basic foundation of an AI chatbot.
Using the Native Velona API With JavaScript
You are not limited to the OpenAI-compatible endpoint.
Velona also provides a native API surface at:
https://velona.in/gateway/v1
The native inference endpoint is:
POST /gateway/v1/inference/run
The native API uses a request structure based on model and turns. :contentReference[oaicite:5]{index=5}
You can call it directly from JavaScript using fetch.
const response = await fetch(
"https://velona.in/gateway/v1/inference/run",
{
method: "POST",
headers: {
"Authorization": `Bearer ${process.env.VELONA_API_KEY}`,
"Content-Type": "application/json"
},
body: JSON.stringify({
model: "openai/gpt-4o-mini",
turns: [
{
role: "user",
content: "Explain APIs in simple terms."
}
]
})
}
)
const data = await response.json()
console.log(data)
This approach does not require the OpenAI SDK.
It uses the standard JavaScript fetch function to communicate directly with the REST API.
OpenAI SDK or Fetch?
Both approaches are useful.
| Approach | Useful When |
|---|---|
| OpenAI SDK | You want a familiar SDK interface |
| fetch | You want direct REST API control |
| Native Velona API | You need Velona-specific API features |
If you already use the OpenAI SDK, the compatible endpoint can make the setup very straightforward.
If you want complete control over the HTTP request, native fetch is also a simple option.
How to Handle API Errors
Network requests can fail.
Your application should never assume that every API call will succeed.
Wrap your request in a try and catch block.
try {
const response = await client.chat.completions.create({
model: "openai/gpt-4o-mini",
messages: [
{
role: "user",
content: "Hello"
}
]
})
console.log(response.choices[0].message.content)
} catch (error) {
console.error("AI request failed")
console.error(error.message)
}
This prevents your application from crashing without a useful message.
Check the HTTP Response With Fetch
If you use fetch, check whether the request succeeded.
const response = await fetch(
"https://velona.in/gateway/v1/inference/run",
{
method: "POST",
headers: {
"Authorization": `Bearer ${process.env.VELONA_API_KEY}`,
"Content-Type": "application/json"
},
body: JSON.stringify({
model: "openai/gpt-4o-mini",
turns: [
{
role: "user",
content: "Hello"
}
]
})
}
)
if (!response.ok) {
console.error("Request failed")
console.error(response.status)
}
const data = await response.json()
console.log(data)
This gives you a basic foundation for handling failed requests.
Do Not Put Your API Key in Frontend JavaScript
This is one of the most important security rules when building an AI web application.
Imagine you have this code inside a browser application:
const apiKey = "YOUR_REAL_API_KEY"
That is unsafe.
Users can inspect browser code and network requests.
Your secret API key should remain on your server.
A safer architecture looks like this:
Browser
|
| User message
v
Your Backend
|
| Secret API key
v
Velona API
|
v
AI Model
|
v
Your Backend
|
v
Browser
The browser talks to your backend.
Your backend talks to Velona.
The API key stays on the server.
Using JavaScript With an Express Server
If you are building a web application, you can use Express as a simple backend.
Install Express:
npm install express openai dotenv
Create:
server.js
Then:
import express from "express"
import OpenAI from "openai"
import dotenv from "dotenv"
dotenv.config()
const app = express()
app.use(express.json())
const client = new OpenAI({
apiKey: process.env.VELONA_API_KEY,
baseURL: "https://velona.in/v1"
})
app.post("/api/chat", async (req, res) => {
try {
const response = await client.chat.completions.create({
model: "openai/gpt-4o-mini",
messages: [
{
role: "user",
content: req.body.message
}
]
})
res.json({
reply: response.choices[0].message.content
})
} catch (error) {
res.status(500).json({
error: "AI request failed"
})
}
})
app.listen(3000, () => {
console.log("Server running on port 3000")
})
Your frontend can now send a request to your own backend.
Frontend Request
Your browser application can send:
const response = await fetch("/api/chat", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
message: "Explain artificial intelligence."
})
})
const data = await response.json()
console.log(data.reply)
The API key never needs to appear in this browser code.
Streaming AI Responses With JavaScript
Normal AI requests wait for the complete response before returning it.
Streaming works differently.
The model sends pieces of the response as they become available.
User
|
v
AI request
|
+---- Token
|
+---- Token
|
+---- Token
|
+---- Token
|
v
Complete response
This is useful for chat applications because users can start reading the response while the model is still generating it.
Velona supports streaming through Server-Sent Events. The current API documentation shows streaming by setting stream: true. :contentReference[oaicite:6]{index=6}
Streaming With the OpenAI JavaScript SDK
const stream = await client.chat.completions.create({
model: "openai/gpt-4o-mini",
messages: [
{
role: "user",
content: "Tell me a short story about space."
}
],
stream: true
})
for await (const chunk of stream) {
const text = chunk.choices[0]?.delta?.content
if (text) {
process.stdout.write(text)
}
}
Instead of waiting for the complete answer, your application receives pieces of the generated content.
This creates a much more responsive experience for chat interfaces.
Understanding Streaming Visually
Without streaming
Request
|
|
|
|
Complete response
|
v
Display
With streaming
Request
|
+---- Response piece
|
+---- Response piece
|
+---- Response piece
|
+---- Response piece
|
v
Complete response
For applications where response time feels important, streaming can make a significant difference to the user experience.
Control the AI Response
AI APIs usually provide generation settings that let you control how the model responds.
For example, the native Velona API supports configuration options such as temperature, maximum tokens and top-p. :contentReference[oaicite:7]{index=7}
A native API request can include:
{
"model": "openai/gpt-4o-mini",
"turns": [
{
"role": "user",
"content": "Explain photosynthesis."
}
],
"config": {
"temperature": 0.7,
"max_tokens": 300
}
}
The exact settings you use should depend on the application.
What Is Temperature?
Temperature affects how varied the model's output can be.
A lower temperature can be useful when you want more predictable responses.
A higher temperature can be useful when you want more variation in creative tasks.
For example:
Customer support
temperature: 0.2
Creative writing
temperature: 0.8
These are examples rather than universal rules.
You should test the setting with your actual application.
What Is max_tokens?
The max_tokens setting limits the amount of output generated by the model.
For example:
max_tokens: 200
can be useful when you want relatively short responses.
Limiting unnecessary output can also help keep token usage under control.
Use JavaScript to Build a Simple AI Summarizer
Now let's build a practical example.
Imagine you want to summarize text using an AI model.
import OpenAI from "openai"
import dotenv from "dotenv"
dotenv.config()
const client = new OpenAI({
apiKey: process.env.VELONA_API_KEY,
baseURL: "https://velona.in/v1"
})
const text = `
Artificial intelligence is being used in many industries.
Businesses use AI for customer support, automation,
content generation and data analysis.
`
const response = await client.chat.completions.create({
model: "openai/gpt-4o-mini",
messages: [
{
role: "system",
content: "Summarize the user's text in three short bullet points."
},
{
role: "user",
content: text
}
]
})
console.log(response.choices[0].message.content)
This small program can become the backend for a document summarization tool.
Build an AI Translation Tool
The same API structure can be used for translation.
const response = await client.chat.completions.create({
model: "openai/gpt-4o-mini",
messages: [
{
role: "system",
content: "Translate the user's text into Hindi."
},
{
role: "user",
content: "Artificial intelligence is changing software development."
}
]
})
console.log(response.choices[0].message.content)
The application itself does not need to know how the model performs the translation.
It simply sends the instruction and receives the result.
Build an AI Question Answering Application
You can also create a simple question answering application.
async function askAI(question) {
const response = await client.chat.completions.create({
model: "openai/gpt-4o-mini",
messages: [
{
role: "user",
content: question
}
]
})
return response.choices[0].message.content
}
const answer = await askAI(
"Why does JavaScript use promises?"
)
console.log(answer)
The useful part of this structure is that the AI request is placed inside a reusable function.
Your application can then call askAI() whenever it needs an AI response.
Create a Reusable AI Function
A good application should avoid repeating the same API setup throughout the project.
Create a reusable function:
async function generateText(prompt) {
const response = await client.chat.completions.create({
model: "openai/gpt-4o-mini",
messages: [
{
role: "user",
content: prompt
}
]
})
return response.choices[0].message.content
}
Now you can use:
const answer = await generateText(
"Explain APIs to a beginner."
)
console.log(answer)
This makes your code easier to maintain.
Use Different Models in the Same Application
One useful feature of a unified AI gateway is that your application can work with different model IDs through the same API structure.
For example:
const response = await client.chat.completions.create({
model: "MODEL_ID",
messages: [
{
role: "user",
content: "Hello"
}
]
})
To use another supported model, you can change the model ID.
The rest of your JavaScript integration can remain largely the same.
Velona's current model catalogue contains 300+ models and provides model IDs that can be used with the gateway. :contentReference[oaicite:8]{index=8}
How Your JavaScript Application Connects to the AI Model
Your Application
┌─────────────────────┐
│ JavaScript │
│ / Node.js │
└──────────┬──────────┘
|
| HTTPS
v
┌─────────────────────┐
│ Velona Gateway │
└──────────┬──────────┘
|
v
┌─────────────────────┐
│ AI Model │
└──────────┬──────────┘
|
v
┌─────────────────────┐
│ Response │
└─────────────────────┘
Your application does not need to manage a separate SDK integration for every model.
You send the request through the gateway and specify the model you want to use.
How Much Does a JavaScript AI Application Cost?
The JavaScript language itself does not determine your AI API cost.
Your cost depends on the AI usage generated by your application.
Important factors include:
- Model used
- Input tokens
- Output tokens
- Number of requests
- Conversation length
- Application traffic
Velona displays AI model pricing in INR and deducts usage from the prepaid wallet based on the request usage. :contentReference[oaicite:9]{index=9}
This means you should design your JavaScript application with both functionality and usage in mind.
Keep Large Prompts Under Control
Suppose your application keeps sending a huge instruction block with every request.
Your token usage can grow quickly.
Instead of sending unnecessary information:
Huge instructions
+
Old conversation
+
Repeated context
+
New question
Try to send only the context the model actually needs.
Required instructions
+
Relevant context
+
New question
This can make your application more efficient.
How to Structure a JavaScript AI Project
As your application grows, avoid putting everything inside one file.
A simple structure could be:
my-ai-app/
|
├── src/
│ ├── ai.js
│ ├── server.js
│ └── prompts.js
|
├── .env
├── .gitignore
├── package.json
└── README.md
The ai.js file can contain your AI client.
The server.js file can contain your API routes.
The prompts.js file can contain reusable prompts.
This structure becomes easier to maintain as your project grows.
Create a Separate AI Client Module
For example:
import OpenAI from "openai"
import dotenv from "dotenv"
dotenv.config()
export const client = new OpenAI({
apiKey: process.env.VELONA_API_KEY,
baseURL: "https://velona.in/v1"
})
You can then import the client wherever you need it.
import { client } from "./ai.js"
const response = await client.chat.completions.create({
model: "openai/gpt-4o-mini",
messages: [
{
role: "user",
content: "Hello"
}
]
})
console.log(response.choices[0].message.content)
This keeps your project organized.
Common JavaScript AI API Mistakes
Mistake 1: Hardcoding the API Key
Never put your production API key directly into source code.
Mistake 2: Exposing the Key in the Browser
Keep secret credentials on your backend.
Mistake 3: Ignoring Errors
API requests can fail. Always handle errors.
Mistake 4: Sending Huge Prompts
Only send the context your application actually needs.
Mistake 5: Ignoring Response Limits
If you only need a short answer, avoid unnecessarily large responses.
Mistake 6: Building Everything in One File
Separate API logic from application logic as your project grows.
Mistake 7: Forgetting Environment Variables
Use environment variables for credentials and configuration.
JavaScript AI API Development Workflow
Choose your use case
|
v
Create Velona account
|
v
Add wallet credits
|
v
Create API key
|
v
Create Node.js project
|
v
Install OpenAI SDK
|
v
Store key in .env
|
v
Create AI client
|
v
Send first request
|
v
Handle response
|
v
Add error handling
|
v
Build your application
This is enough to take you from an empty JavaScript folder to a working AI application.
What Can You Build With JavaScript and an AI API?
Once the basic integration works, the possibilities become much larger.
You could build:
- An AI customer support chatbot
- A study assistant
- A document summarizer
- An AI writing assistant
- A coding assistant
- An email generator
- A translation application
- An AI search interface
- A content classification system
- An AI agent
The API connection remains the foundation.
Your application determines what happens around it.
Final JavaScript Example
Here is a compact version of the complete setup.
import OpenAI from "openai"
import dotenv from "dotenv"
dotenv.config()
const client = new OpenAI({
apiKey: process.env.VELONA_API_KEY,
baseURL: "https://velona.in/v1"
})
async function askAI(prompt) {
try {
const response = await client.chat.completions.create({
model: "openai/gpt-4o-mini",
messages: [
{
role: "user",
content: prompt
}
]
})
return response.choices[0].message.content
} catch (error) {
console.error("AI request failed")
console.error(error.message)
}
}
const answer = await askAI(
"Explain artificial intelligence in five simple sentences."
)
console.log(answer)
This small program contains the core pattern used by many larger AI applications.
Prompt
↓
JavaScript
↓
AI API
↓
AI Model
↓
Response
↓
Your Application
Frequently Asked Questions
Can I use JavaScript to call an AI API?
Yes. JavaScript can communicate with AI APIs using the OpenAI SDK, native fetch or other HTTP libraries.
Can I use Node.js?
Yes. Node.js is a common choice for server-side JavaScript AI applications.
Do I need a separate SDK for every AI model?
Not when you use a unified compatible API. With Velona, supported models can be accessed through the same gateway structure.
Can I use the OpenAI JavaScript SDK?
Yes. Velona provides an OpenAI-compatible endpoint at https://velona.in/v1. :contentReference[oaicite:10]{index=10}
Can I use JavaScript fetch instead?
Yes. You can make HTTP requests directly with the native JavaScript fetch API.
Should I put my API key in frontend JavaScript?
No. Keep secret API keys on your backend and use your backend as the secure connection between your frontend and the AI API.
Can I stream AI responses with JavaScript?
Yes. Velona supports streaming through Server-Sent Events and the OpenAI-compatible API supports streaming for chat completions. :contentReference[oaicite:11]{index=11}
Can I use different AI models from the same JavaScript application?
Yes. You can specify the model you want to use in the API request and work with supported models through the Velona gateway.
How are AI API costs calculated?
AI usage is generally based on the amount of processing performed by the model. For text models, input and output token usage are important parts of the calculation.
Can I build a chatbot with JavaScript?
Yes. A chatbot can be built by storing conversation messages, sending them to the AI API and displaying the generated response to the user.
Start Building With JavaScript
You do not need a huge codebase to start building with AI.
A Node.js project, an API key and a small JavaScript function are enough to make your first request.
From there, you can add a frontend, user authentication, conversation history, streaming, databases, tools and other application features.
The important first step is getting the basic request working.
Once your JavaScript application can send a prompt and receive a response, you have the foundation for much larger AI products.
Ready to make your first AI request?
Explore the Velona API documentation and start building with JavaScript.
You can also explore the AI model catalogue to see the models available through the gateway.