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.8 to 4.0.0-beta.9

bin/cli

9

_shims/fetch.d.ts

@@ -29,2 +29,4 @@ /**

// @ts-ignore
type _ResponseType = unknown extends ResponseType ? never : ResponseType;
// @ts-ignore
type _BodyInit = unknown extends BodyInit ? never : BodyInit;

@@ -53,2 +55,7 @@ // @ts-ignore

export { _fetch as fetch, _Request as Request, _Response as Response, _Headers as Headers };
export type { _RequestInit as RequestInit, _RequestInfo as RequestInfo, _BodyInit as BodyInit };
export type {
_RequestInit as RequestInit,
_RequestInfo as RequestInfo,
_ResponseType as ResponseType,
_BodyInit as BodyInit,
};

@@ -29,2 +29,7 @@ /**

type _ResponseInit = unknown extends ResponseInit ? nf.ResponseInit : ResponseInit;
type _ResponseType =
// @ts-ignore
unknown extends ResponseType ? 'basic' | 'cors' | 'default' | 'error' | 'opaque' | 'opaqueredirect'
: // @ts-ignore
ResponseType;
// @ts-ignore

@@ -54,2 +59,7 @@ type _BodyInit = unknown extends BodyInit ? nf.BodyInit : BodyInit;

export { _fetch as fetch, _Request as Request, _Response as Response, _Headers as Headers };
export type { _RequestInit as RequestInit, _RequestInfo as RequestInfo, _BodyInit as BodyInit };
export type {
_RequestInit as RequestInit,
_RequestInfo as RequestInfo,
_ResponseType as ResponseType,
_BodyInit as BodyInit,
};

102

core.d.ts

@@ -5,2 +5,3 @@ import { APIError } from './error.js';

import { type RequestInfo, type RequestInit, type Response } from 'openai/_shims/fetch';
export { type Response };
export {

@@ -13,2 +14,49 @@ maybeMultipartFormRequestOptions,

export type Fetch = (url: RequestInfo, init?: RequestInit) => Promise<Response>;
type PromiseOrValue<T> = T | Promise<T>;
type APIResponseProps = {
response: Response;
options: FinalRequestOptions;
controller: AbortController;
};
/**
* A subclass of `Promise` providing additional helper methods
* for interacting with the SDK.
*/
export declare class APIPromise<T> extends Promise<T> {
private responsePromise;
private parseResponse;
private parsedPromise;
constructor(
responsePromise: Promise<APIResponseProps>,
parseResponse?: (props: APIResponseProps) => PromiseOrValue<T>,
);
_thenUnwrap<U>(transform: (data: T) => U): APIPromise<U>;
/**
* Gets the raw `Response` instance instead of parsing the response
* data.
*
* If you want to parse the response body but still get the `Response`
* instance, you can use {@link withResponse()}.
*/
asResponse(): Promise<Response>;
/**
* Gets the parsed response data and the raw `Response` instance.
*
* If you just want to get the raw `Response` instance without parsing it,
* you can use {@link asResponse()}.
*/
withResponse(): Promise<{
data: T;
response: Response;
}>;
private parse;
then<TResult1 = T, TResult2 = never>(
onfulfilled?: ((value: T) => TResult1 | PromiseLike<TResult1>) | undefined | null,
onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | undefined | null,
): Promise<TResult1 | TResult2>;
catch<TResult = never>(
onrejected?: ((reason: any) => TResult | PromiseLike<TResult>) | undefined | null,
): Promise<T | TResult>;
finally(onfinally?: (() => void) | undefined | null): Promise<T>;
}
export declare abstract class APIClient {

@@ -50,7 +98,8 @@ baseURL: string;

protected defaultIdempotencyKey(): string;
get<Req extends {}, Rsp>(path: string, opts?: RequestOptions<Req>): Promise<Rsp>;
post<Req extends {}, Rsp>(path: string, opts?: RequestOptions<Req>): Promise<Rsp>;
patch<Req extends {}, Rsp>(path: string, opts?: RequestOptions<Req>): Promise<Rsp>;
put<Req extends {}, Rsp>(path: string, opts?: RequestOptions<Req>): Promise<Rsp>;
delete<Req extends {}, Rsp>(path: string, opts?: RequestOptions<Req>): Promise<Rsp>;
get<Req extends {}, Rsp>(path: string, opts?: PromiseOrValue<RequestOptions<Req>>): APIPromise<Rsp>;
post<Req extends {}, Rsp>(path: string, opts?: PromiseOrValue<RequestOptions<Req>>): APIPromise<Rsp>;
patch<Req extends {}, Rsp>(path: string, opts?: PromiseOrValue<RequestOptions<Req>>): APIPromise<Rsp>;
put<Req extends {}, Rsp>(path: string, opts?: PromiseOrValue<RequestOptions<Req>>): APIPromise<Rsp>;
delete<Req extends {}, Rsp>(path: string, opts?: PromiseOrValue<RequestOptions<Req>>): APIPromise<Rsp>;
private methodRequest;
getAPIList<Item, PageClass extends AbstractPage<Item> = AbstractPage<Item>>(

@@ -60,3 +109,3 @@ path: string,

opts?: RequestOptions<any>,
): PagePromise<PageClass>;
): PagePromise<PageClass, Item>;
private calculateContentLength;

@@ -91,9 +140,10 @@ buildRequest<Req extends {}>(

request<Req extends {}, Rsp>(
options: FinalRequestOptions<Req>,
retriesRemaining?: number,
): Promise<APIResponse<Rsp>>;
options: PromiseOrValue<FinalRequestOptions<Req>>,
remainingRetries?: number | null,
): APIPromise<Rsp>;
private makeRequest;
requestAPIList<Item = unknown, PageClass extends AbstractPage<Item> = AbstractPage<Item>>(
Page: new (...args: ConstructorParameters<typeof AbstractPage>) => PageClass,
options: FinalRequestOptions,
): PagePromise<PageClass>;
): PagePromise<PageClass, Item>;
buildURL<Req>(path: string, query: Req | undefined): string;

@@ -112,3 +162,2 @@ protected stringifyQuery(query: Record<string, unknown>): string;

private getUserAgent;
private debug;
}

