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


  1. ```sh
  2. npm install openai
  3. ```

You can import in Deno via:


  1. ```ts
  2. import OpenAI from 'https://deno.land/x/openai@v4.54.0/mod.ts';
  3. ```


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.

  1. ```js
  2. import OpenAI from 'openai';

  3. const client = new OpenAI({
  4.   apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted
  5. });

  6. async function main() {
  7.   const chatCompletion = await client.chat.completions.create({
  8.     messages: [{ role: 'user', content: 'Say this is a test' }],
  9.     model: 'gpt-3.5-turbo',
  10.   });
  11. }

  12. main();
  13. ```

Streaming responses


We provide support for streaming responses using Server Sent Events (SSE).

  1. ```ts
  2. import OpenAI from 'openai';

  3. const client = new OpenAI();

  4. async function main() {
  5.   const stream = await client.chat.completions.create({
  6.     model: 'gpt-4',
  7.     messages: [{ role: 'user', content: 'Say this is a test' }],
  8.     stream: true,
  9.   });
  10.   for await (const chunk of stream) {
  11.     process.stdout.write(chunk.choices[0]?.delta?.content || '');
  12.   }
  13. }

  14. main();
  15. ```

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:

  1. ```ts
  2. import OpenAI from 'openai';

  3. const client = new OpenAI({
  4.   apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted
  5. });

  6. async function main() {
  7.   const params: OpenAI.Chat.ChatCompletionCreateParams = {
  8.     messages: [{ role: 'user', content: 'Say this is a test' }],
  9.     model: 'gpt-3.5-turbo',
  10.   };
  11.   const chatCompletion: OpenAI.Chat.ChatCompletion = await client.chat.completions.create(params);
  12. }

  13. main();
  14. ```

Documentation for each method, request param, and response field are available in docstrings and will appear on hover in most modern editors.