CoolFace
Datasetpublic

basant307/AI_Governance_Project

sourceHugging Faceapache-2.0updated 2mo agoView on Hugging Face
0likes48downloads
azure.js131 linesDownload Raw Back to openai
1"use strict";2Object.defineProperty(exports, "__esModule", { value: true });3exports.AzureOpenAI = void 0;4const tslib_1 = require("./internal/tslib.js");5const Errors = tslib_1.__importStar(require("./error.js"));6const utils_1 = require("./internal/utils.js");7const client_1 = require("./client.js");8const headers_1 = require("./internal/headers.js");9/** API Client for interfacing with the Azure OpenAI API. */10class AzureOpenAI extends client_1.OpenAI {11    /**12     * API Client for interfacing with the Azure OpenAI API.13     *14     * @param {string | undefined} [opts.apiVersion=process.env['OPENAI_API_VERSION'] ?? undefined]15     * @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/`16     * @param {string | undefined} [opts.apiKey=process.env['AZURE_OPENAI_API_KEY'] ?? undefined]17     * @param {string | undefined} opts.deployment - A model deployment, if given, sets the base client URL to include `/deployments/{deployment}`.18     * @param {string | null | undefined} [opts.organization=process.env['OPENAI_ORG_ID'] ?? null]19     * @param {string} [opts.baseURL=process.env['OPENAI_BASE_URL']] - Sets the base URL for the API, e.g. `https://example-resource.azure.openai.com/openai/`.20     * @param {number} [opts.timeout=10 minutes] - The maximum amount of time (in milliseconds) the client will wait for a response before timing out.21     * @param {number} [opts.httpAgent] - An HTTP agent used to manage HTTP(s) connections.22     * @param {Fetch} [opts.fetch] - Specify a custom `fetch` function implementation.23     * @param {number} [opts.maxRetries=2] - The maximum number of times the client will retry a request.24     * @param {Headers} opts.defaultHeaders - Default headers to include with every request to the API.25     * @param {DefaultQuery} opts.defaultQuery - Default query parameters to include with every request to the API.26     * @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.27     */28    constructor({ baseURL = (0, utils_1.readEnv)('OPENAI_BASE_URL'), apiKey = (0, utils_1.readEnv)('AZURE_OPENAI_API_KEY'), apiVersion = (0, utils_1.readEnv)('OPENAI_API_VERSION'), endpoint, deployment, azureADTokenProvider, dangerouslyAllowBrowser, ...opts } = {}) {29        if (!apiVersion) {30            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' }).");31        }32        if (typeof azureADTokenProvider === 'function') {33            dangerouslyAllowBrowser = true;34        }35        if (!azureADTokenProvider && !apiKey) {36            throw new Errors.OpenAIError('Missing credentials. Please pass one of `apiKey` and `azureADTokenProvider`, or set the `AZURE_OPENAI_API_KEY` environment variable.');37        }38        if (azureADTokenProvider && apiKey) {39            throw new Errors.OpenAIError('The `apiKey` and `azureADTokenProvider` arguments are mutually exclusive; only one can be passed at a time.');40        }41        // define a sentinel value to avoid any typing issues42        apiKey ?? (apiKey = API_KEY_SENTINEL);43        opts.defaultQuery = { ...opts.defaultQuery, 'api-version': apiVersion };44        if (!baseURL) {45            if (!endpoint) {46                endpoint = process.env['AZURE_OPENAI_ENDPOINT'];47            }48            if (!endpoint) {49                throw new Errors.OpenAIError('Must provide one of the `baseURL` or `endpoint` arguments, or the `AZURE_OPENAI_ENDPOINT` environment variable');50            }51            baseURL = `${endpoint}/openai`;52        }53        else {54            if (endpoint) {55                throw new Errors.OpenAIError('baseURL and endpoint are mutually exclusive');56            }57        }58        super({59            apiKey,60            baseURL,61            ...opts,62            ...(dangerouslyAllowBrowser !== undefined ? { dangerouslyAllowBrowser } : {}),63        });64        this.apiVersion = '';65        this._azureADTokenProvider = azureADTokenProvider;66        this.apiVersion = apiVersion;67        this.deploymentName = deployment;68    }69    async buildRequest(options, props = {}) {70        if (_deployments_endpoints.has(options.path) && options.method === 'post' && options.body !== undefined) {71            if (!(0, utils_1.isObj)(options.body)) {72                throw new Error('Expected request body to be an object');73            }74            const model = this.deploymentName || options.body['model'] || options.__metadata?.['model'];75            if (model !== undefined && !this.baseURL.includes('/deployments')) {76                options.path = `/deployments/${model}${options.path}`;77            }78        }79        return super.buildRequest(options, props);80    }81    async _getAzureADToken() {82        if (typeof this._azureADTokenProvider === 'function') {83            const token = await this._azureADTokenProvider();84            if (!token || typeof token !== 'string') {85                throw new Errors.OpenAIError(`Expected 'azureADTokenProvider' argument to return a string but it returned ${token}`);86            }87            return token;88        }89        return undefined;90    }91    async authHeaders(opts) {92        return;93    }94    async prepareOptions(opts) {95        opts.headers = (0, headers_1.buildHeaders)([opts.headers]);96        /**97         * The user should provide a bearer token provider if they want98         * to use Azure AD authentication. The user shouldn't set the99         * Authorization header manually because the header is overwritten100         * with the Azure AD token if a bearer token provider is provided.101         */102        if (opts.headers.values.get('Authorization') || opts.headers.values.get('api-key')) {103            return super.prepareOptions(opts);104        }105        const token = await this._getAzureADToken();106        if (token) {107            opts.headers.values.set('Authorization', `Bearer ${token}`);108        }109        else if (this.apiKey !== API_KEY_SENTINEL) {110            opts.headers.values.set('api-key', this.apiKey);111        }112        else {113            throw new Errors.OpenAIError('Unable to handle auth');114        }115        return super.prepareOptions(opts);116    }117}118exports.AzureOpenAI = AzureOpenAI;119const _deployments_endpoints = new Set([120    '/completions',121    '/chat/completions',122    '/embeddings',123    '/audio/transcriptions',124    '/audio/translations',125    '/audio/speech',126    '/images/generations',127    '/batches',128    '/images/edits',129]);130const API_KEY_SENTINEL = '<Missing Key>';131//# sourceMappingURL=azure.js.map
basant307/AI_Governance_Project · CoolFace