Comparing version 4.40.2 to 4.41.0
# Changelog | ||
## 4.41.0 (2024-05-05) | ||
Full Changelog: [v4.40.2...v4.41.0](https://github.com/openai/openai-node/compare/v4.40.2...v4.41.0) | ||
### Features | ||
* **client:** add Azure client ([#822](https://github.com/openai/openai-node/issues/822)) ([92f9049](https://github.com/openai/openai-node/commit/92f90499f0bbee79ba9c8342c8d58dbcaf88bdd1)) | ||
## 4.40.2 (2024-05-03) | ||
@@ -4,0 +12,0 @@ |
import * as Core from "./core.js"; | ||
import * as Errors from "./error.js"; | ||
import { type Agent } from "./_shims/index.js"; | ||
import { type Agent, type RequestInit } from "./_shims/index.js"; | ||
import * as Uploads from "./uploads.js"; | ||
@@ -208,3 +208,58 @@ import * as Pagination from 'openai/pagination'; | ||
} | ||
/** API Client for interfacing with the Azure OpenAI API. */ | ||
export interface AzureClientOptions extends ClientOptions { | ||
/** | ||
* Defaults to process.env['OPENAI_API_VERSION']. | ||
*/ | ||
apiVersion?: string | undefined; | ||
/** | ||
* Your Azure endpoint, including the resource, e.g. `https://example-resource.azure.openai.com/` | ||
*/ | ||
endpoint?: string | undefined; | ||
/** | ||
* A model deployment, if given, sets the base client URL to include `/deployments/{deployment}`. | ||
* Note: this means you won't be able to use non-deployment endpoints. Not supported with Assistants APIs. | ||
*/ | ||
deployment?: string | undefined; | ||
/** | ||
* Defaults to process.env['AZURE_OPENAI_API_KEY']. | ||
*/ | ||
apiKey?: string | undefined; | ||
/** | ||
* A function that returns an access token for Microsoft Entra (formerly known as Azure Active Directory), | ||
* which will be invoked on every request. | ||
*/ | ||
azureADTokenProvider?: (() => string) | undefined; | ||
} | ||
/** API Client for interfacing with the Azure OpenAI API. */ | ||
export declare class AzureOpenAI extends OpenAI { | ||
private _azureADTokenProvider; | ||
apiVersion: string; | ||
/** | ||
* API Client for interfacing with the Azure OpenAI API. | ||
* | ||
* @param {string | undefined} [opts.apiVersion=process.env['OPENAI_API_VERSION'] ?? undefined] | ||
* @param {string | undefined} [opts.endpoint=process.env['AZURE_OPENAI_ENDPOINT'] ?? undefined] - Your Azure endpoint, including the resource, e.g. `https://example-resource.azure.openai.com/` | ||
* @param {string | undefined} [opts.apiKey=process.env['AZURE_OPENAI_API_KEY'] ?? undefined] | ||
* @param {string | undefined} opts.deployment - A model deployment, if given, sets the base client URL to include `/deployments/{deployment}`. | ||
* @param {string | null | undefined} [opts.organization=process.env['OPENAI_ORG_ID'] ?? null] | ||
* @param {string} [opts.baseURL=process.env['OPENAI_BASE_URL']] - Sets the base URL for the API. | ||
* @param {number} [opts.timeout=10 minutes] - The maximum amount of time (in milliseconds) the client will wait for a response before timing out. | ||
* @param {number} [opts.httpAgent] - An HTTP agent used to manage HTTP(s) connections. | ||
* @param {Core.Fetch} [opts.fetch] - Specify a custom `fetch` function implementation. | ||
* @param {number} [opts.maxRetries=2] - The maximum number of times the client will retry a request. | ||
* @param {Core.Headers} opts.defaultHeaders - Default headers to include with every request to the API. | ||
* @param {Core.DefaultQuery} opts.defaultQuery - Default query parameters to include with every request to the API. | ||
* @param {boolean} [opts.dangerouslyAllowBrowser=false] - By default, client-side use of this library is not allowed, as it risks exposing your secret API credentials to attackers. | ||
*/ | ||
constructor({ baseURL, apiKey, apiVersion, endpoint, deployment, azureADTokenProvider, dangerouslyAllowBrowser, ...opts }?: AzureClientOptions); | ||
buildRequest(options: Core.FinalRequestOptions<unknown>): { | ||
req: RequestInit; | ||
url: string; | ||
timeout: number; | ||
}; | ||
private _getAzureADToken; | ||
protected authHeaders(opts: Core.FinalRequestOptions): Core.Headers; | ||
} | ||
export default OpenAI; | ||
//# sourceMappingURL=index.d.ts.map |
115
index.js
@@ -28,3 +28,3 @@ "use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.fileFromPath = exports.toFile = exports.UnprocessableEntityError = exports.PermissionDeniedError = exports.InternalServerError = exports.AuthenticationError = exports.BadRequestError = exports.RateLimitError = exports.ConflictError = exports.NotFoundError = exports.APIUserAbortError = exports.APIConnectionTimeoutError = exports.APIConnectionError = exports.APIError = exports.OpenAIError = exports.OpenAI = void 0; | ||
exports.AzureOpenAI = exports.fileFromPath = exports.toFile = exports.UnprocessableEntityError = exports.PermissionDeniedError = exports.InternalServerError = exports.AuthenticationError = exports.BadRequestError = exports.RateLimitError = exports.ConflictError = exports.NotFoundError = exports.APIUserAbortError = exports.APIConnectionTimeoutError = exports.APIConnectionError = exports.APIError = exports.OpenAIError = exports.OpenAI = void 0; | ||
const Core = __importStar(require("./core.js")); | ||
@@ -143,4 +143,117 @@ const Errors = __importStar(require("./error.js")); | ||
})(OpenAI = exports.OpenAI || (exports.OpenAI = {})); | ||
/** API Client for interfacing with the Azure OpenAI API. */ | ||
class AzureOpenAI extends OpenAI { | ||
/** | ||
* API Client for interfacing with the Azure OpenAI API. | ||
* | ||
* @param {string | undefined} [opts.apiVersion=process.env['OPENAI_API_VERSION'] ?? undefined] | ||
* @param {string | undefined} [opts.endpoint=process.env['AZURE_OPENAI_ENDPOINT'] ?? undefined] - Your Azure endpoint, including the resource, e.g. `https://example-resource.azure.openai.com/` | ||
* @param {string | undefined} [opts.apiKey=process.env['AZURE_OPENAI_API_KEY'] ?? undefined] | ||
* @param {string | undefined} opts.deployment - A model deployment, if given, sets the base client URL to include `/deployments/{deployment}`. | ||
* @param {string | null | undefined} [opts.organization=process.env['OPENAI_ORG_ID'] ?? null] | ||
* @param {string} [opts.baseURL=process.env['OPENAI_BASE_URL']] - Sets the base URL for the API. | ||
* @param {number} [opts.timeout=10 minutes] - The maximum amount of time (in milliseconds) the client will wait for a response before timing out. | ||
* @param {number} [opts.httpAgent] - An HTTP agent used to manage HTTP(s) connections. | ||
* @param {Core.Fetch} [opts.fetch] - Specify a custom `fetch` function implementation. | ||
* @param {number} [opts.maxRetries=2] - The maximum number of times the client will retry a request. | ||
* @param {Core.Headers} opts.defaultHeaders - Default headers to include with every request to the API. | ||
* @param {Core.DefaultQuery} opts.defaultQuery - Default query parameters to include with every request to the API. | ||
* @param {boolean} [opts.dangerouslyAllowBrowser=false] - By default, client-side use of this library is not allowed, as it risks exposing your secret API credentials to attackers. | ||
*/ | ||
constructor({ baseURL = Core.readEnv('OPENAI_BASE_URL'), apiKey = Core.readEnv('AZURE_OPENAI_API_KEY'), apiVersion = Core.readEnv('OPENAI_API_VERSION'), endpoint, deployment, azureADTokenProvider, dangerouslyAllowBrowser, ...opts } = {}) { | ||
if (!apiVersion) { | ||
throw new Errors.OpenAIError("The OPENAI_API_VERSION environment variable is missing or empty; either provide it, or instantiate the AzureOpenAI client with an apiVersion option, like new AzureOpenAI({ apiVersion: 'My API Version' })."); | ||
} | ||
if (typeof azureADTokenProvider === 'function') { | ||
dangerouslyAllowBrowser = true; | ||
} | ||
if (!azureADTokenProvider && !apiKey) { | ||
throw new Errors.OpenAIError('Missing credentials. Please pass one of `apiKey` and `azureADTokenProvider`, or set the `AZURE_OPENAI_API_KEY` environment variable.'); | ||
} | ||
if (azureADTokenProvider && apiKey) { | ||
throw new Errors.OpenAIError('The `apiKey` and `azureADTokenProvider` arguments are mutually exclusive; only one can be passed at a time.'); | ||
} | ||
// define a sentinel value to avoid any typing issues | ||
apiKey ?? (apiKey = API_KEY_SENTINEL); | ||
opts.defaultQuery = { ...opts.defaultQuery, 'api-version': apiVersion }; | ||
if (!baseURL) { | ||
if (!endpoint) { | ||
endpoint = process.env['AZURE_OPENAI_ENDPOINT']; | ||
} | ||
if (!endpoint) { | ||
throw new Errors.OpenAIError('Must provide one of the `baseURL` or `endpoint` arguments, or the `AZURE_OPENAI_ENDPOINT` environment variable'); | ||
} | ||
if (deployment) { | ||
baseURL = `${endpoint}/openai/deployments/${deployment}`; | ||
} | ||
else { | ||
baseURL = `${endpoint}/openai`; | ||
} | ||
} | ||
else { | ||
if (endpoint) { | ||
throw new Errors.OpenAIError('baseURL and endpoint are mutually exclusive'); | ||
} | ||
} | ||
super({ | ||
apiKey, | ||
baseURL, | ||
...opts, | ||
...(dangerouslyAllowBrowser !== undefined ? { dangerouslyAllowBrowser } : {}), | ||
}); | ||
this.apiVersion = ''; | ||
this._azureADTokenProvider = azureADTokenProvider; | ||
this.apiVersion = apiVersion; | ||
} | ||
buildRequest(options) { | ||
if (_deployments_endpoints.has(options.path) && options.method === 'post' && options.body !== undefined) { | ||
if (!Core.isObj(options.body)) { | ||
throw new Error('Expected request body to be an object'); | ||
} | ||
const model = options.body['model']; | ||
delete options.body['model']; | ||
if (model !== undefined && !this.baseURL.includes('/deployments')) { | ||
options.path = `/deployments/${model}${options.path}`; | ||
} | ||
} | ||
return super.buildRequest(options); | ||
} | ||
_getAzureADToken() { | ||
if (typeof this._azureADTokenProvider === 'function') { | ||
const token = this._azureADTokenProvider(); | ||
if (!token || typeof token !== 'string') { | ||
throw new Errors.OpenAIError(`Expected 'azureADTokenProvider' argument to return a string but it returned ${token}`); | ||
} | ||
return token; | ||
} | ||
return undefined; | ||
} | ||
authHeaders(opts) { | ||
if (opts.headers?.['Authorization'] || opts.headers?.['api-key']) { | ||
return {}; | ||
} | ||
const token = this._getAzureADToken(); | ||
if (token) { | ||
return { Authorization: `Bearer ${token}` }; | ||
} | ||
if (this.apiKey !== API_KEY_SENTINEL) { | ||
return { 'api-key': this.apiKey }; | ||
} | ||
throw new Errors.OpenAIError('Unable to handle auth'); | ||
} | ||
} | ||
exports.AzureOpenAI = AzureOpenAI; | ||
const _deployments_endpoints = new Set([ | ||
'/completions', | ||
'/chat/completions', | ||
'/embeddings', | ||
'/audio/transcriptions', | ||
'/audio/translations', | ||
'/audio/speech', | ||
'/images/generations', | ||
]); | ||
const API_KEY_SENTINEL = '<Missing Key>'; | ||
// ---------------------- End Azure ---------------------- | ||
exports = module.exports = OpenAI; | ||
exports.default = OpenAI; | ||
//# sourceMappingURL=index.js.map |
{ | ||
"name": "openai", | ||
"version": "4.40.2", | ||
"version": "4.41.0", | ||
"description": "The official TypeScript library for the OpenAI API", | ||
@@ -5,0 +5,0 @@ "author": "OpenAI <support@openai.com>", |
@@ -22,3 +22,3 @@ # OpenAI Node API Library | ||
```ts | ||
import OpenAI from 'https://deno.land/x/openai@v4.40.2/mod.ts'; | ||
import OpenAI from 'https://deno.land/x/openai@v4.41.0/mod.ts'; | ||
``` | ||
@@ -365,11 +365,22 @@ | ||
### Azure OpenAI | ||
## Microsoft Azure OpenAI | ||
An example of using this library with Azure OpenAI can be found [here](https://github.com/openai/openai-node/blob/master/examples/azure.ts). | ||
To use this library with [Azure OpenAI](https://learn.microsoft.com/en-us/azure/ai-services/openai/overview), use the `AzureOpenAI` | ||
class instead of the `OpenAI` class. | ||
Please note there are subtle differences in API shape & behavior between the Azure OpenAI API and the OpenAI API, | ||
so using this library with Azure OpenAI may result in incorrect types, which can lead to bugs. | ||
> [!IMPORTANT] | ||
> The Azure API shape differs from the core API shape which means that the static types for responses / params | ||
> won't always be correct. | ||
See [`@azure/openai`](https://www.npmjs.com/package/@azure/openai) for an Azure-specific SDK provided by Microsoft. | ||
```ts | ||
const openai = new AzureOpenAI(); | ||
const result = await openai.chat.completions.create({ | ||
model: 'gpt-4-1106-preview', | ||
messages: [{ role: 'user', content: 'Say hello!' }], | ||
}); | ||
console.log(result.choices[0]!.message?.content); | ||
``` | ||
### Retries | ||
@@ -376,0 +387,0 @@ |
@@ -46,2 +46,3 @@ import * as Core from 'openai/core'; | ||
* Upload a file to the `files` API and then attach it to the given vector store. | ||
* | ||
* Note the file will be asynchronously processed (you can use the alternative | ||
@@ -48,0 +49,0 @@ * polling helper method to wait for processing to complete). |
@@ -126,2 +126,3 @@ "use strict"; | ||
* Upload a file to the `files` API and then attach it to the given vector store. | ||
* | ||
* Note the file will be asynchronously processed (you can use the alternative | ||
@@ -128,0 +129,0 @@ * polling helper method to wait for processing to complete). |
185
src/index.ts
@@ -5,3 +5,3 @@ // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. | ||
import * as Errors from './error'; | ||
import { type Agent } from './_shims/index'; | ||
import { type Agent, type RequestInit } from './_shims/index'; | ||
import * as Uploads from './uploads'; | ||
@@ -314,2 +314,185 @@ import * as Pagination from "./pagination"; | ||
// ---------------------- Azure ---------------------- | ||
/** API Client for interfacing with the Azure OpenAI API. */ | ||
export interface AzureClientOptions extends ClientOptions { | ||
/** | ||
* Defaults to process.env['OPENAI_API_VERSION']. | ||
*/ | ||
apiVersion?: string | undefined; | ||
/** | ||
* Your Azure endpoint, including the resource, e.g. `https://example-resource.azure.openai.com/` | ||
*/ | ||
endpoint?: string | undefined; | ||
/** | ||
* A model deployment, if given, sets the base client URL to include `/deployments/{deployment}`. | ||
* Note: this means you won't be able to use non-deployment endpoints. Not supported with Assistants APIs. | ||
*/ | ||
deployment?: string | undefined; | ||
/** | ||
* Defaults to process.env['AZURE_OPENAI_API_KEY']. | ||
*/ | ||
apiKey?: string | undefined; | ||
/** | ||
* A function that returns an access token for Microsoft Entra (formerly known as Azure Active Directory), | ||
* which will be invoked on every request. | ||
*/ | ||
azureADTokenProvider?: (() => string) | undefined; | ||
} | ||
/** API Client for interfacing with the Azure OpenAI API. */ | ||
export class AzureOpenAI extends OpenAI { | ||
private _azureADTokenProvider: (() => string) | undefined; | ||
apiVersion: string = ''; | ||
/** | ||
* API Client for interfacing with the Azure OpenAI API. | ||
* | ||
* @param {string | undefined} [opts.apiVersion=process.env['OPENAI_API_VERSION'] ?? undefined] | ||
* @param {string | undefined} [opts.endpoint=process.env['AZURE_OPENAI_ENDPOINT'] ?? undefined] - Your Azure endpoint, including the resource, e.g. `https://example-resource.azure.openai.com/` | ||
* @param {string | undefined} [opts.apiKey=process.env['AZURE_OPENAI_API_KEY'] ?? undefined] | ||
* @param {string | undefined} opts.deployment - A model deployment, if given, sets the base client URL to include `/deployments/{deployment}`. | ||
* @param {string | null | undefined} [opts.organization=process.env['OPENAI_ORG_ID'] ?? null] | ||
* @param {string} [opts.baseURL=process.env['OPENAI_BASE_URL']] - Sets the base URL for the API. | ||
* @param {number} [opts.timeout=10 minutes] - The maximum amount of time (in milliseconds) the client will wait for a response before timing out. | ||
* @param {number} [opts.httpAgent] - An HTTP agent used to manage HTTP(s) connections. | ||
* @param {Core.Fetch} [opts.fetch] - Specify a custom `fetch` function implementation. | ||
* @param {number} [opts.maxRetries=2] - The maximum number of times the client will retry a request. | ||
* @param {Core.Headers} opts.defaultHeaders - Default headers to include with every request to the API. | ||
* @param {Core.DefaultQuery} opts.defaultQuery - Default query parameters to include with every request to the API. | ||
* @param {boolean} [opts.dangerouslyAllowBrowser=false] - By default, client-side use of this library is not allowed, as it risks exposing your secret API credentials to attackers. | ||
*/ | ||
constructor({ | ||
baseURL = Core.readEnv('OPENAI_BASE_URL'), | ||
apiKey = Core.readEnv('AZURE_OPENAI_API_KEY'), | ||
apiVersion = Core.readEnv('OPENAI_API_VERSION'), | ||
endpoint, | ||
deployment, | ||
azureADTokenProvider, | ||
dangerouslyAllowBrowser, | ||
...opts | ||
}: AzureClientOptions = {}) { | ||
if (!apiVersion) { | ||
throw new Errors.OpenAIError( | ||
"The OPENAI_API_VERSION environment variable is missing or empty; either provide it, or instantiate the AzureOpenAI client with an apiVersion option, like new AzureOpenAI({ apiVersion: 'My API Version' }).", | ||
); | ||
} | ||
if (typeof azureADTokenProvider === 'function') { | ||
dangerouslyAllowBrowser = true; | ||
} | ||
if (!azureADTokenProvider && !apiKey) { | ||
throw new Errors.OpenAIError( | ||
'Missing credentials. Please pass one of `apiKey` and `azureADTokenProvider`, or set the `AZURE_OPENAI_API_KEY` environment variable.', | ||
); | ||
} | ||
if (azureADTokenProvider && apiKey) { | ||
throw new Errors.OpenAIError( | ||
'The `apiKey` and `azureADTokenProvider` arguments are mutually exclusive; only one can be passed at a time.', | ||
); | ||
} | ||
// define a sentinel value to avoid any typing issues | ||
apiKey ??= API_KEY_SENTINEL; | ||
opts.defaultQuery = { ...opts.defaultQuery, 'api-version': apiVersion }; | ||
if (!baseURL) { | ||
if (!endpoint) { | ||
endpoint = process.env['AZURE_OPENAI_ENDPOINT']; | ||
} | ||
if (!endpoint) { | ||
throw new Errors.OpenAIError( | ||
'Must provide one of the `baseURL` or `endpoint` arguments, or the `AZURE_OPENAI_ENDPOINT` environment variable', | ||
); | ||
} | ||
if (deployment) { | ||
baseURL = `${endpoint}/openai/deployments/${deployment}`; | ||
} else { | ||
baseURL = `${endpoint}/openai`; | ||
} | ||
} else { | ||
if (endpoint) { | ||
throw new Errors.OpenAIError('baseURL and endpoint are mutually exclusive'); | ||
} | ||
} | ||
super({ | ||
apiKey, | ||
baseURL, | ||
...opts, | ||
...(dangerouslyAllowBrowser !== undefined ? { dangerouslyAllowBrowser } : {}), | ||
}); | ||
this._azureADTokenProvider = azureADTokenProvider; | ||
this.apiVersion = apiVersion; | ||
} | ||
override buildRequest(options: Core.FinalRequestOptions<unknown>): { | ||
req: RequestInit; | ||
url: string; | ||
timeout: number; | ||
} { | ||
if (_deployments_endpoints.has(options.path) && options.method === 'post' && options.body !== undefined) { | ||
if (!Core.isObj(options.body)) { | ||
throw new Error('Expected request body to be an object'); | ||
} | ||
const model = options.body['model']; | ||
delete options.body['model']; | ||
if (model !== undefined && !this.baseURL.includes('/deployments')) { | ||
options.path = `/deployments/${model}${options.path}`; | ||
} | ||
} | ||
return super.buildRequest(options); | ||
} | ||
private _getAzureADToken(): string | undefined { | ||
if (typeof this._azureADTokenProvider === 'function') { | ||
const token = this._azureADTokenProvider(); | ||
if (!token || typeof token !== 'string') { | ||
throw new Errors.OpenAIError( | ||
`Expected 'azureADTokenProvider' argument to return a string but it returned ${token}`, | ||
); | ||
} | ||
return token; | ||
} | ||
return undefined; | ||
} | ||
protected override authHeaders(opts: Core.FinalRequestOptions): Core.Headers { | ||
if (opts.headers?.['Authorization'] || opts.headers?.['api-key']) { | ||
return {}; | ||
} | ||
const token = this._getAzureADToken(); | ||
if (token) { | ||
return { Authorization: `Bearer ${token}` }; | ||
} | ||
if (this.apiKey !== API_KEY_SENTINEL) { | ||
return { 'api-key': this.apiKey }; | ||
} | ||
throw new Errors.OpenAIError('Unable to handle auth'); | ||
} | ||
} | ||
const _deployments_endpoints = new Set([ | ||
'/completions', | ||
'/chat/completions', | ||
'/embeddings', | ||
'/audio/transcriptions', | ||
'/audio/translations', | ||
'/audio/speech', | ||
'/images/generations', | ||
]); | ||
const API_KEY_SENTINEL = '<Missing Key>'; | ||
// ---------------------- End Azure ---------------------- | ||
export default OpenAI; |
@@ -147,2 +147,3 @@ // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. | ||
* Upload a file to the `files` API and then attach it to the given vector store. | ||
* | ||
* Note the file will be asynchronously processed (you can use the alternative | ||
@@ -149,0 +150,0 @@ * polling helper method to wait for processing to complete). |
@@ -1,1 +0,1 @@ | ||
export const VERSION = '4.40.2'; // x-release-please-version | ||
export const VERSION = '4.41.0'; // x-release-please-version |
@@ -1,2 +0,2 @@ | ||
export declare const VERSION = "4.40.2"; | ||
export declare const VERSION = "4.41.0"; | ||
//# sourceMappingURL=version.d.ts.map |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.VERSION = void 0; | ||
exports.VERSION = '4.40.2'; // x-release-please-version | ||
exports.VERSION = '4.41.0'; // x-release-please-version | ||
//# 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
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
Environment variable access
Supply chain riskPackage accesses environment variables, which may be a sign of credential stuffing or data theft.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
2417283
41445
617
7