OpenAI Node API
The official Node.js / Typescript library for the OpenAI API
README
OpenAI Node API Library
This library provides convenient access to the OpenAI REST API from TypeScript or JavaScript.
It is generated from our OpenAPI specification with Stainless.
To learn how to use the OpenAI API, check out our API Reference and Documentation.
Installation
- ```sh
- npm install openai
- ```
You can import in Deno via:
- ```ts
- import OpenAI from 'https://deno.land/x/openai@v4.54.0/mod.ts';
- ```
Usage
The full API of this library can be found in api.md file along with many code examples. The code below shows how to get started using the chat completions API.
- ```js
- import OpenAI from 'openai';
- const client = new OpenAI({
- apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted
- });
- async function main() {
- const chatCompletion = await client.chat.completions.create({
- messages: [{ role: 'user', content: 'Say this is a test' }],
- model: 'gpt-3.5-turbo',
- });
- }
- main();
- ```
Streaming responses
We provide support for streaming responses using Server Sent Events (SSE).
- ```ts
- import OpenAI from 'openai';
- const client = new OpenAI();
- async function main() {
- const stream = await client.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().
Request & Response types
This library includes TypeScript definitions for all request params and response fields. You may import and use them like so:
- ```ts
- import OpenAI from 'openai';
- const client = 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 client.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.