Socket
Socket
Sign inDemoInstall

openai

Package Overview
Dependencies
Maintainers
4
Versions
190
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

openai - npm Package Compare versions

Comparing version 3.3.0 to 4.0.0-beta.0

.eslintrc.js

169

index.ts

@@ -1,18 +0,157 @@

/* tslint:disable */
/* eslint-disable */
/**
* OpenAI API
* APIs for sampling from and fine-tuning language models
*
* The version of the OpenAPI document: 1.3.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
// File generated from our OpenAPI spec by Stainless.
import qs from 'qs';
import * as Core from './core';
import * as API from './resources';
import * as Errors from '~/error';
import type { Agent } from 'http';
import * as FileFromPath from 'formdata-node/file-from-path';
export * from "./api";
export * from "./configuration";
type Config = {
/**
* Defaults to process.env["OPENAI_API_KEY"].
*/
apiKey?: string;
baseURL?: string;
timeout?: number;
httpAgent?: Agent;
maxRetries?: number;
defaultHeaders?: Core.Headers;
};
/** Instantiate the API Client. */
export class OpenAI extends Core.APIClient {
apiKey: string;
private _options: Config;
constructor(config?: Config) {
const options: Config = {
apiKey: process.env['OPENAI_API_KEY'] || '',
baseURL: 'https://api.openai.com/v1',
...config,
};
if (!options.apiKey && options.apiKey !== null) {
throw new Error(
"The OPENAI_API_KEY environment variable is missing or empty; either provide it, or instantiate the OpenAI client with an apiKey option, like new OpenAI({ apiKey: 'my api key' }).",
);
}
super({
baseURL: options.baseURL!,
timeout: options.timeout,
httpAgent: options.httpAgent,
maxRetries: options.maxRetries,
});
this.apiKey = options.apiKey;
this._options = options;
}
completions: API.Completions = new API.Completions(this);
chat: API.Chat = new API.Chat(this);
edits: API.Edits = new API.Edits(this);
embeddings: API.Embeddings = new API.Embeddings(this);
files: API.Files = new API.Files(this);
images: API.Images = new API.Images(this);
audio: API.Audio = new API.Audio(this);
answers: API.Answers = new API.Answers(this);
classifications: API.Classifications = new API.Classifications(this);
moderations: API.Moderations = new API.Moderations(this);
models: API.Models = new API.Models(this);
fineTunes: API.FineTunes = new API.FineTunes(this);
protected override defaultHeaders(): Core.Headers {
return {
...super.defaultHeaders(),
...this._options.defaultHeaders,
};
}
protected override authHeaders(): Core.Headers {
return { Authorization: `Bearer ${this.apiKey}` };
}
protected override qsOptions(): qs.IStringifyOptions {
return { arrayFormat: 'comma' };
}
static APIError = Errors.APIError;
static APIConnectionError = Errors.APIConnectionError;
static APIConnectionTimeoutError = Errors.APIConnectionTimeoutError;
static NotFoundError = Errors.NotFoundError;
static ConflictError = Errors.ConflictError;
static RateLimitError = Errors.RateLimitError;
static BadRequestError = Errors.BadRequestError;
static AuthenticationError = Errors.AuthenticationError;
static InternalServerError = Errors.InternalServerError;
static PermissionDeniedError = Errors.PermissionDeniedError;
static UnprocessableEntityError = Errors.UnprocessableEntityError;
}
export const {
APIError,
APIConnectionError,
APIConnectionTimeoutError,
NotFoundError,
ConflictError,
RateLimitError,
BadRequestError,
AuthenticationError,
InternalServerError,
PermissionDeniedError,
UnprocessableEntityError,
} = Errors;
export import fileFromPath = FileFromPath.fileFromPath;
export namespace OpenAI {
// Helper functions
export import fileFromPath = FileFromPath.fileFromPath;
export import Completion = API.Completion;
export import CompletionChoice = API.CompletionChoice;
export import CompletionCreateParams = API.CompletionCreateParams;
export import Edit = API.Edit;
export import EditCreateParams = API.EditCreateParams;
export import Embedding = API.Embedding;
export import EmbeddingCreateParams = API.EmbeddingCreateParams;
export import File = API.File;
export import FileListResponse = API.FileListResponse;
export import FileDeleteResponse = API.FileDeleteResponse;
export import FileRetrieveFileContentResponse = API.FileRetrieveFileContentResponse;
export import FileCreateParams = API.FileCreateParams;
export import Image = API.Image;
export import ImagesResponse = API.ImagesResponse;
export import ImageCreateVariationParams = API.ImageCreateVariationParams;
export import ImageEditParams = API.ImageEditParams;
export import ImageGenerateParams = API.ImageGenerateParams;
export import AnswerCreateResponse = API.AnswerCreateResponse;
export import AnswerCreateParams = API.AnswerCreateParams;
export import ClassificationCreateResponse = API.ClassificationCreateResponse;
export import ClassificationCreateParams = API.ClassificationCreateParams;
export import Moderation = API.Moderation;
export import ModerationCreateResponse = API.ModerationCreateResponse;
export import ModerationCreateParams = API.ModerationCreateParams;
export import DeleteModelResponse = API.DeleteModelResponse;
export import ListModelsResponse = API.ListModelsResponse;
export import Model = API.Model;
export import FineTune = API.FineTune;
export import FineTuneEvent = API.FineTuneEvent;
export import ListFineTuneEventsResponse = API.ListFineTuneEventsResponse;
export import ListFineTunesResponse = API.ListFineTunesResponse;
export import FineTuneCreateParams = API.FineTuneCreateParams;
export import FineTuneListEventsParams = API.FineTuneListEventsParams;
}
exports = module.exports = OpenAI;
export default OpenAI;