@@ -135,3 +184,5 @@ export declare class APIResource {

protected options: FinalRequestOptions;
constructor(client: APIClient, response: APIResponse<unknown>, options: FinalRequestOptions);
protected response: Response;
protected body: unknown;
constructor(client: APIClient, response: Response, body: unknown, options: FinalRequestOptions);
/**

@@ -148,2 +199,11 @@ * @deprecated Use nextPageInfo instead

}
/**
* This subclass of Promise will resolve to an instantiated Page once the request completes.
*
* It also implements AsyncIterable to allow auto-paginating iteration on an unawaited list call, eg:
*
* for await (const item of client.items.list()) {
* console.log(item)
* }
*/
export declare class PagePromise<

@@ -153,20 +213,11 @@ PageClass extends AbstractPage<Item>,

>
extends Promise<PageClass>
extends APIPromise<PageClass>
implements AsyncIterable<Item>
{
/**
* This subclass of Promise will resolve to an instantiated Page once the request completes.
*/
constructor(
client: APIClient,
requestPromise: Promise<APIResponse<unknown>>,
options: FinalRequestOptions,
request: Promise<APIResponseProps>,
Page: new (...args: ConstructorParameters<typeof AbstractPage>) => PageClass,
);
/**
* Enable subclassing Promise.
* Ref: https://stackoverflow.com/a/60328122
*/
static get [Symbol.species](): PromiseConstructor;
/**
* Allow auto-paginating iteration on an unawaited list call, eg:

@@ -212,6 +263,2 @@ *

};
export type APIResponse<T> = T & {
/** @deprecated - we plan to add a different way to access raw response information shortly. */
responseHeaders: Headers;
};
export declare const safeJSON: (text: string) => any;

@@ -234,2 +281,3 @@ export declare const castToError: (err: any) => Error;

export declare function hasOwn(obj: Object, key: string): boolean;
export declare function debug(action: string, ...args: any[]): void;
export declare const isRunningInBrowser: () => boolean;

@@ -236,0 +284,0 @@ export interface HeadersProtocol {

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

exports.isRunningInBrowser =
exports.debug =
exports.hasOwn =

@@ -54,2 +55,3 @@ exports.isEmptyObj =

exports.APIClient =
exports.APIPromise =
exports.createForm =

@@ -85,2 +87,75 @@ exports.multipartFormRequestOptions =

const MAX_RETRIES = 2;
async function defaultParseResponse(props) {
const { response } = props;
if (props.options.stream) {
// Note: there is an invariant here that isn't represented in the type system
// that if you set `stream: true` the response type must also be `Stream<T>`
return new streaming_1.Stream(response, props.controller);
}
const contentType = response.headers.get('content-type');
if (contentType === null || contentType === void 0 ? void 0 : contentType.includes('application/json')) {
const json = await response.json();
debug('response', response.status, response.url, response.headers, json);
return json;
}
// TODO handle blob, arraybuffer, other content types, etc.
const text = await response.text();
debug('response', response.status, response.url, response.headers, text);
return text;
}
/**
* A subclass of `Promise` providing additional helper methods
* for interacting with the SDK.
*/
class APIPromise extends Promise {
constructor(responsePromise, parseResponse = defaultParseResponse) {
super((resolve) => {
// this is maybe a bit weird but this has to be a no-op to not implicitly
// parse the response body; instead .then, .catch, .finally are overridden
// to parse the response
resolve(null);
});
this.responsePromise = responsePromise;
this.parseResponse = parseResponse;
}
_thenUnwrap(transform) {
return new APIPromise(this.responsePromise, async (props) => transform(await this.parseResponse(props)));
}
/**
* Gets the raw `Response` instance instead of parsing the response
* data.
*
* If you want to parse the response body but still get the `Response`
* instance, you can use {@link withResponse()}.
*/
asResponse() {
return this.responsePromise.then((p) => p.response);
}
/**
* Gets the parsed response data and the raw `Response` instance.
*
* If you just want to get the raw `Response` instance without parsing it,
* you can use {@link asResponse()}.
*/
async withResponse() {
const [data, response] = await Promise.all([this.parse(), this.asResponse()]);
return { data, response };
}
parse() {
if (!this.parsedPromise) {
this.parsedPromise = this.responsePromise.then(this.parseResponse);
}
return this.parsedPromise;
}
then(onfulfilled, onrejected) {
return this.parse().then(onfulfilled, onrejected);
}
catch(onrejected) {
return this.parse().catch(onrejected);
}
finally(onfinally) {
return this.parse().finally(onfinally);
}
}
exports.APIPromise = APIPromise;
class APIClient {

@@ -131,16 +206,19 @@ constructor({

get(path, opts) {
return this.request({ method: 'get', path, ...opts });
return this.methodRequest('get', path, opts);
}
post(path, opts) {
return this.request({ method: 'post', path, ...opts });
return this.methodRequest('post', path, opts);
}
patch(path, opts) {
return this.request({ method: 'patch', path, ...opts });
return this.methodRequest('patch', path, opts);
}
put(path, opts) {
return this.request({ method: 'put', path, ...opts });
return this.methodRequest('put', path, opts);
}
delete(path, opts) {
return this.request({ method: 'delete', path, ...opts });
return this.methodRequest('delete', path, opts);
}
methodRequest(method, path, opts) {
return this.request(Promise.resolve(opts).then((opts) => ({ method, path, ...opts })));
}
getAPIList(path, Page, opts) {

@@ -228,5 +306,9 @@ return this.requestAPIList(Page, { method: 'get', path, ...opts });

}
async request(options, retriesRemaining) {
request(options, remainingRetries = null) {
return new APIPromise(this.makeRequest(options, remainingRetries));
}
async makeRequest(optionsInput, retriesRemaining) {
var _a, _b, _c;
if (retriesRemaining === void 0) {
const options = await optionsInput;
if (retriesRemaining == null) {
retriesRemaining = (_a = options.maxRetries) !== null && _a !== void 0 ? _a : this.maxRetries;

@@ -236,3 +318,3 @@ }

await this.prepareRequest(req, { url });
this.debug('request', url, options, req.headers);
debug('request', url, options, req.headers);
if ((_b = options.signal) === null || _b === void 0 ? void 0 : _b.aborted) {

@@ -263,33 +345,11 @@ throw new error_1.APIUserAbortError();

const errMessage = errJSON ? undefined : errText;
this.debug('response', response.status, url, responseHeaders, errMessage);
debug('response', response.status, url, responseHeaders, errMessage);
const err = this.makeStatusError(response.status, errJSON, errMessage, responseHeaders);
throw err;
}
if (options.stream) {
// Note: there is an invariant here that isn't represented in the type system
// that if you set `stream: true` the response type must also be `Stream<T>`
return new streaming_1.Stream(response, controller);
}
const contentType = response.headers.get('content-type');
if (contentType === null || contentType === void 0 ? void 0 : contentType.includes('application/json')) {
const json = await response.json();
if (typeof json === 'object' && json != null) {
/** @deprecated – we expect to change this interface in the near future. */
Object.defineProperty(json, 'responseHeaders', {
enumerable: false,
writable: false,
value: responseHeaders,
});
}
this.debug('response', response.status, url, responseHeaders, json);
return json;
}
// TODO handle blob, arraybuffer, other content types, etc.
const text = response.text();
this.debug('response', response.status, url, responseHeaders, text);
return text;
return { response, options, controller };
}
requestAPIList(Page, options) {
const requestPromise = this.request(options);
return new PagePromise(this, requestPromise, options, Page);
const request = this.makeRequest(options, null);
return new PagePromise(this, request, Page);
}

@@ -387,7 +447,2 @@ buildURL(path, query) {

}
debug(action, ...args) {
if (typeof process !== 'undefined' && process.env['DEBUG'] === 'true') {
console.log(`${this.constructor.name}:DEBUG:${action}`, ...args);
}
}
}

@@ -408,6 +463,8 @@ exports.APIClient = APIClient;

class AbstractPage {
constructor(client, response, options) {
constructor(client, response, body, options) {
_AbstractPage_client.set(this, void 0);
__classPrivateFieldSet(this, _AbstractPage_client, client, 'f');
this.options = options;
this.response = response;
this.body = body;
}

@@ -460,19 +517,19 @@ hasNextPage() {

exports.AbstractPage = AbstractPage;
class PagePromise extends Promise {
/**
* This subclass of Promise will resolve to an instantiated Page once the request completes.
*/
constructor(client, requestPromise, options, Page) {
super((resolve, reject) =>
requestPromise.then((response) => resolve(new Page(client, response, options))).catch(reject),
/**
* This subclass of Promise will resolve to an instantiated Page once the request completes.
*
* It also implements AsyncIterable to allow auto-paginating iteration on an unawaited list call, eg:
*
* for await (const item of client.items.list()) {
* console.log(item)
* }
*/
class PagePromise extends APIPromise {
constructor(client, request, Page) {
super(
request,
async (props) => new Page(client, props.response, await defaultParseResponse(props), props.options),
);
}
/**
* Enable subclassing Promise.
* Ref: https://stackoverflow.com/a/60328122
*/
static get [Symbol.species]() {
return Promise;
}
/**
* Allow auto-paginating iteration on an unawaited list call, eg:

@@ -754,2 +811,8 @@ *

exports.hasOwn = hasOwn;
function debug(action, ...args) {
if (typeof process !== 'undefined' && process.env['DEBUG'] === 'true') {
console.log(`OpenAI:DEBUG:${action}`, ...args);
}
}
exports.debug = debug;
/**

@@ -756,0 +819,0 @@ * https://stackoverflow.com/a/2117523

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

throw new Error(
"It looks like you're running in a browser-like environment.\n\nThis is disabled by default, as it risks exposing your secret API credentials to attackers. \nIf you understand the risks and have appropriate mitigations in place,\nyou can set the `dangerouslyAllowBrowser` option to `true`, e.g.,\n\nnew OpenAI({ apiKey, dangerouslyAllowBrowser: true });\n\nhttps://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety\n",
"It looks like you're running in a browser-like environment.\n\nThis is disabled by default, as it risks exposing your secret API credentials to attackers.\nIf you understand the risks and have appropriate mitigations in place,\nyou can set the `dangerouslyAllowBrowser` option to `true`, e.g.,\n\nnew OpenAI({ apiKey, dangerouslyAllowBrowser: true });\n\nhttps://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety\n",
);

@@ -91,0 +91,0 @@ }

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

@@ -81,3 +81,4 @@ "author": "OpenAI <support@openai.com>",

"node-fetch": "^2.6.7"
}
},
"bin": "./bin/cli"
}

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

import { AbstractPage, APIResponse, APIClient, FinalRequestOptions } from './core.js';
import { AbstractPage, Response, APIClient, FinalRequestOptions } from './core.js';
export interface PageResponse<Item> {

@@ -12,3 +12,3 @@ data: Array<Item>;

data: Array<Item>;
constructor(client: APIClient, response: APIResponse<PageResponse<Item>>, options: FinalRequestOptions);
constructor(client: APIClient, response: Response, body: PageResponse<Item>, options: FinalRequestOptions);
getPaginatedItems(): Item[];

@@ -15,0 +15,0 @@ /**

@@ -10,6 +10,6 @@ 'use strict';

class Page extends core_1.AbstractPage {
constructor(client, response, options) {
super(client, response, options);
this.object = response.object;
this.data = response.data;
constructor(client, response, body, options) {
super(client, response, body, options);
this.object = body.object;
this.data = body.data;
}

@@ -16,0 +16,0 @@ getPaginatedItems() {

@@ -5,9 +5,6 @@ # OpenAI Node API Library

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.
This library provides convenient access to the OpenAI REST API from TypeScript or JavaScript.
> ⚠️ **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.**
It is generated from our [OpenAPI specification](https://github.com/openai/openai-openapi) with [Stainless](https://stainlessapi.com/).
## 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).

@@ -25,2 +22,5 @@

> [!IMPORTANT]
> Previous versions of this SDK used a `Configuration` class. See the [v3 to v4 migration guide](https://github.com/openai/openai-node/discussions/217).
```js

@@ -71,6 +71,5 @@ import OpenAI from 'openai';

### Usage with TypeScript
### Request & Response types
Importing, instantiating, and interacting with the library are the same as above.
If you like, you may reference our types directly:
This library includes TypeScript definitions for all request params and response fields. You may import and use them like so:

@@ -213,2 +212,26 @@ ```ts

## Advanced Usage
### Accessing raw Response data (e.g., headers)
The "raw" `Response` returned by `fetch()` can be accessed through the `.asResponse()` method on the `APIPromise` type that all methods return.
You can also use the `.withResponse()` method to get the raw `Response` along with the parsed data.
```ts
const openai = new OpenAI();
const response = await openai.chat.completions
.create({ messages: [{ role: 'user', content: 'Say this is a test' }], model: 'gpt-3.5-turbo' })
.asResponse();
console.log(response.headers.get('X-My-Header'));
console.log(response.statusText); // access the underlying Response object
const { data: completions, response: raw } = await openai.chat.completions
.create({ messages: [{ role: 'user', content: 'Say this is a test' }], model: 'gpt-3.5-turbo' })
.withResponse();
console.log(raw.headers.get('X-My-Header'));
console.log(completions.choices);
```
## Configuring an HTTP(S) Agent (e.g., for proxies)

@@ -254,5 +277,7 @@

- Node.js 16 LTS or later ([non-EOL](https://endoflife.date/nodejs)) versions.
- Deno v1.28.0 or higher (experimental).
Use `import OpenAI from "npm:openai"`.
- Deno v1.28.0 or higher, using `import OpenAI from "npm:openai"`.
Deno Deploy is not yet supported.
- Cloudflare Workers.
- Vercel Edge Runtime.
If you are interested in other runtime environments, please open or upvote an issue on GitHub.

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

*/
create(
body: TranscriptionCreateParams,
options?: Core.RequestOptions,
): Promise<Core.APIResponse<Transcription>>;
create(body: TranscriptionCreateParams, options?: Core.RequestOptions): Core.APIPromise<Transcription>;
}

@@ -15,0 +12,0 @@ export interface Transcription {

@@ -11,7 +11,4 @@ 'use strict';

*/
async create(body, options) {
return this.post(
'/audio/transcriptions',
await (0, core_1.multipartFormRequestOptions)({ body, ...options }),
);
create(body, options) {
return this.post('/audio/transcriptions', (0, core_1.multipartFormRequestOptions)({ body, ...options }));
}

@@ -18,0 +15,0 @@ }

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

*/
create(
body: TranslationCreateParams,
options?: Core.RequestOptions,
): Promise<Core.APIResponse<Translation>>;
create(body: TranslationCreateParams, options?: Core.RequestOptions): Core.APIPromise<Translation>;
}

@@ -15,0 +12,0 @@ export interface Translation {

@@ -11,7 +11,4 @@ 'use strict';

*/
async create(body, options) {
return this.post(
'/audio/translations',
await (0, core_1.multipartFormRequestOptions)({ body, ...options }),
);
create(body, options) {
return this.post('/audio/translations', (0, core_1.multipartFormRequestOptions)({ body, ...options }));
}

@@ -18,0 +15,0 @@ }

@@ -11,2 +11,3 @@ import { APIResource } from 'openai/resource';

export import ChatCompletionChunk = API.ChatCompletionChunk;
export import ChatCompletionMessage = API.ChatCompletionMessage;
export import CreateChatCompletionRequestMessage = API.CreateChatCompletionRequestMessage;

@@ -13,0 +14,0 @@ export import CompletionCreateParams = API.CompletionCreateParams;

import * as Core from 'openai/core';
import { APIPromise } from 'openai/core';
import { APIResource } from 'openai/resource';

@@ -9,14 +10,7 @@ import * as API from './index.js';

*/
create(body: CompletionCreateParamsNonStreaming, options?: Core.RequestOptions): APIPromise<ChatCompletion>;
create(
body: CompletionCreateParamsNonStreaming,
options?: Core.RequestOptions,
): Promise<Core.APIResponse<ChatCompletion>>;
create(
body: CompletionCreateParamsStreaming,
options?: Core.RequestOptions,
): Promise<Core.APIResponse<Stream<ChatCompletionChunk>>>;
create(
body: CompletionCreateParams,
options?: Core.RequestOptions,
): Promise<Core.APIResponse<ChatCompletion | Stream<ChatCompletionChunk>>>;
): APIPromise<Stream<ChatCompletionChunk>>;
}

@@ -35,40 +29,4 @@ export interface ChatCompletion {

index: number;
message: Choice.Message;
message: ChatCompletionMessage;
}
namespace Choice {
interface Message {
/**
* The role of the author of this message.
*/
role: 'system' | 'user' | 'assistant' | 'function';
/**
* The contents of the message.
*/
content?: string | null;
/**
* The name and arguments of a function that should be called, as generated by the
* model.
*/
function_call?: Message.FunctionCall;
}
namespace Message {
/**
* The name and arguments of a function that should be called, as generated by the
* model.
*/
interface FunctionCall {
/**
* The arguments to call the function with, as generated by the model in JSON
* format. Note that the model does not always generate valid JSON, and may
* hallucinate parameters not defined by your function schema. Validate the
* arguments in your code before calling your function.
*/
arguments?: string;
/**
* The name of the function to call.
*/
name?: string;
}
}
}
interface Usage {

@@ -130,2 +88,36 @@ completion_tokens: number;

}
export interface ChatCompletionMessage {
/**
* The contents of the message.
*/
content: string | null;
/**
* The role of the author of this message.
*/
role: 'system' | 'user' | 'assistant' | 'function';
/**
* The name and arguments of a function that should be called, as generated by the
* model.
*/
function_call?: ChatCompletionMessage.FunctionCall;
}
export declare namespace ChatCompletionMessage {
/**
* The name and arguments of a function that should be called, as generated by the
* model.
*/
interface FunctionCall {
/**
* The arguments to call the function with, as generated by the model in JSON
* format. Note that the model does not always generate valid JSON, and may
* hallucinate parameters not defined by your function schema. Validate the
* arguments in your code before calling your function.
*/
arguments: string;
/**
* The name of the function to call.
*/
name: string;
}
}
export interface CreateChatCompletionRequestMessage {

@@ -343,2 +335,3 @@ /**

export import ChatCompletionChunk = API.ChatCompletionChunk;
export import ChatCompletionMessage = API.ChatCompletionMessage;
export import CreateChatCompletionRequestMessage = API.CreateChatCompletionRequestMessage;

@@ -345,0 +338,0 @@ export import CompletionCreateParams = API.CompletionCreateParams;

@@ -5,2 +5,3 @@ export { Chat } from './chat.js';

ChatCompletionChunk,
ChatCompletionMessage,
CreateChatCompletionRequestMessage,

@@ -7,0 +8,0 @@ CompletionCreateParams,

import * as Core from 'openai/core';
import { APIPromise } from 'openai/core';
import { APIResource } from 'openai/resource';

@@ -9,14 +10,7 @@ import * as API from './index.js';

*/
create(body: CompletionCreateParamsNonStreaming, options?: Core.RequestOptions): APIPromise<Completion>;
create(
body: CompletionCreateParamsNonStreaming,
options?: Core.RequestOptions,
): Promise<Core.APIResponse<Completion>>;
create(
body: CompletionCreateParamsStreaming,
options?: Core.RequestOptions,
): Promise<Core.APIResponse<Stream<Completion>>>;
create(
body: CompletionCreateParams,
options?: Core.RequestOptions,
): Promise<Core.APIResponse<Completion | Stream<Completion>>>;
): APIPromise<Stream<Completion>>;
}

@@ -23,0 +17,0 @@ export interface Completion {

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

*/
create(body: EditCreateParams, options?: Core.RequestOptions): Promise<Core.APIResponse<Edit>>;
create(body: EditCreateParams, options?: Core.RequestOptions): Core.APIPromise<Edit>;
}

@@ -15,0 +15,0 @@ export interface Edit {

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

*/
create(body: EmbeddingCreateParams, options?: Core.RequestOptions): Promise<Core.APIResponse<Embedding>>;
create(body: EmbeddingCreateParams, options?: Core.RequestOptions): Core.APIPromise<Embedding>;
}

@@ -11,0 +11,0 @@ export interface Embedding {

@@ -13,19 +13,19 @@ import * as Core from 'openai/core';

*/
create(body: FileCreateParams, options?: Core.RequestOptions): Promise<Core.APIResponse<FileObject>>;
create(body: FileCreateParams, options?: Core.RequestOptions): Core.APIPromise<FileObject>;
/**
* Returns information about a specific file.
*/
retrieve(fileId: string, options?: Core.RequestOptions): Promise<Core.APIResponse<FileObject>>;
retrieve(fileId: string, options?: Core.RequestOptions): Core.APIPromise<FileObject>;
/**
* Returns a list of files that belong to the user's organization.
*/
list(options?: Core.RequestOptions): Core.PagePromise<FileObjectsPage>;
list(options?: Core.RequestOptions): Core.PagePromise<FileObjectsPage, FileObject>;
/**
* Delete a file.
*/
del(fileId: string, options?: Core.RequestOptions): Promise<Core.APIResponse<FileDeleted>>;
del(fileId: string, options?: Core.RequestOptions): Core.APIPromise<FileDeleted>;
/**
* Returns the contents of the specified file
*/
retrieveFileContent(fileId: string, options?: Core.RequestOptions): Promise<Core.APIResponse<string>>;
retrieveFileContent(fileId: string, options?: Core.RequestOptions): Core.APIPromise<string>;
}

@@ -32,0 +32,0 @@ /**

@@ -15,4 +15,4 @@ 'use strict';

*/
async create(body, options) {
return this.post('/files', await (0, core_1.multipartFormRequestOptions)({ body, ...options }));
create(body, options) {
return this.post('/files', (0, core_1.multipartFormRequestOptions)({ body, ...options }));
}

@@ -19,0 +19,0 @@ /**

import * as Core from 'openai/core';
import { APIPromise } from 'openai/core';
import { APIResource } from 'openai/resource';

@@ -16,3 +17,3 @@ import * as Files from 'openai/resources/files';

*/
create(body: FineTuneCreateParams, options?: Core.RequestOptions): Promise<Core.APIResponse<FineTune>>;
create(body: FineTuneCreateParams, options?: Core.RequestOptions): Core.APIPromise<FineTune>;
/**

@@ -23,11 +24,11 @@ * Gets info about the fine-tune job.

*/
retrieve(fineTuneId: string, options?: Core.RequestOptions): Promise<Core.APIResponse<FineTune>>;
retrieve(fineTuneId: string, options?: Core.RequestOptions): Core.APIPromise<FineTune>;
/**
* List your organization's fine-tuning jobs
*/
list(options?: Core.RequestOptions): Core.PagePromise<FineTunesPage>;
list(options?: Core.RequestOptions): Core.PagePromise<FineTunesPage, FineTune>;
/**
* Immediately cancel a fine-tune job.
*/
cancel(fineTuneId: string, options?: Core.RequestOptions): Promise<Core.APIResponse<FineTune>>;
cancel(fineTuneId: string, options?: Core.RequestOptions): Core.APIPromise<FineTune>;
/**

@@ -40,3 +41,3 @@ * Get fine-grained status updates for a fine-tune job.

options?: Core.RequestOptions,
): Promise<Core.APIResponse<FineTuneEventsListResponse>>;
): APIPromise<FineTuneEventsListResponse>;
listEvents(

@@ -46,8 +47,3 @@ fineTuneId: string,

options?: Core.RequestOptions,
): Promise<Core.APIResponse<Stream<FineTuneEvent>>>;
listEvents(
fineTuneId: string,
query?: FineTuneListEventsParams,
options?: Core.RequestOptions,
): Promise<Core.APIResponse<FineTuneEventsListResponse | Stream<FineTuneEvent>>>;
): APIPromise<Stream<FineTuneEvent>>;
}

@@ -54,0 +50,0 @@ /**

@@ -12,14 +12,11 @@ import * as Core from 'openai/core';

options?: Core.RequestOptions,
): Promise<Core.APIResponse<ImagesResponse>>;
): Core.APIPromise<ImagesResponse>;
/**
* Creates an edited or extended image given an original image and a prompt.
*/
edit(body: ImageEditParams, options?: Core.RequestOptions): Promise<Core.APIResponse<ImagesResponse>>;
edit(body: ImageEditParams, options?: Core.RequestOptions): Core.APIPromise<ImagesResponse>;
/**
* Creates an image given a prompt.
*/
generate(
body: ImageGenerateParams,
options?: Core.RequestOptions,
): Promise<Core.APIResponse<ImagesResponse>>;
generate(body: ImageGenerateParams, options?: Core.RequestOptions): Core.APIPromise<ImagesResponse>;
}

@@ -26,0 +23,0 @@ export interface Image {

@@ -11,7 +11,4 @@ 'use strict';

*/
async createVariation(body, options) {
return this.post(
'/images/variations',
await (0, core_1.multipartFormRequestOptions)({ body, ...options }),
);
createVariation(body, options) {
return this.post('/images/variations', (0, core_1.multipartFormRequestOptions)({ body, ...options }));
}

@@ -21,4 +18,4 @@ /**

*/
async edit(body, options) {
return this.post('/images/edits', await (0, core_1.multipartFormRequestOptions)({ body, ...options }));
edit(body, options) {
return this.post('/images/edits', (0, core_1.multipartFormRequestOptions)({ body, ...options }));
}

@@ -25,0 +22,0 @@ /**

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

*/
retrieve(model: string, options?: Core.RequestOptions): Promise<Core.APIResponse<Model>>;
retrieve(model: string, options?: Core.RequestOptions): Core.APIPromise<Model>;
/**

@@ -16,7 +16,7 @@ * Lists the currently available models, and provides basic information about each

*/
list(options?: Core.RequestOptions): Core.PagePromise<ModelsPage>;
list(options?: Core.RequestOptions): Core.PagePromise<ModelsPage, Model>;
/**
* Delete a fine-tuned model. You must have the Owner role in your organization.
*/
del(model: string, options?: Core.RequestOptions): Promise<Core.APIResponse<ModelDeleted>>;
del(model: string, options?: Core.RequestOptions): Core.APIPromise<ModelDeleted>;
}

@@ -23,0 +23,0 @@ /**

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

options?: Core.RequestOptions,
): Promise<Core.APIResponse<ModerationCreateResponse>>;
): Core.APIPromise<ModerationCreateResponse>;
}

@@ -14,0 +14,0 @@ export interface Moderation {

@@ -29,2 +29,4 @@ /**

// @ts-ignore
type _ResponseType = unknown extends ResponseType ? never : ResponseType;
// @ts-ignore
type _BodyInit = unknown extends BodyInit ? never : BodyInit;

@@ -53,2 +55,7 @@ // @ts-ignore

export { _fetch as fetch, _Request as Request, _Response as Response, _Headers as Headers };
export type { _RequestInit as RequestInit, _RequestInfo as RequestInfo, _BodyInit as BodyInit };
export type {
_RequestInit as RequestInit,
_RequestInfo as RequestInfo,
_ResponseType as ResponseType,
_BodyInit as BodyInit,
};

@@ -29,2 +29,7 @@ /**

type _ResponseInit = unknown extends ResponseInit ? nf.ResponseInit : ResponseInit;
type _ResponseType =
// @ts-ignore
unknown extends ResponseType ? 'basic' | 'cors' | 'default' | 'error' | 'opaque' | 'opaqueredirect'
: // @ts-ignore
ResponseType;
// @ts-ignore

@@ -54,2 +59,7 @@ type _BodyInit = unknown extends BodyInit ? nf.BodyInit : BodyInit;

export { _fetch as fetch, _Request as Request, _Response as Response, _Headers as Headers };
export type { _RequestInit as RequestInit, _RequestInfo as RequestInfo, _BodyInit as BodyInit };
export type {
_RequestInit as RequestInit,
_RequestInfo as RequestInfo,
_ResponseType as ResponseType,
_BodyInit as BodyInit,
};

@@ -13,2 +13,3 @@ import { VERSION } from './version';

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

@@ -26,2 +27,102 @@ export {

type PromiseOrValue<T> = T | Promise<T>;
type APIResponseProps = {
response: Response;
options: FinalRequestOptions;
controller: AbortController;
};
async function defaultParseResponse<T>(props: APIResponseProps): Promise<T> {
const { response } = props;
if (props.options.stream) {
// Note: there is an invariant here that isn't represented in the type system
// that if you set `stream: true` the response type must also be `Stream<T>`
return new Stream(response, props.controller) as any;
}
const contentType = response.headers.get('content-type');
if (contentType?.includes('application/json')) {
const json = await response.json();
debug('response', response.status, response.url, response.headers, json);
return json as T;
}
// TODO handle blob, arraybuffer, other content types, etc.
const text = await response.text();
debug('response', response.status, response.url, response.headers, text);
return text as T;
}
/**
* A subclass of `Promise` providing additional helper methods
* for interacting with the SDK.
*/
export class APIPromise<T> extends Promise<T> {
private parsedPromise: Promise<T> | undefined;
constructor(
private responsePromise: Promise<APIResponseProps>,
private parseResponse: (props: APIResponseProps) => PromiseOrValue<T> = defaultParseResponse,
) {
super((resolve) => {
// this is maybe a bit weird but this has to be a no-op to not implicitly
// parse the response body; instead .then, .catch, .finally are overridden
// to parse the response
resolve(null as any);
});
}
_thenUnwrap<U>(transform: (data: T) => U): APIPromise<U> {
return new APIPromise(this.responsePromise, async (props) => transform(await this.parseResponse(props)));
}
/**
* Gets the raw `Response` instance instead of parsing the response
* data.
*
* If you want to parse the response body but still get the `Response`
* instance, you can use {@link withResponse()}.
*/
asResponse(): Promise<Response> {
return this.responsePromise.then((p) => p.response);
}
/**
* Gets the parsed response data and the raw `Response` instance.
*
* If you just want to get the raw `Response` instance without parsing it,
* you can use {@link asResponse()}.
*/
async withResponse(): Promise<{ data: T; response: Response }> {
const [data, response] = await Promise.all([this.parse(), this.asResponse()]);
return { data, response };
}
private parse(): Promise<T> {
if (!this.parsedPromise) {
this.parsedPromise = this.responsePromise.then(this.parseResponse);
}
return this.parsedPromise;
}
override then<TResult1 = T, TResult2 = never>(
onfulfilled?: ((value: T) => TResult1 | PromiseLike<TResult1>) | undefined | null,
onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | undefined | null,
): Promise<TResult1 | TResult2> {
return this.parse().then(onfulfilled, onrejected);
}
override catch<TResult = never>(
onrejected?: ((reason: any) => TResult | PromiseLike<TResult>) | undefined | null,
): Promise<T | TResult> {
return this.parse().catch(onrejected);
}
override finally(onfinally?: (() => void) | undefined | null): Promise<T> {
return this.parse().finally(onfinally);
}
}
export abstract class APIClient {

@@ -90,18 +191,30 @@ baseURL: string;

get<Req extends {}, Rsp>(path: string, opts?: RequestOptions<Req>): Promise<Rsp> {
return this.request({ method: 'get', path, ...opts });
get<Req extends {}, Rsp>(path: string, opts?: PromiseOrValue<RequestOptions<Req>>): APIPromise<Rsp> {
return this.methodRequest('get', path, opts);
}
post<Req extends {}, Rsp>(path: string, opts?: RequestOptions<Req>): Promise<Rsp> {
return this.request({ method: 'post', path, ...opts });
post<Req extends {}, Rsp>(path: string, opts?: PromiseOrValue<RequestOptions<Req>>): APIPromise<Rsp> {
return this.methodRequest('post', path, opts);
}
patch<Req extends {}, Rsp>(path: string, opts?: RequestOptions<Req>): Promise<Rsp> {
return this.request({ method: 'patch', path, ...opts });
patch<Req extends {}, Rsp>(path: string, opts?: PromiseOrValue<RequestOptions<Req>>): APIPromise<Rsp> {
return this.methodRequest('patch', path, opts);
}
put<Req extends {}, Rsp>(path: string, opts?: RequestOptions<Req>): Promise<Rsp> {
return this.request({ method: 'put', path, ...opts });
put<Req extends {}, Rsp>(path: string, opts?: PromiseOrValue<RequestOptions<Req>>): APIPromise<Rsp> {
return this.methodRequest('put', path, opts);
}
delete<Req extends {}, Rsp>(path: string, opts?: RequestOptions<Req>): Promise<Rsp> {
return this.request({ method: 'delete', path, ...opts });
delete<Req extends {}, Rsp>(path: string, opts?: PromiseOrValue<RequestOptions<Req>>): APIPromise<Rsp> {
return this.methodRequest('delete', path, opts);
}
private methodRequest<Req extends {}, Rsp>(
method: HTTPMethod,
path: string,
opts?: PromiseOrValue<RequestOptions<Req>>,
): APIPromise<Rsp> {
return this.request(Promise.resolve(opts).then((opts) => ({ method, path, ...opts })));
}
getAPIList<Item, PageClass extends AbstractPage<Item> = AbstractPage<Item>>(

@@ -111,3 +224,3 @@ path: string,

opts?: RequestOptions<any>,
): PagePromise<PageClass> {
): PagePromise<PageClass, Item> {
return this.requestAPIList(Page, { method: 'get', path, ...opts });

@@ -206,10 +319,23 @@ }

async request<Req extends {}, Rsp>(
options: FinalRequestOptions<Req>,
retriesRemaining = options.maxRetries ?? this.maxRetries,
): Promise<APIResponse<Rsp>> {
request<Req extends {}, Rsp>(
options: PromiseOrValue<FinalRequestOptions<Req>>,
remainingRetries: number | null = null,
): APIPromise<Rsp> {
return new APIPromise(this.makeRequest(options, remainingRetries));
}
private async makeRequest<T>(
optionsInput: PromiseOrValue<FinalRequestOptions>,
retriesRemaining: number | null,
): Promise<{ response: Response; options: FinalRequestOptions; controller: AbortController }> {
const options = await optionsInput;
if (retriesRemaining == null) {
retriesRemaining = options.maxRetries ?? this.maxRetries;
}
const { req, url, timeout } = this.buildRequest(options);
await this.prepareRequest(req, { url });
this.debug('request', url, options, req.headers);
debug('request', url, options, req.headers);

@@ -247,3 +373,3 @@ if (options.signal?.aborted) {

this.debug('response', response.status, url, responseHeaders, errMessage);
debug('response', response.status, url, responseHeaders, errMessage);

@@ -254,30 +380,3 @@ const err = this.makeStatusError(response.status, errJSON, errMessage, responseHeaders);

if (options.stream) {
// Note: there is an invariant here that isn't represented in the type system
// that if you set `stream: true` the response type must also be `Stream<T>`
return new Stream(response, controller) as any;
}
const contentType = response.headers.get('content-type');
if (contentType?.includes('application/json')) {
const json = await response.json();
if (typeof json === 'object' && json != null) {
/** @deprecated – we expect to change this interface in the near future. */
Object.defineProperty(json, 'responseHeaders', {
enumerable: false,
writable: false,
value: responseHeaders,
});
}
this.debug('response', response.status, url, responseHeaders, json);
return json as APIResponse<Rsp>;
}
// TODO handle blob, arraybuffer, other content types, etc.
const text = response.text();
this.debug('response', response.status, url, responseHeaders, text);
return text as Promise<any>;
return { response, options, controller };
}

@@ -288,5 +387,5 @@

options: FinalRequestOptions,
): PagePromise<PageClass> {
const requestPromise = this.request(options) as Promise<APIResponse<unknown>>;
return new PagePromise(this, requestPromise, options, Page);
): PagePromise<PageClass, Item> {
const request = this.makeRequest(options, null);
return new PagePromise<PageClass, Item>(this, request, Page);
}

@@ -419,8 +518,2 @@

}
private debug(action: string, ...args: any[]) {
if (typeof process !== 'undefined' && process.env['DEBUG'] === 'true') {
console.log(`${this.constructor.name}:DEBUG:${action}`, ...args);
}
}
}

@@ -455,5 +548,10 @@

constructor(client: APIClient, response: APIResponse<unknown>, options: FinalRequestOptions) {
protected response: Response;
protected body: unknown;
constructor(client: APIClient, response: Response, body: unknown, options: FinalRequestOptions) {
this.#client = client;
this.options = options;
this.response = response;
this.body = body;
}

@@ -515,2 +613,11 @@

/**
* This subclass of Promise will resolve to an instantiated Page once the request completes.
*
* It also implements AsyncIterable to allow auto-paginating iteration on an unawaited list call, eg:
*
* for await (const item of client.items.list()) {
* console.log(item)
* }
*/
export class PagePromise<

@@ -520,16 +627,13 @@ PageClass extends AbstractPage<Item>,

>
extends Promise<PageClass>
extends APIPromise<PageClass>
implements AsyncIterable<Item>
{
/**
* This subclass of Promise will resolve to an instantiated Page once the request completes.
*/
constructor(
client: APIClient,
requestPromise: Promise<APIResponse<unknown>>,
options: FinalRequestOptions,
request: Promise<APIResponseProps>,
Page: new (...args: ConstructorParameters<typeof AbstractPage>) => PageClass,
) {
super((resolve, reject) =>
requestPromise.then((response) => resolve(new Page(client, response, options))).catch(reject),
super(
request,
async (props) => new Page(client, props.response, await defaultParseResponse(props), props.options),
);

@@ -539,10 +643,2 @@ }

/**
* Enable subclassing Promise.
* Ref: https://stackoverflow.com/a/60328122
*/
static get [Symbol.species]() {
return Promise;
}
/**
* Allow auto-paginating iteration on an unawaited list call, eg:

@@ -633,7 +729,2 @@ *

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

@@ -901,2 +992,8 @@ declare const EdgeRuntime: any;

export function debug(action: string, ...args: any[]) {
if (typeof process !== 'undefined' && process.env['DEBUG'] === 'true') {
console.log(`OpenAI:DEBUG:${action}`, ...args);
}
}
/**

@@ -903,0 +1000,0 @@ * https://stackoverflow.com/a/2117523

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

throw new Error(
"It looks like you're running in a browser-like environment.\n\nThis is disabled by default, as it risks exposing your secret API credentials to attackers. \nIf you understand the risks and have appropriate mitigations in place,\nyou can set the `dangerouslyAllowBrowser` option to `true`, e.g.,\n\nnew OpenAI({ apiKey, dangerouslyAllowBrowser: true });\n\nhttps://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety\n",
"It looks like you're running in a browser-like environment.\n\nThis is disabled by default, as it risks exposing your secret API credentials to attackers.\nIf you understand the risks and have appropriate mitigations in place,\nyou can set the `dangerouslyAllowBrowser` option to `true`, e.g.,\n\nnew OpenAI({ apiKey, dangerouslyAllowBrowser: true });\n\nhttps://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety\n",
);

@@ -109,0 +109,0 @@ }

// File generated from our OpenAPI spec by Stainless.
import { AbstractPage, APIResponse, APIClient, FinalRequestOptions } from './core';
import { AbstractPage, Response, APIClient, FinalRequestOptions } from './core';

@@ -19,7 +19,7 @@ export interface PageResponse<Item> {

constructor(client: APIClient, response: APIResponse<PageResponse<Item>>, options: FinalRequestOptions) {
super(client, response, options);
constructor(client: APIClient, response: Response, body: PageResponse<Item>, options: FinalRequestOptions) {
super(client, response, body, options);
this.object = response.object;
this.data = response.data;
this.object = body.object;
this.data = body.data;
}

@@ -26,0 +26,0 @@

@@ -12,7 +12,4 @@ // File generated from our OpenAPI spec by Stainless.

*/
async create(
body: TranscriptionCreateParams,
options?: Core.RequestOptions,
): Promise<Core.APIResponse<Transcription>> {
return this.post('/audio/transcriptions', await multipartFormRequestOptions({ body, ...options }));
create(body: TranscriptionCreateParams, options?: Core.RequestOptions): Core.APIPromise<Transcription> {
return this.post('/audio/transcriptions', multipartFormRequestOptions({ body, ...options }));
}

@@ -19,0 +16,0 @@ }

@@ -12,7 +12,4 @@ // File generated from our OpenAPI spec by Stainless.

*/
async create(
body: TranslationCreateParams,
options?: Core.RequestOptions,
): Promise<Core.APIResponse<Translation>> {
return this.post('/audio/translations', await multipartFormRequestOptions({ body, ...options }));
create(body: TranslationCreateParams, options?: Core.RequestOptions): Core.APIPromise<Translation> {
return this.post('/audio/translations', multipartFormRequestOptions({ body, ...options }));
}

@@ -19,0 +16,0 @@ }

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

export import ChatCompletionChunk = API.ChatCompletionChunk;
export import ChatCompletionMessage = API.ChatCompletionMessage;
export import CreateChatCompletionRequestMessage = API.CreateChatCompletionRequestMessage;

@@ -17,0 +18,0 @@ export import CompletionCreateParams = API.CompletionCreateParams;

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

@@ -12,19 +13,14 @@ import * as API from './index';

*/
create(body: CompletionCreateParamsNonStreaming, options?: Core.RequestOptions): APIPromise<ChatCompletion>;
create(
body: CompletionCreateParamsNonStreaming,
options?: Core.RequestOptions,
): Promise<Core.APIResponse<ChatCompletion>>;
create(
body: CompletionCreateParamsStreaming,
options?: Core.RequestOptions,
): Promise<Core.APIResponse<Stream<ChatCompletionChunk>>>;
): APIPromise<Stream<ChatCompletionChunk>>;
create(
body: CompletionCreateParams,
options?: Core.RequestOptions,
): Promise<Core.APIResponse<ChatCompletion | Stream<ChatCompletionChunk>>>;
create(
body: CompletionCreateParams,
options?: Core.RequestOptions,
): Promise<Core.APIResponse<ChatCompletion | Stream<ChatCompletionChunk>>> {
return this.post('/chat/completions', { body, ...options, stream: body.stream ?? false });
): APIPromise<ChatCompletion> | APIPromise<Stream<ChatCompletionChunk>> {
return this.post('/chat/completions', { body, ...options, stream: body.stream ?? false }) as
| APIPromise<ChatCompletion>
| APIPromise<Stream<ChatCompletionChunk>>;
}

@@ -53,46 +49,5 @@ }

message: Choice.Message;
message: ChatCompletionMessage;
}
export namespace Choice {
export interface Message {
/**
* The role of the author of this message.
*/
role: 'system' | 'user' | 'assistant' | 'function';
/**
* The contents of the message.
*/
content?: string | null;
/**
* The name and arguments of a function that should be called, as generated by the
* model.
*/
function_call?: Message.FunctionCall;
}
export namespace Message {
/**
* The name and arguments of a function that should be called, as generated by the
* model.
*/
export interface FunctionCall {
/**
* The arguments to call the function with, as generated by the model in JSON
* format. Note that the model does not always generate valid JSON, and may
* hallucinate parameters not defined by your function schema. Validate the
* arguments in your code before calling your function.
*/
arguments?: string;
/**
* The name of the function to call.
*/
name?: string;
}
}
}
export interface Usage {

@@ -170,2 +125,41 @@ completion_tokens: number;

export interface ChatCompletionMessage {
/**
* The contents of the message.
*/
content: string | null;
/**
* The role of the author of this message.
*/
role: 'system' | 'user' | 'assistant' | 'function';
/**
* The name and arguments of a function that should be called, as generated by the
* model.
*/
function_call?: ChatCompletionMessage.FunctionCall;
}
export namespace ChatCompletionMessage {
/**
* The name and arguments of a function that should be called, as generated by the
* model.
*/
export interface FunctionCall {
/**
* The arguments to call the function with, as generated by the model in JSON
* format. Note that the model does not always generate valid JSON, and may
* hallucinate parameters not defined by your function schema. Validate the
* arguments in your code before calling your function.
*/
arguments: string;
/**
* The name of the function to call.
*/
name: string;
}
}
export interface CreateChatCompletionRequestMessage {

@@ -410,2 +404,3 @@ /**

export import ChatCompletionChunk = API.ChatCompletionChunk;
export import ChatCompletionMessage = API.ChatCompletionMessage;
export import CreateChatCompletionRequestMessage = API.CreateChatCompletionRequestMessage;

@@ -412,0 +407,0 @@ export import CompletionCreateParams = API.CompletionCreateParams;

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

ChatCompletionChunk,
ChatCompletionMessage,
CreateChatCompletionRequestMessage,

@@ -9,0 +10,0 @@ CompletionCreateParams,

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

@@ -12,19 +13,14 @@ import * as API from './index';

*/
create(body: CompletionCreateParamsNonStreaming, options?: Core.RequestOptions): APIPromise<Completion>;
create(
body: CompletionCreateParamsNonStreaming,
options?: Core.RequestOptions,
): Promise<Core.APIResponse<Completion>>;
create(
body: CompletionCreateParamsStreaming,
options?: Core.RequestOptions,
): Promise<Core.APIResponse<Stream<Completion>>>;
): APIPromise<Stream<Completion>>;
create(
body: CompletionCreateParams,
options?: Core.RequestOptions,
): Promise<Core.APIResponse<Completion | Stream<Completion>>>;
create(
body: CompletionCreateParams,
options?: Core.RequestOptions,
): Promise<Core.APIResponse<Completion | Stream<Completion>>> {
return this.post('/completions', { body, ...options, stream: body.stream ?? false });
): APIPromise<Completion> | APIPromise<Stream<Completion>> {
return this.post('/completions', { body, ...options, stream: body.stream ?? false }) as
| APIPromise<Completion>
| APIPromise<Stream<Completion>>;
}

@@ -31,0 +27,0 @@ }

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

*/
create(body: EditCreateParams, options?: Core.RequestOptions): Promise<Core.APIResponse<Edit>> {
create(body: EditCreateParams, options?: Core.RequestOptions): Core.APIPromise<Edit> {
return this.post('/edits', { body, ...options });

@@ -18,0 +18,0 @@ }

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

*/
create(body: EmbeddingCreateParams, options?: Core.RequestOptions): Promise<Core.APIResponse<Embedding>> {
create(body: EmbeddingCreateParams, options?: Core.RequestOptions): Core.APIPromise<Embedding> {
return this.post('/embeddings', { body, ...options });

@@ -14,0 +14,0 @@ }

@@ -16,4 +16,4 @@ // File generated from our OpenAPI spec by Stainless.

*/
async create(body: FileCreateParams, options?: Core.RequestOptions): Promise<Core.APIResponse<FileObject>> {
return this.post('/files', await multipartFormRequestOptions({ body, ...options }));
create(body: FileCreateParams, options?: Core.RequestOptions): Core.APIPromise<FileObject> {
return this.post('/files', multipartFormRequestOptions({ body, ...options }));
}

@@ -24,3 +24,3 @@

*/
retrieve(fileId: string, options?: Core.RequestOptions): Promise<Core.APIResponse<FileObject>> {
retrieve(fileId: string, options?: Core.RequestOptions): Core.APIPromise<FileObject> {
return this.get(`/files/${fileId}`, options);

@@ -32,3 +32,3 @@ }

*/
list(options?: Core.RequestOptions): Core.PagePromise<FileObjectsPage> {
list(options?: Core.RequestOptions): Core.PagePromise<FileObjectsPage, FileObject> {
return this.getAPIList('/files', FileObjectsPage, options);

@@ -40,3 +40,3 @@ }

*/
del(fileId: string, options?: Core.RequestOptions): Promise<Core.APIResponse<FileDeleted>> {
del(fileId: string, options?: Core.RequestOptions): Core.APIPromise<FileDeleted> {
return this.delete(`/files/${fileId}`, options);

@@ -48,3 +48,3 @@ }

*/
retrieveFileContent(fileId: string, options?: Core.RequestOptions): Promise<Core.APIResponse<string>> {
retrieveFileContent(fileId: string, options?: Core.RequestOptions): Core.APIPromise<string> {
return this.get(`/files/${fileId}/content`, {

@@ -51,0 +51,0 @@ ...options,

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

@@ -19,3 +20,3 @@ import * as Files from './files';

*/
create(body: FineTuneCreateParams, options?: Core.RequestOptions): Promise<Core.APIResponse<FineTune>> {
create(body: FineTuneCreateParams, options?: Core.RequestOptions): Core.APIPromise<FineTune> {
return this.post('/fine-tunes', { body, ...options });

@@ -29,3 +30,3 @@ }

*/
retrieve(fineTuneId: string, options?: Core.RequestOptions): Promise<Core.APIResponse<FineTune>> {
retrieve(fineTuneId: string, options?: Core.RequestOptions): Core.APIPromise<FineTune> {
return this.get(`/fine-tunes/${fineTuneId}`, options);

@@ -37,3 +38,3 @@ }

*/
list(options?: Core.RequestOptions): Core.PagePromise<FineTunesPage> {
list(options?: Core.RequestOptions): Core.PagePromise<FineTunesPage, FineTune> {
return this.getAPIList('/fine-tunes', FineTunesPage, options);

@@ -45,3 +46,3 @@ }

*/
cancel(fineTuneId: string, options?: Core.RequestOptions): Promise<Core.APIResponse<FineTune>> {
cancel(fineTuneId: string, options?: Core.RequestOptions): Core.APIPromise<FineTune> {
return this.post(`/fine-tunes/${fineTuneId}/cancel`, options);

@@ -57,3 +58,3 @@ }

options?: Core.RequestOptions,
): Promise<Core.APIResponse<FineTuneEventsListResponse>>;
): APIPromise<FineTuneEventsListResponse>;
listEvents(

@@ -63,13 +64,8 @@ fineTuneId: string,

options?: Core.RequestOptions,
): Promise<Core.APIResponse<Stream<FineTuneEvent>>>;
): APIPromise<Stream<FineTuneEvent>>;
listEvents(
fineTuneId: string,
query?: FineTuneListEventsParams,
options?: Core.RequestOptions,
): Promise<Core.APIResponse<FineTuneEventsListResponse | Stream<FineTuneEvent>>>;
listEvents(
fineTuneId: string,
query?: FineTuneListEventsParams | undefined,
options?: Core.RequestOptions,
): Promise<Core.APIResponse<FineTuneEventsListResponse | Stream<FineTuneEvent>>> {
): APIPromise<FineTuneEventsListResponse> | APIPromise<Stream<FineTuneEvent>> {
return this.get(`/fine-tunes/${fineTuneId}/events`, {

@@ -80,3 +76,3 @@ query,

stream: query?.stream ?? false,
});
}) as APIPromise<FineTuneEventsListResponse> | APIPromise<Stream<FineTuneEvent>>;
}

@@ -83,0 +79,0 @@ }

@@ -12,7 +12,7 @@ // File generated from our OpenAPI spec by Stainless.

*/
async createVariation(
createVariation(
body: ImageCreateVariationParams,
options?: Core.RequestOptions,
): Promise<Core.APIResponse<ImagesResponse>> {
return this.post('/images/variations', await multipartFormRequestOptions({ body, ...options }));
): Core.APIPromise<ImagesResponse> {
return this.post('/images/variations', multipartFormRequestOptions({ body, ...options }));
}

@@ -23,7 +23,4 @@

*/
async edit(
body: ImageEditParams,
options?: Core.RequestOptions,
): Promise<Core.APIResponse<ImagesResponse>> {
return this.post('/images/edits', await multipartFormRequestOptions({ body, ...options }));
edit(body: ImageEditParams, options?: Core.RequestOptions): Core.APIPromise<ImagesResponse> {
return this.post('/images/edits', multipartFormRequestOptions({ body, ...options }));
}

@@ -34,6 +31,3 @@

*/
generate(
body: ImageGenerateParams,
options?: Core.RequestOptions,
): Promise<Core.APIResponse<ImagesResponse>> {
generate(body: ImageGenerateParams, options?: Core.RequestOptions): Core.APIPromise<ImagesResponse> {
return this.post('/images/generations', { body, ...options });

@@ -40,0 +34,0 @@ }

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

*/
retrieve(model: string, options?: Core.RequestOptions): Promise<Core.APIResponse<Model>> {
retrieve(model: string, options?: Core.RequestOptions): Core.APIPromise<Model> {
return this.get(`/models/${model}`, options);

@@ -22,3 +22,3 @@ }

*/
list(options?: Core.RequestOptions): Core.PagePromise<ModelsPage> {
list(options?: Core.RequestOptions): Core.PagePromise<ModelsPage, Model> {
return this.getAPIList('/models', ModelsPage, options);

@@ -30,3 +30,3 @@ }

*/
del(model: string, options?: Core.RequestOptions): Promise<Core.APIResponse<ModelDeleted>> {
del(model: string, options?: Core.RequestOptions): Core.APIPromise<ModelDeleted> {
return this.delete(`/models/${model}`, options);

@@ -33,0 +33,0 @@ }

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

options?: Core.RequestOptions,
): Promise<Core.APIResponse<ModerationCreateResponse>> {
): Core.APIPromise<ModerationCreateResponse> {
return this.post('/moderations', { body, ...options });

@@ -17,0 +17,0 @@ }

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

@@ -14,16 +12,7 @@

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;
controller: AbortController;
export class Stream<Item> implements AsyncIterable<Item> {
private decoder: SSEDecoder;
constructor(response: Response, controller: AbortController) {
this.response = response;
this.controller = controller;
constructor(private response: Response, private controller: AbortController) {
this.decoder = new SSEDecoder();
this.responseHeaders = createResponseHeaders(response.headers);
}

@@ -30,0 +19,0 @@

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

export const VERSION = '4.0.0-beta.8';
export const VERSION = '4.0.0-beta.9';
import type { Response } from 'openai/_shims/fetch';
import { ReadableStream } from 'openai/_shims/ReadableStream';
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;
controller: AbortController;
export declare class Stream<Item> implements AsyncIterable<Item> {
private response;
private controller;
private decoder;

@@ -11,0 +7,0 @@ constructor(response: Response, controller: AbortController);

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

const ReadableStream_1 = require('openai/_shims/ReadableStream');
const core_1 = require('./core.js');
class Stream {

@@ -12,3 +11,2 @@ constructor(response, controller) {

this.decoder = new SSEDecoder();
this.responseHeaders = (0, core_1.createResponseHeaders)(response.headers);
}

@@ -15,0 +13,0 @@ async *iterMessages() {

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

export declare const VERSION = '4.0.0-beta.8';
export declare const VERSION = '4.0.0-beta.9';
//# sourceMappingURL=version.d.ts.map
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
exports.VERSION = void 0;
exports.VERSION = '4.0.0-beta.8';
exports.VERSION = '4.0.0-beta.9';
//# 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

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