OpenAI Node.js SDK Tutorial
OpenAI Node.js SDK: Complete Tutorial
The official OpenAI Node.js SDK (openai) provides a typed, modern JavaScript/TypeScript interface for all OpenAI API endpoints. This guide covers installation, every major feature, TypeScript integration, error handling, and production patterns.
Installation
# npm
npm install openai
# yarn
yarn add openai
# pnpm
pnpm add openai
# Verify
node -e "const OpenAI = require('openai'); console.log('SDK loaded')"
Client Initialization
import OpenAI from 'openai';
// Method 1: Explicit configuration
const client = new OpenAI({
apiKey: 'sk-your-key',
baseURL: 'https://claude4u.com/v1'
});
// Method 2: Environment variables (recommended)
// Set OPENAI_API_KEY and OPENAI_BASE_URL in your env
const client2 = new OpenAI();
// Method 3: With custom options
const client3 = new OpenAI({
apiKey: process.env.OPENAI_API_KEY,
baseURL: 'https://claude4u.com/v1',
timeout: 60000, // 60-second timeout
maxRetries: 3 // Retry transient errors
});
Chat Completions
const response = await client.chat.completions.create({
model: 'gpt-4o',
messages: [
{ role: 'system', content: 'You are a JavaScript expert.' },
{ role: 'user', content: 'How do I debounce a function?' }
],
temperature: 0.7,
max_tokens: 500
});
console.log(response.choices[0].message.content);
console.log(`Tokens: ${response.usage?.total_tokens}`);
Streaming Responses
const stream = await client.chat.completions.create({
model: 'gpt-4o',
messages: [{ role: 'user', content: 'Explain async/await in JavaScript.' }],
stream: true
});
const chunks = [];
for await (const chunk of stream) {
const content = chunk.choices[0]?.delta?.content;
if (content) {
process.stdout.write(content);
chunks.push(content);
}
}
console.log(); // newline
const fullResponse = chunks.join('');
TypeScript Support
The SDK includes full TypeScript type definitions:
import OpenAI from 'openai';
import type {
ChatCompletionMessageParam,
ChatCompletionCreateParamsNonStreaming
} from 'openai/resources/chat/completions';
const client = new OpenAI({ baseURL: 'https://claude4u.com/v1' });
const messages: ChatCompletionMessageParam[] = [
{ role: 'system', content: 'You are helpful.' },
{ role: 'user', content: 'Hello!' }
];
const params: ChatCompletionCreateParamsNonStreaming = {
model: 'gpt-4o',
messages,
temperature: 0.7
};
const response = await client.chat.completions.create(params);
const content: string | null = response.choices[0].message.content;
Express.js API Endpoint
import express from 'express';
import OpenAI from 'openai';
const app = express();
app.use(express.json());
const client = new OpenAI({ baseURL: 'https://claude4u.com/v1' });
app.post('/api/chat', async (req, res) => {
try {
const { message } = req.body;
const response = await client.chat.completions.create({
model: 'gpt-4o',
messages: [{ role: 'user', content: message }]
});
res.json({
reply: response.choices[0].message.content,
tokens: response.usage?.total_tokens
});
} catch (error) {
if (error instanceof OpenAI.APIError) {
res.status(error.status || 500).json({ error: error.message });
} else {
res.status(500).json({ error: 'Internal server error' });
}
}
});
app.listen(3000);
Streaming SSE Endpoint
app.post('/api/chat/stream', async (req, res) => {
res.setHeader('Content-Type', 'text/event-stream');
res.setHeader('Cache-Control', 'no-cache');
res.setHeader('Connection', 'keep-alive');
const stream = await client.chat.completions.create({
model: 'gpt-4o',
messages: [{ role: 'user', content: req.body.message }],
stream: true
});
for await (const chunk of stream) {
const content = chunk.choices[0]?.delta?.content;
if (content) {
res.write(`data: ${JSON.stringify({ content })}\n\n`);
}
}
res.write('data: [DONE]\n\n');
res.end();
});
Function Calling
const tools = [{
type: 'function' as const,
function: {
name: 'calculate',
description: 'Perform a math calculation',
parameters: {
type: 'object',
properties: {
expression: {
type: 'string',
description: 'Math expression to evaluate'
}
},
required: ['expression']
}
}
}];
const response = await client.chat.completions.create({
model: 'gpt-4o',
messages: [{ role: 'user', content: 'What is 42 * 17?' }],
tools
});
const toolCall = response.choices[0].message.tool_calls?.[0];
if (toolCall) {
const args = JSON.parse(toolCall.function.arguments);
console.log(`Function: ${toolCall.function.name}`);
console.log(`Args: ${JSON.stringify(args)}`);
}
Error Handling
import OpenAI from 'openai';
const client = new OpenAI({ baseURL: 'https://claude4u.com/v1' });
try {
const response = await client.chat.completions.create({
model: 'gpt-4o',
messages: [{ role: 'user', content: 'Hello' }]
});
} catch (error) {
if (error instanceof OpenAI.AuthenticationError) {
console.error('Invalid API key');
} else if (error instanceof OpenAI.RateLimitError) {
console.error('Rate limited - implement backoff');
} else if (error instanceof OpenAI.BadRequestError) {
console.error('Invalid request:', error.message);
} else if (error instanceof OpenAI.NotFoundError) {
console.error('Model not found');
} else if (error instanceof OpenAI.APIConnectionError) {
console.error('Network error:', error.message);
} else if (error instanceof OpenAI.APIError) {
console.error(`API error ${error.status}: ${error.message}`);
}
}
Retry with Exponential Backoff
async function chatWithRetry(messages, maxRetries = 3) {
for (let attempt = 0; attempt < maxRetries; attempt++) {
try {
return await client.chat.completions.create({
model: 'gpt-4o',
messages
});
} catch (error) {
if (error instanceof OpenAI.RateLimitError && attempt < maxRetries - 1) {
const delay = Math.pow(2, attempt) * 1000;
console.log(`Rate limited. Retrying in ${delay}ms...`);
await new Promise((resolve) => setTimeout(resolve, delay));
} else {
throw error;
}
}
}
}
Embeddings
const embedding = await client.embeddings.create({
model: 'text-embedding-3-small',
input: ['Search query', 'Document text']
});
console.log(`Dimensions: ${embedding.data[0].embedding.length}`);
Warning: The Node.js SDK requires Node.js 18 or later due to its use of native fetch and other modern APIs. If you need to support older Node.js versions, use the
node-fetch polyfill.
Abort Requests
const controller = new AbortController();
// Cancel after 10 seconds
setTimeout(() => controller.abort(), 10000);
try {
const response = await client.chat.completions.create(
{
model: 'gpt-4o',
messages: [{ role: 'user', content: 'Write a long essay.' }]
},
{ signal: controller.signal }
);
} catch (error) {
if (error.name === 'AbortError') {
console.log('Request was cancelled');
}
}
Tip: claude4u.com works seamlessly with the OpenAI Node.js SDK. Simply set the
baseURL to https://claude4u.com/v1 and use your relay API key. All SDK features including streaming, function calling, and embeddings are fully supported.
Get Started with 轻舟 AI
Stable, fast AI API relay — supports Claude, OpenAI, Gemini and more
Sign Up Free
轻舟 AI