60

package.json
{
"name": "openai",
"version": "3.3.0",
"description": "Node.js library for the OpenAI API",
"repository": {
"type": "git",
"url": "git@github.com:openai/openai-node.git"
},
"keywords": [
"openai",
"open",
"ai",
"gpt-3",
"gpt3"
],
"author": "OpenAI",
"license": "MIT",
"main": "./dist/index.js",
"types": "./dist/index.d.ts",
"version": "v4.0.0-beta.0",
"description": "Client library for the OpenAI API",
"author": "OpenAI <support@openai.com>",
"types": "dist/cjs/index.d.ts",
"main": "dist/cjs/index.js",
"type": "commonjs",
"repository": "github:openai/openai-node",
"license": "Apache-2.0",
"private": false,
"scripts": {
"build": "tsc --outDir dist/"
"test": "bin/check-test-server && yarn jest",
"build": "bash ./build",
"prepack": "yarn build",
"format": "prettier --write .",
"tsn": "ts-node -r tsconfig-paths/register",
"fix": "eslint --fix --ext ts,js ."
},
"dependencies": {
"axios": "^0.26.0",
"form-data": "^4.0.0"
"@types/node": "^18.11.18",
"@types/node-fetch": "^2.6.1",
"@types/qs": "^6.9.7",
"abort-controller": "^3.0.0",
"agentkeepalive": "^4.2.1",
"digest-fetch": "^1.3.0",
"form-data-encoder": "1.7.2",
"formdata-node": "^4.3.2",
"node-fetch": "^2.6.7",
"qs": "^6.10.3"
},
"devDependencies": {
"@types/node": "^12.11.5",
"typescript": "^3.6.4"
"openai": "link:.",
"@types/jest": "^27.5.0",
"@typescript-eslint/eslint-plugin": "^5.33.0",
"@typescript-eslint/parser": "^5.33.0",
"eslint": "^8.22.0",
"eslint-plugin-unused-imports": "^2.0.0",
"jest": "^28.1.0",
"prettier": "rattrayalex/prettier#postfix-ternaries",
"ts-jest": "^28.0.2",
"ts-node": "^10.5.0",
"tsc-alias": "^1.6.9",
"tsconfig-paths": "^3.12.0",
"typescript": "^4.8.2"
}
}

@@ -1,11 +0,20 @@

