Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

openai

Package Overview
Dependencies
Maintainers
4
Versions
209
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 4.0.0-beta.2 to 4.0.0-beta.3

LICENSE

3

core.d.ts

@@ -41,2 +41,3 @@ import * as qs from 'qs';

protected defaultHeaders(): Headers;
protected abstract defaultQuery(): DefaultQuery | undefined;
/**

@@ -185,2 +186,3 @@ * Override this to add your own headers validation:

export type Headers = Record<string, string | null | undefined>;
export type DefaultQuery = Record<string, string | undefined>;
export type KeysEnum<T> = {

@@ -209,2 +211,3 @@ [P in keyof Required<T>]: true;

export type APIResponse<T> = T & {
/** @deprecated - we plan to add a different way to access raw response information shortly. */
responseHeaders: Headers;

@@ -211,0 +214,0 @@ };

27

core.js

@@ -191,3 +191,3 @@ 'use strict';

buildRequest(options) {
var _a, _b, _c;
var _a, _b, _c, _d;
const { method, path, query, headers: headers = {} } = options;

@@ -200,11 +200,22 @@ const body =

const url = this.buildURL(path, query);
if ('timeout' in options) validatePositiveInteger('timeout', options.timeout);
const timeout = (_a = options.timeout) !== null && _a !== void 0 ? _a : this.timeout;
const httpAgent =
(
(_b = (_a = options.httpAgent) !== null && _a !== void 0 ? _a : this.httpAgent) !== null &&
_b !== void 0
(_c = (_b = options.httpAgent) !== null && _b !== void 0 ? _b : this.httpAgent) !== null &&
_c !== void 0
) ?
_b
_c
: (0, agent_1.getDefaultAgent)(url);
const timeout = (_c = options.timeout) !== null && _c !== void 0 ? _c : this.timeout;
validatePositiveInteger('timeout', timeout);
const minAgentTimeout = timeout + 1000;
if (
(httpAgent === null || httpAgent === void 0 ? void 0 : httpAgent.options) &&
minAgentTimeout > ((_d = httpAgent.options.timeout) !== null && _d !== void 0 ? _d : 0)
) {
// Allow any given request to bump our agent active socket timeout.
// This may seem strange, but leaking active sockets should be rare and not particularly problematic,
// and without mutating agent we would need to create more of them.
// This tradeoff optimizes for performance.
httpAgent.options.timeout = minAgentTimeout;
}
if (this.idempotencyHeader && method !== 'get') {

@@ -304,2 +315,6 @@ if (!options.idempotencyKey) options.idempotencyKey = this.defaultIdempotencyKey();

: new URL(this.baseURL + (this.baseURL.endsWith('/') && path.startsWith('/') ? path.slice(1) : path));
const defaultQuery = this.defaultQuery();
if (!isEmptyObj(defaultQuery)) {
query = { ...defaultQuery, ...query };
}
if (query) {

@@ -306,0 +321,0 @@ url.search = qs.stringify(query, this.qsOptions());

@@ -13,7 +13,42 @@ import * as qs from 'qs';

apiKey?: string;
/**
* Override the default base URL for the API, e.g., "https://api.example.com/v2/"
*/
baseURL?: string;
/**
* The maximum amount of time (in milliseconds) that the client should wait for a response
* from the server before timing out a single request.
*
* Note that request timeouts are retried by default, so in a worst-case scenario you may wait
* much longer than this timeout before the promise succeeds or fails.
*/
timeout?: number;
/**
* An HTTP agent used to manage HTTP(S) connections.
*
* If not provided, an agent will be constructed by default in the Node.js environment,
* otherwise no agent is used.
*/
httpAgent?: Agent;
/**
* The maximum number of times that the client will retry a request in case of a
* temporary failure, like a network error or a 5XX error from the server.
*
* @default 2
*/
maxRetries?: number;
/**
* Default headers to include with every request to the API.
*
* These can be removed in individual requests by explicitly setting the
* header to `undefined` or `null` in request options.
*/
defaultHeaders?: Core.Headers;
/**
* Default query parameters to include with every request to the API.
*
* These can be removed in individual requests by explicitly setting the
* param to `undefined` in request options.
*/
defaultQuery?: Core.DefaultQuery;
};

@@ -35,2 +70,3 @@ /** Instantiate the API Client. */

fineTunes: API.FineTunes;
protected defaultQuery(): Core.DefaultQuery | undefined;
protected defaultHeaders(): Core.Headers;

@@ -37,0 +73,0 @@ protected authHeaders(): Core.Headers;

@@ -67,2 +67,3 @@ 'use strict';

constructor(config) {
var _a;
const options = {

@@ -80,3 +81,3 @@ apiKey: typeof process === 'undefined' ? '' : process.env['OPENAI_API_KEY'] || '',

baseURL: options.baseURL,
timeout: options.timeout,
timeout: (_a = options.timeout) !== null && _a !== void 0 ? _a : 600000,
httpAgent: options.httpAgent,

@@ -98,2 +99,5 @@ maxRetries: options.maxRetries,

}
defaultQuery() {
return this._options.defaultQuery;
}
defaultHeaders() {

@@ -100,0 +104,0 @@ return {

{
"name": "openai",
"version": "4.0.0-beta.2",
"version": "4.0.0-beta.3",
"description": "Client library for the OpenAI API",

@@ -5,0 +5,0 @@ "author": "OpenAI <support@openai.com>",

@@ -186,3 +186,3 @@ import * as Core from 'openai/core';

*/
logit_bias?: unknown | null;
logit_bias?: Record<string, number> | null;
/**

@@ -384,3 +384,3 @@ * The maximum number of [tokens](/tokenizer) to generate in the chat completion.

*/
logit_bias?: unknown | null;
logit_bias?: Record<string, number> | null;
/**

@@ -387,0 +387,0 @@ * The maximum number of [tokens](/tokenizer) to generate in the chat completion.

@@ -44,3 +44,3 @@ import * as Core from 'openai/core';

tokens?: Array<string>;
top_logprobs?: Array<unknown>;
top_logprobs?: Array<Record<string, number>>;
}

@@ -116,3 +116,3 @@ }

*/
logit_bias?: unknown | null;
logit_bias?: Record<string, number> | null;
/**

@@ -265,3 +265,3 @@ * Include the log probabilities on the `logprobs` most likely tokens, as well the

*/
logit_bias?: unknown | null;
logit_bias?: Record<string, number> | null;
/**

@@ -268,0 +268,0 @@ * Include the log probabilities on the `logprobs` most likely tokens, as well the

@@ -7,2 +7,6 @@ import * as Core from 'openai/core';

* Creates a new edit for the provided input, instruction, and parameters.
*
* @deprecated The Edits API is deprecated; please use Chat Completions instead.
*
* https://openai.com/blog/gpt-4-api-general-availability#deprecation-of-the-edits-api
*/

@@ -29,3 +33,3 @@ create(body: EditCreateParams, options?: Core.RequestOptions): Promise<Core.APIResponse<Edit>>;

tokens?: Array<string>;
top_logprobs?: Array<unknown>;
top_logprobs?: Array<Record<string, number>>;
}

@@ -32,0 +36,0 @@ }

@@ -9,2 +9,6 @@ 'use strict';

* Creates a new edit for the provided input, instruction, and parameters.
*
* @deprecated The Edits API is deprecated; please use Chat Completions instead.
*
* https://openai.com/blog/gpt-4-api-general-availability#deprecation-of-the-edits-api
*/

@@ -11,0 +15,0 @@ create(body, options) {

@@ -35,2 +35,3 @@ import * as Core from 'openai/core';

export declare class FileObjectsPage extends Page<FileObject> {}
type _FileObjectsPage = FileObjectsPage;
export type FileContent = string;

@@ -50,3 +51,3 @@ export interface FileDeleted {

status?: string;
status_details?: unknown | null;
status_details?: string | null;
}

@@ -75,5 +76,6 @@ export interface FileCreateParams {

export import FileObject = API.FileObject;
export import FileObjectsPage = API.FileObjectsPage;
type FileObjectsPage = _FileObjectsPage;
export import FileCreateParams = API.FileCreateParams;
}
export {};
//# sourceMappingURL=files.d.ts.map
'use strict';
// File generated from our OpenAPI spec by Stainless.
var __createBinding =
(this && this.__createBinding) ||
(Object.create ?
function (o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ('get' in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = {
enumerable: true,
get: function () {
return m[k];
},
};
}
Object.defineProperty(o, k2, desc);
}
: function (o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
});
var __setModuleDefault =
(this && this.__setModuleDefault) ||
(Object.create ?
function (o, v) {
Object.defineProperty(o, 'default', { enumerable: true, value: v });
}
: function (o, v) {
o['default'] = v;
});
var __importStar =
(this && this.__importStar) ||
function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null)
for (var k in mod)
if (k !== 'default' && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, '__esModule', { value: true });
exports.FileObjectsPage = exports.Files = void 0;
const resource_1 = require('openai/resource');
const API = __importStar(require('./index.js'));
const core_1 = require('openai/core');

@@ -96,5 +55,3 @@ const pagination_1 = require('openai/pagination');

exports.FileObjectsPage = FileObjectsPage;
(function (Files) {
Files.FileObjectsPage = API.FileObjectsPage;
})((Files = exports.Files || (exports.Files = {})));
(function (Files) {})((Files = exports.Files || (exports.Files = {})));
//# sourceMappingURL=files.js.map

@@ -49,2 +49,3 @@ import * as Core from 'openai/core';

export declare class FineTunesPage extends Page<FineTune> {}
type _FineTunesPage = FineTunesPage;
export interface FineTune {

@@ -54,3 +55,3 @@ id: string;

fine_tuned_model: string | null;
hyperparams: unknown;
hyperparams: FineTune.Hyperparams;
model: string;

@@ -66,2 +67,13 @@ object: string;

}
export declare namespace FineTune {
interface Hyperparams {
batch_size: number;
learning_rate_multiplier: number;
n_epochs: number;
prompt_loss_weight: number;
classification_n_classes?: number;
classification_positive_class?: string;
compute_classification_metrics?: boolean;
}
}
export interface FineTuneEvent {

@@ -225,6 +237,7 @@ created_at: number;

export import FineTuneEventsListResponse = API.FineTuneEventsListResponse;
export import FineTunesPage = API.FineTunesPage;
type FineTunesPage = _FineTunesPage;
export import FineTuneCreateParams = API.FineTuneCreateParams;
export import FineTuneListEventsParams = API.FineTuneListEventsParams;
}
export {};
//# sourceMappingURL=fine-tunes.d.ts.map
'use strict';
// File generated from our OpenAPI spec by Stainless.
var __createBinding =
(this && this.__createBinding) ||
(Object.create ?
function (o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ('get' in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = {
enumerable: true,
get: function () {
return m[k];
},
};
}
Object.defineProperty(o, k2, desc);
}
: function (o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
});
var __setModuleDefault =
(this && this.__setModuleDefault) ||
(Object.create ?
function (o, v) {
Object.defineProperty(o, 'default', { enumerable: true, value: v });
}
: function (o, v) {
o['default'] = v;
});
var __importStar =
(this && this.__importStar) ||
function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null)
for (var k in mod)
if (k !== 'default' && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, '__esModule', { value: true });
exports.FineTunesPage = exports.FineTunes = void 0;
const resource_1 = require('openai/resource');
const API = __importStar(require('./index.js'));
const pagination_1 = require('openai/pagination');

@@ -84,2 +43,3 @@ class FineTunes extends resource_1.APIResource {

query,
timeout: 86400000,
...options,

@@ -99,5 +59,3 @@ stream:

exports.FineTunesPage = FineTunesPage;
(function (FineTunes) {
FineTunes.FineTunesPage = API.FineTunesPage;
})((FineTunes = exports.FineTunes || (exports.FineTunes = {})));
(function (FineTunes) {})((FineTunes = exports.FineTunes || (exports.FineTunes = {})));
//# sourceMappingURL=fine-tunes.js.map

@@ -25,2 +25,3 @@ import * as Core from 'openai/core';

export declare class ModelsPage extends Page<Model> {}
type _ModelsPage = ModelsPage;
export interface Model {

@@ -40,4 +41,5 @@ id: string;

export import ModelDeleted = API.ModelDeleted;
export import ModelsPage = API.ModelsPage;
type ModelsPage = _ModelsPage;
}
export {};
//# sourceMappingURL=models.d.ts.map
'use strict';
// File generated from our OpenAPI spec by Stainless.
var __createBinding =
(this && this.__createBinding) ||
(Object.create ?
function (o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ('get' in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = {
enumerable: true,
get: function () {
return m[k];
},
};
}
Object.defineProperty(o, k2, desc);
}
: function (o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
});
var __setModuleDefault =
(this && this.__setModuleDefault) ||
(Object.create ?
function (o, v) {
Object.defineProperty(o, 'default', { enumerable: true, value: v });
}
: function (o, v) {
o['default'] = v;
});
var __importStar =
(this && this.__importStar) ||
function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null)
for (var k in mod)
if (k !== 'default' && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, '__esModule', { value: true });
exports.ModelsPage = exports.Models = void 0;
const resource_1 = require('openai/resource');
const API = __importStar(require('./index.js'));
const pagination_1 = require('openai/pagination');

@@ -76,5 +35,3 @@ class Models extends resource_1.APIResource {

exports.ModelsPage = ModelsPage;
(function (Models) {
Models.ModelsPage = API.ModelsPage;
})((Models = exports.Models || (exports.Models = {})));
(function (Models) {})((Models = exports.Models || (exports.Models = {})));
//# sourceMappingURL=models.js.map

@@ -6,3 +6,3 @@ /**

import { fileFromPath as _fileFromPath } from 'formdata-node/file-from-path';
import type { File, FilePropertyBag } from './formdata.node';
import type { File, FilePropertyBag } from './formdata.node.js';

@@ -9,0 +9,0 @@ export type FileFromPathOptions = Omit<FilePropertyBag, 'lastModified'>;

@@ -8,3 +8,3 @@ /**

import type { FilePropertyBag, File } from './formdata';
import type { FilePropertyBag, File } from './formdata.js';

@@ -11,0 +11,0 @@ export type FileFromPathOptions = Omit<FilePropertyBag, 'lastModified'>;

@@ -5,3 +5,3 @@ /**

import { FormData } from './formdata.node';
import { FormData } from './formdata.node.js';
import type { RequestOptions } from '../core';

@@ -8,0 +8,0 @@ import { Readable } from 'node:stream';

@@ -5,3 +5,3 @@ /**

import { FormData } from './formdata';
import { FormData } from './formdata.js';
import type { RequestOptions } from '../core';

@@ -8,0 +8,0 @@ import { MultipartBody } from '../uploads';

@@ -5,4 +5,4 @@ import * as qs from 'qs';

import { APIError, APIConnectionError, APIConnectionTimeoutError } from './error';
import type { Readable } from 'openai/_shims/node-readable';
import { getDefaultAgent, type Agent } from 'openai/_shims/agent';
import type { Readable } from './_shims/node-readable';
import { getDefaultAgent, type Agent } from './_shims/agent';
import {

@@ -14,3 +14,3 @@ fetch,

type Response,
} from 'openai/_shims/fetch';
} from './_shims/fetch.js';
import { isMultipartBody } from './uploads';

@@ -78,2 +78,4 @@ export {

protected abstract defaultQuery(): DefaultQuery | undefined;
/**

@@ -136,5 +138,13 @@ * Override this to add your own headers validation:

const url = this.buildURL(path!, query);
if ('timeout' in options) validatePositiveInteger('timeout', options.timeout);
const timeout = options.timeout ?? this.timeout;
const httpAgent = options.httpAgent ?? this.httpAgent ?? getDefaultAgent(url);
const timeout = options.timeout ?? this.timeout;
validatePositiveInteger('timeout', timeout);
const minAgentTimeout = timeout + 1000;
if ((httpAgent as any)?.options && minAgentTimeout > ((httpAgent as any).options.timeout ?? 0)) {
// Allow any given request to bump our agent active socket timeout.
// This may seem strange, but leaking active sockets should be rare and not particularly problematic,
// and without mutating agent we would need to create more of them.
// This tradeoff optimizes for performance.
(httpAgent as any).options.timeout = minAgentTimeout;
}

@@ -267,2 +277,7 @@ if (this.idempotencyHeader && method !== 'get') {

const defaultQuery = this.defaultQuery();
if (!isEmptyObj(defaultQuery)) {
query = { ...defaultQuery, ...query } as Req;
}
if (query) {

@@ -524,2 +539,3 @@ url.search = qs.stringify(query, this.qsOptions());

export type Headers = Record<string, string | null | undefined>;
export type DefaultQuery = Record<string, string | undefined>;
export type KeysEnum<T> = { [P in keyof Required<T>]: true };

@@ -573,2 +589,3 @@

export type APIResponse<T> = T & {
/** @deprecated - we plan to add a different way to access raw response information shortly. */
responseHeaders: Headers;

@@ -575,0 +592,0 @@ };

@@ -8,3 +8,3 @@ // File generated from our OpenAPI spec by Stainless.

import * as Errors from './error';
import type { Agent } from 'openai/_shims/agent';
import type { Agent } from './_shims/agent';
import * as Uploads from './uploads';

@@ -17,7 +17,48 @@

apiKey?: string;
/**
* Override the default base URL for the API, e.g., "https://api.example.com/v2/"
*/
baseURL?: string;
/**
* The maximum amount of time (in milliseconds) that the client should wait for a response
* from the server before timing out a single request.
*
* Note that request timeouts are retried by default, so in a worst-case scenario you may wait
* much longer than this timeout before the promise succeeds or fails.
*/
timeout?: number;
/**
* An HTTP agent used to manage HTTP(S) connections.
*
* If not provided, an agent will be constructed by default in the Node.js environment,
* otherwise no agent is used.
*/
httpAgent?: Agent;
/**
* The maximum number of times that the client will retry a request in case of a
* temporary failure, like a network error or a 5XX error from the server.
*
* @default 2
*/
maxRetries?: number;
/**
* Default headers to include with every request to the API.
*
* These can be removed in individual requests by explicitly setting the
* header to `undefined` or `null` in request options.
*/
defaultHeaders?: Core.Headers;
/**
* Default query parameters to include with every request to the API.
*
* These can be removed in individual requests by explicitly setting the
* param to `undefined` in request options.
*/
defaultQuery?: Core.DefaultQuery;
};

@@ -46,3 +87,3 @@

baseURL: options.baseURL!,
timeout: options.timeout,
timeout: options.timeout ?? 600000,
httpAgent: options.httpAgent,

@@ -66,2 +107,6 @@ maxRetries: options.maxRetries,

protected override defaultQuery(): Core.DefaultQuery | undefined {
return this._options.defaultQuery;
}
protected override defaultHeaders(): Core.Headers {

@@ -68,0 +113,0 @@ return {

// File generated from our OpenAPI spec by Stainless.
import { APIResource } from 'openai/resource';
import { APIResource } from '../../resource';
import { Transcriptions } from './transcriptions';
import { Translations } from './translations';
import * as API from './';
import * as API from '.';

@@ -8,0 +8,0 @@ export class Audio extends APIResource {

// File generated from our OpenAPI spec by Stainless.
import * as Core from 'openai/core';
import { APIResource } from 'openai/resource';
import * as API from './';
import { type Uploadable, multipartFormRequestOptions } from 'openai/core';
import * as Core from '../../core';
import { APIResource } from '../../resource';
import * as API from '.';
import { type Uploadable, multipartFormRequestOptions } from '../../core';

@@ -8,0 +8,0 @@ export class Transcriptions extends APIResource {

// File generated from our OpenAPI spec by Stainless.
import * as Core from 'openai/core';
import { APIResource } from 'openai/resource';
import * as API from './';
import { type Uploadable, multipartFormRequestOptions } from 'openai/core';
import * as Core from '../../core';
import { APIResource } from '../../resource';
import * as API from '.';
import { type Uploadable, multipartFormRequestOptions } from '../../core';

@@ -8,0 +8,0 @@ export class Translations extends APIResource {

// File generated from our OpenAPI spec by Stainless.
import { APIResource } from 'openai/resource';
import { APIResource } from '../../resource';
import { Completions } from './completions';
import * as API from './';
import * as API from '.';

@@ -7,0 +7,0 @@ export class Chat extends APIResource {

// File generated from our OpenAPI spec by Stainless.
import * as Core from 'openai/core';
import { APIResource } from 'openai/resource';
import * as API from './';
import { Stream } from 'openai/streaming';
import * as Core from '../../core';
import { APIResource } from '../../resource';
import * as API from '.';
import { Stream } from '../../streaming';

@@ -232,3 +232,3 @@ export class Completions extends APIResource {

*/
logit_bias?: unknown | null;
logit_bias?: Record<string, number> | null;

@@ -455,3 +455,3 @@ /**

*/
logit_bias?: unknown | null;
logit_bias?: Record<string, number> | null;

@@ -458,0 +458,0 @@ /**

// File generated from our OpenAPI spec by Stainless.
import * as Core from 'openai/core';
import { APIResource } from 'openai/resource';
import * as API from './';
import { Stream } from 'openai/streaming';
import * as Core from '../core';
import { APIResource } from '../resource';
import * as API from '.';
import { Stream } from '../streaming';

@@ -70,3 +70,3 @@ export class Completions extends APIResource {

top_logprobs?: Array<unknown>;
top_logprobs?: Array<Record<string, number>>;
}

@@ -149,3 +149,3 @@ }

*/
logit_bias?: unknown | null;
logit_bias?: Record<string, number> | null;

@@ -315,3 +315,3 @@ /**

*/
logit_bias?: unknown | null;
logit_bias?: Record<string, number> | null;

@@ -318,0 +318,0 @@ /**

// File generated from our OpenAPI spec by Stainless.
import * as Core from 'openai/core';
import { APIResource } from 'openai/resource';
import * as API from './';
import * as Core from '../core';
import { APIResource } from '../resource';
import * as API from '.';

@@ -10,2 +10,6 @@ export class Edits extends APIResource {

* Creates a new edit for the provided input, instruction, and parameters.
*
* @deprecated The Edits API is deprecated; please use Chat Completions instead.
*
* https://openai.com/blog/gpt-4-api-general-availability#deprecation-of-the-edits-api
*/

@@ -46,3 +50,3 @@ create(body: EditCreateParams, options?: Core.RequestOptions): Promise<Core.APIResponse<Edit>> {

top_logprobs?: Array<unknown>;
top_logprobs?: Array<Record<string, number>>;
}

@@ -49,0 +53,0 @@ }

// File generated from our OpenAPI spec by Stainless.
import * as Core from 'openai/core';
import { APIResource } from 'openai/resource';
import * as API from './';
import * as Core from '../core';
import { APIResource } from '../resource';
import * as API from '.';

@@ -7,0 +7,0 @@ export class Embeddings extends APIResource {

// File generated from our OpenAPI spec by Stainless.
import * as Core from 'openai/core';
import { APIResource } from 'openai/resource';
import * as API from './';
import { type Uploadable, multipartFormRequestOptions } from 'openai/core';
import { Page } from 'openai/pagination';
import * as Core from '../core';
import { APIResource } from '../resource';
import * as API from '.';
import { type Uploadable, multipartFormRequestOptions } from '../core';
import { Page } from '../pagination';

@@ -56,2 +56,4 @@ export class Files extends APIResource {

export class FileObjectsPage extends Page<FileObject> {}
// alias so we can export it in the namespace
type _FileObjectsPage = FileObjectsPage;

@@ -83,3 +85,3 @@ export type FileContent = string;

status_details?: unknown | null;
status_details?: string | null;
}

@@ -111,4 +113,4 @@

export import FileObject = API.FileObject;
export import FileObjectsPage = API.FileObjectsPage;
export type FileObjectsPage = _FileObjectsPage;
export import FileCreateParams = API.FileCreateParams;
}
// File generated from our OpenAPI spec by Stainless.
import * as Core from 'openai/core';
import { APIResource } from 'openai/resource';
import * as Files from 'openai/resources/files';
import * as API from './';
import { Page } from 'openai/pagination';
import { Stream } from 'openai/streaming';
import * as Core from '../core';
import { APIResource } from '../resource';
import * as Files from './files';
import * as API from '.';
import { Page } from '../pagination';
import { Stream } from '../streaming';

@@ -66,2 +66,3 @@ export class FineTunes extends APIResource {

query,
timeout: 86400000,
...options,

@@ -77,2 +78,4 @@ stream: query?.stream ?? false,

export class FineTunesPage extends Page<FineTune> {}
// alias so we can export it in the namespace
type _FineTunesPage = FineTunesPage;

@@ -86,3 +89,3 @@ export interface FineTune {

hyperparams: unknown;
hyperparams: FineTune.Hyperparams;

@@ -108,2 +111,20 @@ model: string;

export namespace FineTune {
export interface Hyperparams {
batch_size: number;
learning_rate_multiplier: number;
n_epochs: number;
prompt_loss_weight: number;
classification_n_classes?: number;
classification_positive_class?: string;
compute_classification_metrics?: boolean;
}
}
export interface FineTuneEvent {

@@ -288,5 +309,5 @@ created_at: number;

export import FineTuneEventsListResponse = API.FineTuneEventsListResponse;
export import FineTunesPage = API.FineTunesPage;
export type FineTunesPage = _FineTunesPage;
export import FineTuneCreateParams = API.FineTuneCreateParams;
export import FineTuneListEventsParams = API.FineTuneListEventsParams;
}
// File generated from our OpenAPI spec by Stainless.
import * as Core from 'openai/core';
import { APIResource } from 'openai/resource';
import * as API from './';
import { type Uploadable, multipartFormRequestOptions } from 'openai/core';
import * as Core from '../core';
import { APIResource } from '../resource';
import * as API from '.';
import { type Uploadable, multipartFormRequestOptions } from '../core';

@@ -8,0 +8,0 @@ export class Images extends APIResource {

// File generated from our OpenAPI spec by Stainless.
import * as Core from 'openai/core';
import { APIResource } from 'openai/resource';
import * as API from './';
import { Page } from 'openai/pagination';
import * as Core from '../core';
import { APIResource } from '../resource';
import * as API from '.';
import { Page } from '../pagination';

@@ -37,2 +37,4 @@ export class Models extends APIResource {

export class ModelsPage extends Page<Model> {}
// alias so we can export it in the namespace
type _ModelsPage = ModelsPage;

@@ -60,3 +62,3 @@ export interface Model {

export import ModelDeleted = API.ModelDeleted;
export import ModelsPage = API.ModelsPage;
export type ModelsPage = _ModelsPage;
}
// File generated from our OpenAPI spec by Stainless.
import * as Core from 'openai/core';
import { APIResource } from 'openai/resource';
import * as API from './';
import * as Core from '../core';
import { APIResource } from '../resource';
import * as API from '.';

@@ -7,0 +7,0 @@ export class Moderations extends APIResource {

@@ -1,4 +0,7 @@

import type { Response } from 'openai/_shims/fetch';
import type { Response } from './_shims/fetch.js';
import { APIResponse, Headers, createResponseHeaders } from './core';
type Bytes = string | ArrayBuffer | Uint8Array | Buffer | null | undefined;
type ServerSentEvent = {

@@ -10,59 +13,6 @@ event: string | null;

class SSEDecoder {
private data: string[];
private event: string | null;
private chunks: string[];
constructor() {
this.event = null;
this.data = [];
this.chunks = [];
}
decode(line: string) {
if (line.endsWith('\r')) {
line = line.substring(0, line.length - 1);
}
if (!line) {
// empty line and we didn't previously encounter any messages
if (!this.event && !this.data.length) return null;
const sse: ServerSentEvent = {
event: this.event,
data: this.data.join('\n'),
raw: this.chunks,
};
this.event = null;
this.data = [];
this.chunks = [];
return sse;
}
this.chunks.push(line);
if (line.startsWith(':')) {
return null;
}
let [fieldname, _, value] = partition(line, ':');
if (value.startsWith(' ')) {
value = value.substring(1);
}
if (fieldname === 'event') {
this.event = value;
} else if (fieldname === 'data') {
this.data.push(value);
}
return null;
}
}
export class Stream<Item> implements AsyncIterable<Item>, APIResponse<Stream<Item>> {
/** @deprecated - please use the async iterator instead. We plan to add additional helper methods shortly. */
response: Response;
/** @deprecated - we plan to add a different way to access raw response information shortly. */
responseHeaders: Headers;

@@ -85,17 +35,7 @@ controller: AbortController;

}
const lineDecoder = new LineDecoder();
// @ts-ignore
for await (const chunk of this.response.body) {
let text;
if (chunk instanceof Buffer) {
text = chunk.toString();
} else if ((chunk as any) instanceof Uint8Array) {
text = Buffer.from(chunk).toString();
} else {
text = chunk;
}
for (const line of lineDecoder.decode(text)) {
const iter = readableStreamAsyncIterable<Bytes>(this.response.body);
for await (const chunk of iter) {
for (const line of lineDecoder.decode(chunk)) {
const sse = this.decoder.decode(line);

@@ -140,4 +80,57 @@ if (sse) yield sse;

const NEWLINE_CHARS = '\n\r\x0b\x0c\x1c\x1d\x1e\x85\u2028\u2029';
class SSEDecoder {
private data: string[];
private event: string | null;
private chunks: string[];
constructor() {
this.event = null;
this.data = [];
this.chunks = [];
}
decode(line: string) {
if (line.endsWith('\r')) {
line = line.substring(0, line.length - 1);
}
if (!line) {
// empty line and we didn't previously encounter any messages
if (!this.event && !this.data.length) return null;
const sse: ServerSentEvent = {
event: this.event,
data: this.data.join('\n'),
raw: this.chunks,
};
this.event = null;
this.data = [];
this.chunks = [];
return sse;
}
this.chunks.push(line);
if (line.startsWith(':')) {
return null;
}
let [fieldname, _, value] = partition(line, ':');
if (value.startsWith(' ')) {
value = value.substring(1);
}
if (fieldname === 'event') {
this.event = value;
} else if (fieldname === 'data') {
this.data.push(value);
}
return null;
}
}
/**

@@ -150,4 +143,9 @@ * A re-implementation of httpx's `LineDecoder` in Python that handles incrementally

class LineDecoder {
// prettier-ignore
static NEWLINE_CHARS = new Set(['\n', '\r', '\x0b', '\x0c', '\x1c', '\x1d', '\x1e', '\x85', '\u2028', '\u2029']);
static NEWLINE_REGEXP = /\r\n|[\n\r\x0b\x0c\x1c\x1d\x1e\x85\u2028\u2029]/g;
buffer: string[];
trailingCR: boolean;
textDecoder: any; // TextDecoder found in browsers; not typed to avoid pulling in either "dom" or "node" types.

@@ -159,3 +157,5 @@ constructor() {

decode(text: string): string[] {
decode(chunk: Bytes): string[] {
let text = this.decodeText(chunk);
if (this.trailingCR) {

@@ -174,6 +174,6 @@ text = '\r' + text;

const trailing_newline = NEWLINE_CHARS.includes(text.slice(-1));
let lines = text.split(/\r\n|[\n\r\x0b\x0c\x1c\x1d\x1e\x85\u2028\u2029]/g);
const trailingNewline = LineDecoder.NEWLINE_CHARS.has(text[text.length - 1] || '');
let lines = text.split(LineDecoder.NEWLINE_REGEXP);
if (lines.length === 1 && !trailing_newline) {
if (lines.length === 1 && !trailingNewline) {
this.buffer.push(lines[0]!);

@@ -188,3 +188,3 @@ return [];

if (!trailing_newline) {
if (!trailingNewline) {
this.buffer = [lines.pop() || ''];

@@ -196,2 +196,39 @@ }

decodeText(bytes: Bytes): string {
if (bytes == null) return '';
if (typeof bytes === 'string') return bytes;
// Node:
if (typeof Buffer !== 'undefined') {
if (bytes instanceof Buffer) {
return bytes.toString();
}
if (bytes instanceof Uint8Array) {
return Buffer.from(bytes).toString();
}
throw new Error(
`Unexpected: received non-Uint8Array (${bytes.constructor.name}) stream chunk in an environment with a global "Buffer" defined, which this library assumes to be Node. Please report this error.`,
);
}
// Browser
if (typeof TextDecoder !== 'undefined') {
if (bytes instanceof Uint8Array || bytes instanceof ArrayBuffer) {
this.textDecoder ??= new TextDecoder('utf8');
return this.textDecoder.decode(bytes);
}
throw new Error(
`Unexpected: received non-Uint8Array/ArrayBuffer (${
(bytes as any).constructor.name
}) in a web platform. Please report this error.`,
);
}
throw new Error(
`Unexpected: neither Buffer nor TextDecoder are available as globals. Please report this error.`,
);
}
flush(): string[] {

@@ -217,1 +254,26 @@ if (!this.buffer.length && !this.trailingCR) {

}
/**
* Most browsers don't yet have async iterable support for ReadableStream,
* and Node has a very different way of reading bytes from its "ReadableStream".
*
* This polyfill was pulled from https://github.com/MattiasBuelens/web-streams-polyfill/pull/122#issuecomment-1624185965
*/
function readableStreamAsyncIterable<T>(stream: any): AsyncIterableIterator<T> {
if (stream[Symbol.asyncIterator]) return stream[Symbol.asyncIterator];
const reader = stream.getReader();
return {
next() {
return reader.read();
},
async return() {
reader.cancel();
reader.releaseLock();
return { done: true, value: undefined };
},
[Symbol.asyncIterator]() {
return this;
},
};
}
import { type RequestOptions } from './core';
import { type Readable } from 'openai/_shims/node-readable';
import { type BodyInit } from 'openai/_shims/fetch';
import { FormData, File, type FilePropertyBag } from 'openai/_shims/formdata';
import { getMultipartRequestOptions } from 'openai/_shims/getMultipartRequestOptions';
import { fileFromPath } from 'openai/_shims/fileFromPath';
import { type FsReadStream, isFsReadStream } from 'openai/_shims/node-readable';
import { type Readable } from './_shims/node-readable';
import { type BodyInit } from './_shims/fetch.js';
import { FormData, File, type FilePropertyBag } from './_shims/formdata.js';
import { getMultipartRequestOptions } from './_shims/getMultipartRequestOptions';
import { fileFromPath } from './_shims/fileFromPath';
import { type FsReadStream, isFsReadStream } from './_shims/node-readable';

@@ -99,3 +99,3 @@ export { fileFromPath };

export async function toFile(
value: ToFileInput,
value: ToFileInput | PromiseLike<ToFileInput>,
name?: string | null | undefined,

@@ -125,4 +125,5 @@ options: FilePropertyBag | undefined = {},

async function getBytes(value: ToFileInput): Promise<Array<BlobPart>> {
if (value instanceof Promise) return getBytes(await (value as any));
async function getBytes(value: ToFileInput | PromiseLike<ToFileInput>): Promise<Array<BlobPart>> {
// resolve input promise or promiselike object
value = await value;

@@ -129,0 +130,0 @@ let parts: Array<BlobPart> = [];

@@ -1,1 +0,1 @@

export const VERSION = '4.0.0-beta.2';
export const VERSION = '4.0.0-beta.3';
import type { Response } from 'openai/_shims/fetch';
import { APIResponse, Headers } from './core.js';
export declare class Stream<Item> implements AsyncIterable<Item>, APIResponse<Stream<Item>> {
/** @deprecated - please use the async iterator instead. We plan to add additional helper methods shortly. */
response: Response;
/** @deprecated - we plan to add a different way to access raw response information shortly. */
responseHeaders: Headers;

@@ -6,0 +8,0 @@ controller: AbortController;

@@ -5,41 +5,2 @@ 'use strict';

const core_1 = require('./core.js');
class SSEDecoder {
constructor() {
this.event = null;
this.data = [];
this.chunks = [];
}
decode(line) {
if (line.endsWith('\r')) {
line = line.substring(0, line.length - 1);
}
if (!line) {
// empty line and we didn't previously encounter any messages
if (!this.event && !this.data.length) return null;
const sse = {
event: this.event,
data: this.data.join('\n'),
raw: this.chunks,
};
this.event = null;
this.data = [];
this.chunks = [];
return sse;
}
this.chunks.push(line);
if (line.startsWith(':')) {
return null;
}
let [fieldname, _, value] = partition(line, ':');
if (value.startsWith(' ')) {
value = value.substring(1);
}
if (fieldname === 'event') {
this.event = value;
} else if (fieldname === 'data') {
this.data.push(value);
}
return null;
}
}
class Stream {

@@ -58,13 +19,5 @@ constructor(response, controller) {

const lineDecoder = new LineDecoder();
// @ts-ignore
for await (const chunk of this.response.body) {
let text;
if (chunk instanceof Buffer) {
text = chunk.toString();
} else if (chunk instanceof Uint8Array) {
text = Buffer.from(chunk).toString();
} else {
text = chunk;
}
for (const line of lineDecoder.decode(text)) {
const iter = readableStreamAsyncIterable(this.response.body);
for await (const chunk of iter) {
for (const line of lineDecoder.decode(chunk)) {
const sse = this.decoder.decode(line);

@@ -106,3 +59,41 @@ if (sse) yield sse;

exports.Stream = Stream;
const NEWLINE_CHARS = '\n\r\x0b\x0c\x1c\x1d\x1e\x85\u2028\u2029';
class SSEDecoder {
constructor() {
this.event = null;
this.data = [];
this.chunks = [];
}
decode(line) {
if (line.endsWith('\r')) {
line = line.substring(0, line.length - 1);
}
if (!line) {
// empty line and we didn't previously encounter any messages
if (!this.event && !this.data.length) return null;
const sse = {
event: this.event,
data: this.data.join('\n'),
raw: this.chunks,
};
this.event = null;
this.data = [];
this.chunks = [];
return sse;
}
this.chunks.push(line);
if (line.startsWith(':')) {
return null;
}
let [fieldname, _, value] = partition(line, ':');
if (value.startsWith(' ')) {
value = value.substring(1);
}
if (fieldname === 'event') {
this.event = value;
} else if (fieldname === 'data') {
this.data.push(value);
}
return null;
}
}
/**

@@ -119,3 +110,4 @@ * A re-implementation of httpx's `LineDecoder` in Python that handles incrementally

}
decode(text) {
decode(chunk) {
let text = this.decodeText(chunk);
if (this.trailingCR) {

@@ -132,5 +124,5 @@ text = '\r' + text;

}
const trailing_newline = NEWLINE_CHARS.includes(text.slice(-1));
let lines = text.split(/\r\n|[\n\r\x0b\x0c\x1c\x1d\x1e\x85\u2028\u2029]/g);
if (lines.length === 1 && !trailing_newline) {
const trailingNewline = LineDecoder.NEWLINE_CHARS.has(text[text.length - 1] || '');
let lines = text.split(LineDecoder.NEWLINE_REGEXP);
if (lines.length === 1 && !trailingNewline) {
this.buffer.push(lines[0]);

@@ -143,3 +135,3 @@ return [];

}
if (!trailing_newline) {
if (!trailingNewline) {
this.buffer = [lines.pop() || ''];

@@ -149,2 +141,32 @@ }

}
decodeText(bytes) {
var _a;
if (bytes == null) return '';
if (typeof bytes === 'string') return bytes;
// Node:
if (typeof Buffer !== 'undefined') {
if (bytes instanceof Buffer) {
return bytes.toString();
}
if (bytes instanceof Uint8Array) {
return Buffer.from(bytes).toString();
}
throw new Error(
`Unexpected: received non-Uint8Array (${bytes.constructor.name}) stream chunk in an environment with a global "Buffer" defined, which this library assumes to be Node. Please report this error.`,
);
}
// Browser
if (typeof TextDecoder !== 'undefined') {
if (bytes instanceof Uint8Array || bytes instanceof ArrayBuffer) {
(_a = this.textDecoder) !== null && _a !== void 0 ? _a : (this.textDecoder = new TextDecoder('utf8'));
return this.textDecoder.decode(bytes);
}
throw new Error(
`Unexpected: received non-Uint8Array/ArrayBuffer (${bytes.constructor.name}) in a web platform. Please report this error.`,
);
}
throw new Error(
`Unexpected: neither Buffer nor TextDecoder are available as globals. Please report this error.`,
);
}
flush() {

@@ -160,2 +182,5 @@ if (!this.buffer.length && !this.trailingCR) {

}
// prettier-ignore
LineDecoder.NEWLINE_CHARS = new Set(['\n', '\r', '\x0b', '\x0c', '\x1c', '\x1d', '\x1e', '\x85', '\u2028', '\u2029']);
LineDecoder.NEWLINE_REGEXP = /\r\n|[\n\r\x0b\x0c\x1c\x1d\x1e\x85\u2028\u2029]/g;
function partition(str, delimiter) {

@@ -168,2 +193,25 @@ const index = str.indexOf(delimiter);

}
/**
* Most browsers don't yet have async iterable support for ReadableStream,
* and Node has a very different way of reading bytes from its "ReadableStream".
*
* This polyfill was pulled from https://github.com/MattiasBuelens/web-streams-polyfill/pull/122#issuecomment-1624185965
*/
function readableStreamAsyncIterable(stream) {
if (stream[Symbol.asyncIterator]) return stream[Symbol.asyncIterator];
const reader = stream.getReader();
return {
next() {
return reader.read();
},
async return() {
reader.cancel();
reader.releaseLock();
return { done: true, value: undefined };
},
[Symbol.asyncIterator]() {
return this;
},
};
}
//# sourceMappingURL=streaming.js.map

@@ -69,3 +69,3 @@ import { type RequestOptions } from './core.js';

export declare function toFile(
value: ToFileInput,
value: ToFileInput | PromiseLike<ToFileInput>,
name?: string | null | undefined,

@@ -72,0 +72,0 @@ options?: FilePropertyBag | undefined,

@@ -92,3 +92,4 @@ 'use strict';

var _a;
if (value instanceof Promise) return getBytes(await value);
// resolve input promise or promiselike object
value = await value;
let parts = [];

@@ -95,0 +96,0 @@ if (

@@ -1,2 +0,2 @@

export declare const VERSION = '4.0.0-beta.2';
export declare const VERSION = '4.0.0-beta.3';
//# sourceMappingURL=version.d.ts.map
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
exports.VERSION = void 0;
exports.VERSION = '4.0.0-beta.2';
exports.VERSION = '4.0.0-beta.3';
//# sourceMappingURL=version.js.map

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

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

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

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

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

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

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

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