Learn how to use the OpenAI Node API Library with npm. Setup and start using powerful AI features in your applications.
npm install openai
To use the OpenAI Node API Library, you can install it via npm.
For example, to install it via npm, run the following command:
To install the OpenAI Node API Library using npm, use the following command:
npm install openai
The code below shows how to get started using the chat completions API.
import OpenAI from 'openai';
const openai = new OpenAI({
apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted
});
async function main() {
const chatCompletion = await openai.chat.completions.create({
messages: [{ role: 'user', content: 'Say this is a test' }],
model: 'gpt-3.5-turbo',
});
}
main();
We provide support for streaming responses using Server Sent Events (SSE).
import OpenAI from 'openai';
const openai = new OpenAI();
async function main() {
const stream = await openai.chat.completions.create({
model: 'gpt-4',
messages: [{ role: 'user', content: 'Say this is a test' }],
stream: true,
});
for await (const chunk of stream) {
process.stdout.write(chunk.choices[0]?.delta?.content || '');
}
}
main();
If you need to cancel a stream, you can break from the loop or call stream.controller.abort()
.
This library includes TypeScript definitions for all request params and response fields. You may import and use them like so:
import OpenAI from 'openai';
const openai = new OpenAI({
apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted
});
async function main() {
const params: OpenAI.Chat.ChatCompletionCreateParams = {
messages: [{ role: 'user', content: 'Say this is a test' }],
model: 'gpt-3.5-turbo',
};
const chatCompletion: OpenAI.Chat.ChatCompletion = await openai.chat.completions.create(params);
}
main();
Documentation for each method, request param, and response field are available in docstrings and will appear on hover in most modern editors.
apiKey
: Your OpenAI API key.maxRetries
: The maximum number of retries for failed requests.timeout
: Request timeout in milliseconds.httpAgent
: HTTP agent for custom network settings.fetch
: Custom fetch function.npm install openai
import OpenAI from 'openai';
const openai = new OpenAI({ apiKey: process.env['OPENAI_API_KEY'] });
const chatCompletion = await openai.chat.completions.create({ messages: [{ role: 'user', content: 'Say this is a test' }], model: 'gpt-3.5-turbo' });