# OpenAI Node.js Library
# OpenAI Node API Library
The OpenAI Node.js library provides convenient access to the OpenAI API from Node.js applications. Most of the code in this library is generated from our [OpenAPI specification](https://github.com/openai/openai-openapi).
[![NPM version](https://img.shields.io/npm/v/openai.svg)](https://npmjs.org/package/openai)
The OpenAI Node library provides convenient access to the OpenAI REST API from applications written in server-side JavaScript.
It includes TypeScript definitions for all request params and response fields.
> ⚠️ **Important note: this library is meant for server-side usage only, as using it in client-side browser code will expose your secret API key. [See here](https://platform.openai.com/docs/api-reference/authentication) for more details.**
## Documentation
To learn how to use the OpenAI API, check out our [API Reference](https://platform.openai.com/docs/api-reference) and [Documentation](https://platform.openai.com/docs).
## Installation
```bash
npm install openai
```sh
npm install --save openai
# or
yarn add openai
```

@@ -15,76 +24,201 @@

The library needs to be configured with your account's secret key, which is available in your [OpenAI account page](https://platform.openai.com/account/api-keys). We recommend setting it as an environment variable. Here's an example of initializing the library with the API key loaded from an environment variable and creating a completion:
```js
import OpenAI from 'openai';
```javascript
const { Configuration, OpenAIApi } = require("openai");
const openAI = new OpenAI({
apiKey: 'my api key', // defaults to process.env["OPENAI_API_KEY"]
});
const configuration = new Configuration({
apiKey: process.env.OPENAI_API_KEY,
async function main() {
const completion = await openAI.completions.create({
model: 'text-davinci-002',
prompt: 'Say this is a test',
max_tokens: 6,
temperature: 0,
});
console.log(completion.choices);
}
main().catch(console.error);
```
## Streaming Responses
We provide support for streaming responses using Server Side Events (SSE).
```ts
import OpenAI from 'openai';
const client = new OpenAI();
const stream = await client.completions.create({
prompt: 'Say this is a test',
model: 'text-davinci-003',
stream: true,
});
const openai = new OpenAIApi(configuration);
for await (const part of stream) {
process.stdout.write(part.choices[0]?.text || '');
}
```
const chatCompletion = await openai.createChatCompletion({
model: "gpt-3.5-turbo",
messages: [{role: "user", content: "Hello world"}],
If you need to cancel a stream, you can `break` from the loop
or call `stream.controller.abort()`.
### Usage with TypeScript
Importing, instantiating, and interacting with the library are the same as above.
If you like, you may reference our types directly:
```ts
import OpenAI from 'openai';
const openAI = new OpenAI({
apiKey: 'my api key', // defaults to process.env["OPENAI_API_KEY"]
});
console.log(chatCompletion.data.choices[0].message);
async function main() {
const params: OpenAI.CompletionCreateParams = {
model: 'text-davinci-002',
prompt: 'Say this is a test',
max_tokens: 6,
temperature: 0,
};
const completion: OpenAI.Completion = await openAI.completions.create(params);
}
main().catch(console.error);
```
Check out the [full API documentation](https://platform.openai.com/docs/api-reference?lang=node.js) for examples of all the available functions.
Documentation for each method, request param, and response field are available in docstrings and will appear on hover in most modern editors.
### Request options
## File Uploads
All of the available API request functions additionally contain an optional final parameter where you can pass custom [axios request options](https://axios-http.com/docs/req_config), for example:
Request parameters that correspond to file uploads can be passed as either a `FormData.Blob` or a `FormData.File` instance.
```javascript
const completion = await openai.createCompletion(
{
model: "text-davinci-003",
prompt: "Hello world",
},
{
timeout: 1000,
headers: {
"Example-Header": "example",
},
}
);
We provide a `fileFromPath` helper function to easily create `FormData.File` instances from a given class.
```ts
import OpenAI, { fileFromPath } from 'openai';
const openAI = new OpenAI();
const file = await fileFromPath('input.jsonl');
await openAI.files.create({ file: file, purpose: 'fine-tune' });
```
### Error handling
## Handling errors
API requests can potentially return errors due to invalid inputs or other issues. These errors can be handled with a `try...catch` statement, and the error details can be found in either `error.response` or `error.message`:
When the library is unable to connect to the API,
or if the API returns a non-success status code (i.e., 4xx or 5xx response),
a subclass of `APIError` will be thrown:
```javascript
try {
const completion = await openai.createCompletion({
model: "text-davinci-003",
prompt: "Hello world",
});
console.log(completion.data.choices[0].text);
} catch (error) {
if (error.response) {
console.log(error.response.status);
console.log(error.response.data);
} else {
console.log(error.message);
}
```ts
async function main() {
const fineTune = await openAI.fineTunes
.create({ training_file: 'file-XGinujblHPwGLSztz8cPS8XY' })
.catch((err) => {
if (err instanceof OpenAI.APIError) {
console.log(err.status); // 400
console.log(err.name); // BadRequestError
console.log(err.headers); // {server: 'nginx', ...}
}
});
}
main().catch(console.error);
```
### Streaming completions
Error codes are as followed:
Streaming completions (`stream=true`) are not natively supported in this package yet, but [a workaround exists](https://github.com/openai/openai-node/issues/18#issuecomment-1369996933) if needed.
| Status Code | Error Type |
| ----------- | -------------------------- |
| 400 | `BadRequestError` |
| 401 | `AuthenticationError` |
| 403 | `PermissionDeniedError` |
| 404 | `NotFoundError` |
| 422 | `UnprocessableEntityError` |
| 429 | `RateLimitError` |
| >=500 | `InternalServerError` |
| N/A | `APIConnectionError` |
## Upgrade guide
### Retries
All breaking changes for major version releases are listed below.
Certain errors will be automatically retried 2 times by default, with a short exponential backoff.
Connection errors (for example, due to a network connectivity problem), 409 Conflict, 429 Rate Limit,
and >=500 Internal errors will all be retried by default.
### 3.0.0
You can use the `maxRetries` option to configure or disable this:
- The function signature of `createCompletion(engineId, params)` changed to `createCompletion(params)`. The value previously passed in as the `engineId` argument should now be passed in as `model` in the params object (e.g. `createCompletion({ model: "text-davinci-003", ... })`)
- Replace any `createCompletionFromModel(params)` calls with `createCompletion(params)`
<!-- prettier-ignore -->
```js
// Configure the default for all requests:
const openAI = new OpenAI({
maxRetries: 0, // default is 2
});
## Thanks
// Or, configure per-request:
openAI.embeddings.create({ model: 'text-similarity-babbage-001',input: 'The food was delicious and the waiter...' }, {
maxRetries: 5,
});
```
Thank you to [ceifa](https://github.com/ceifa) for creating and maintaining the original unofficial `openai` npm package before we released this official library! ceifa's original package has been renamed to [gpt-x](https://www.npmjs.com/package/gpt-x).
### Timeouts
Requests time out after 60 seconds by default. You can configure this with a `timeout` option:
<!-- prettier-ignore -->
```ts
// Configure the default for all requests:
const openAI = new OpenAI({
timeout: 20 * 1000, // 20 seconds (default is 60s)
});
// Override per-request:
openAI.edits.create({ model: 'text-davinci-edit-001',input: 'What day of the wek is it?',instruction: 'Fix the spelling mistakes' }, {
timeout: 5 * 1000,
});
```
On timeout, an `APIConnectionTimeoutError` is thrown.
Note that requests which time out will be [retried twice by default](#retries).
## Configuring an HTTP(S) Agent (e.g., for proxies)
By default, this library uses a stable agent for all http/https requests to reuse TCP connections, eliminating many TCP & TLS handshakes and shaving around 100ms off most requests.
If you would like to disable or customize this behavior, for example to use the API behind a proxy, you can pass an `httpAgent` which is used for all requests (be they http or https), for example:
<!-- prettier-ignore -->
```ts
import http from 'http';
import HttpsProxyAgent from 'https-proxy-agent';
// Configure the default for all requests:
const openAI = new OpenAI({
httpAgent: new HttpsProxyAgent(process.env.PROXY_URL),
});
// Override per-request:
openAI.models.list({
baseURL: 'http://localhost:8080/test-api',
httpAgent: new http.Agent({ keepAlive: false }),
})
```
## Status
This package is in beta. Its internals and interfaces are not stable
and subject to change without a major semver bump;
please reach out if you rely on any undocumented behavior.
We are keen for your feedback; please open an [issue](https://www.github.com/openai/openai-node/issues) with questions, bugs, or suggestions.
## Requirements
The following runtimes are supported:
- Node.js version 12 or higher.
- Deno v1.28.0 or higher (experimental).
Use `import OpenAI from "npm:openai"`.
If you are interested in other runtime environments, please open or upvote an issue on GitHub.
{
"compilerOptions": {
"target": "es2019",
"lib": ["es2020"],
"module": "commonjs",
"moduleResolution": "node",
"esModuleInterop": true,
"rootDir": "./",
"baseUrl": "./",
"paths": {
"~/*": ["*"],
"digest-fetch": ["./typings/digest-fetch"]
},
"declaration": true,
"target": "es6",
"module": "commonjs",
"declarationMap": true,
"outDir": "dist",
"pretty": true,
"sourceMap": true,
"resolveJsonModule": true,
"forceConsistentCasingInFileNames": true,
"strict": true,
"noImplicitAny": true,
"outDir": "dist",
"rootDir": ".",
"typeRoots": [
"node_modules/@types"
]
},
"exclude": [
"dist",
"node_modules"
]
"strictNullChecks": true,
"strictFunctionTypes": true,
"strictBindCallApply": true,
"strictPropertyInitialization": true,
"noImplicitThis": true,
"alwaysStrict": true,
"exactOptionalPropertyTypes": true,
"noUncheckedIndexedAccess": true,
"noImplicitOverride": true,
"noPropertyAccessFromIndexSignature": true,
"skipLibCheck": true
}
}

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc