index.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  1. "use strict";
  2. // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
  3. var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
  4. if (k2 === undefined) k2 = k;
  5. var desc = Object.getOwnPropertyDescriptor(m, k);
  6. if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
  7. desc = { enumerable: true, get: function() { return m[k]; } };
  8. }
  9. Object.defineProperty(o, k2, desc);
  10. }) : (function(o, m, k, k2) {
  11. if (k2 === undefined) k2 = k;
  12. o[k2] = m[k];
  13. }));
  14. var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
  15. Object.defineProperty(o, "default", { enumerable: true, value: v });
  16. }) : function(o, v) {
  17. o["default"] = v;
  18. });
  19. var __importStar = (this && this.__importStar) || function (mod) {
  20. if (mod && mod.__esModule) return mod;
  21. var result = {};
  22. if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
  23. __setModuleDefault(result, mod);
  24. return result;
  25. };
  26. var _a;
  27. Object.defineProperty(exports, "__esModule", { value: true });
  28. 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.fileFromPath = exports.toFile = exports.AzureOpenAI = exports.OpenAI = void 0;
  29. const qs = __importStar(require("./internal/qs/index.js"));
  30. const Core = __importStar(require("./core.js"));
  31. const Errors = __importStar(require("./error.js"));
  32. const Pagination = __importStar(require("./pagination.js"));
  33. const Uploads = __importStar(require("./uploads.js"));
  34. const API = __importStar(require("./resources/index.js"));
  35. const batches_1 = require("./resources/batches.js");
  36. const completions_1 = require("./resources/completions.js");
  37. const embeddings_1 = require("./resources/embeddings.js");
  38. const files_1 = require("./resources/files.js");
  39. const images_1 = require("./resources/images.js");
  40. const models_1 = require("./resources/models.js");
  41. const moderations_1 = require("./resources/moderations.js");
  42. const audio_1 = require("./resources/audio/audio.js");
  43. const beta_1 = require("./resources/beta/beta.js");
  44. const chat_1 = require("./resources/chat/chat.js");
  45. const containers_1 = require("./resources/containers/containers.js");
  46. const evals_1 = require("./resources/evals/evals.js");
  47. const fine_tuning_1 = require("./resources/fine-tuning/fine-tuning.js");
  48. const graders_1 = require("./resources/graders/graders.js");
  49. const responses_1 = require("./resources/responses/responses.js");
  50. const uploads_1 = require("./resources/uploads/uploads.js");
  51. const vector_stores_1 = require("./resources/vector-stores/vector-stores.js");
  52. const completions_2 = require("./resources/chat/completions/completions.js");
  53. /**
  54. * API Client for interfacing with the OpenAI API.
  55. */
  56. class OpenAI extends Core.APIClient {
  57. /**
  58. * API Client for interfacing with the OpenAI API.
  59. *
  60. * @param {string | undefined} [opts.apiKey=process.env['OPENAI_API_KEY'] ?? undefined]
  61. * @param {string | null | undefined} [opts.organization=process.env['OPENAI_ORG_ID'] ?? null]
  62. * @param {string | null | undefined} [opts.project=process.env['OPENAI_PROJECT_ID'] ?? null]
  63. * @param {string} [opts.baseURL=process.env['OPENAI_BASE_URL'] ?? https://api.openai.com/v1] - Override the default base URL for the API.
  64. * @param {number} [opts.timeout=10 minutes] - The maximum amount of time (in milliseconds) the client will wait for a response before timing out.
  65. * @param {number} [opts.httpAgent] - An HTTP agent used to manage HTTP(s) connections.
  66. * @param {Core.Fetch} [opts.fetch] - Specify a custom `fetch` function implementation.
  67. * @param {number} [opts.maxRetries=2] - The maximum number of times the client will retry a request.
  68. * @param {Core.Headers} opts.defaultHeaders - Default headers to include with every request to the API.
  69. * @param {Core.DefaultQuery} opts.defaultQuery - Default query parameters to include with every request to the API.
  70. * @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.
  71. */
  72. constructor({ baseURL = Core.readEnv('OPENAI_BASE_URL'), apiKey = Core.readEnv('OPENAI_API_KEY'), organization = Core.readEnv('OPENAI_ORG_ID') ?? null, project = Core.readEnv('OPENAI_PROJECT_ID') ?? null, ...opts } = {}) {
  73. if (apiKey === undefined) {
  74. throw new Errors.OpenAIError("The OPENAI_API_KEY environment variable is missing or empty; either provide it, or instantiate the OpenAI client with an apiKey option, like new OpenAI({ apiKey: 'My API Key' }).");
  75. }
  76. const options = {
  77. apiKey,
  78. organization,
  79. project,
  80. ...opts,
  81. baseURL: baseURL || `https://api.openai.com/v1`,
  82. };
  83. if (!options.dangerouslyAllowBrowser && Core.isRunningInBrowser()) {
  84. throw new Errors.OpenAIError("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");
  85. }
  86. super({
  87. baseURL: options.baseURL,
  88. timeout: options.timeout ?? 600000 /* 10 minutes */,
  89. httpAgent: options.httpAgent,
  90. maxRetries: options.maxRetries,
  91. fetch: options.fetch,
  92. });
  93. this.completions = new API.Completions(this);
  94. this.chat = new API.Chat(this);
  95. this.embeddings = new API.Embeddings(this);
  96. this.files = new API.Files(this);
  97. this.images = new API.Images(this);
  98. this.audio = new API.Audio(this);
  99. this.moderations = new API.Moderations(this);
  100. this.models = new API.Models(this);
  101. this.fineTuning = new API.FineTuning(this);
  102. this.graders = new API.Graders(this);
  103. this.vectorStores = new API.VectorStores(this);
  104. this.beta = new API.Beta(this);
  105. this.batches = new API.Batches(this);
  106. this.uploads = new API.Uploads(this);
  107. this.responses = new API.Responses(this);
  108. this.evals = new API.Evals(this);
  109. this.containers = new API.Containers(this);
  110. this._options = options;
  111. this.apiKey = apiKey;
  112. this.organization = organization;
  113. this.project = project;
  114. }
  115. defaultQuery() {
  116. return this._options.defaultQuery;
  117. }
  118. defaultHeaders(opts) {
  119. return {
  120. ...super.defaultHeaders(opts),
  121. 'OpenAI-Organization': this.organization,
  122. 'OpenAI-Project': this.project,
  123. ...this._options.defaultHeaders,
  124. };
  125. }
  126. authHeaders(opts) {
  127. return { Authorization: `Bearer ${this.apiKey}` };
  128. }
  129. stringifyQuery(query) {
  130. return qs.stringify(query, { arrayFormat: 'brackets' });
  131. }
  132. }
  133. exports.OpenAI = OpenAI;
  134. _a = OpenAI;
  135. OpenAI.OpenAI = _a;
  136. OpenAI.DEFAULT_TIMEOUT = 600000; // 10 minutes
  137. OpenAI.OpenAIError = Errors.OpenAIError;
  138. OpenAI.APIError = Errors.APIError;
  139. OpenAI.APIConnectionError = Errors.APIConnectionError;
  140. OpenAI.APIConnectionTimeoutError = Errors.APIConnectionTimeoutError;
  141. OpenAI.APIUserAbortError = Errors.APIUserAbortError;
  142. OpenAI.NotFoundError = Errors.NotFoundError;
  143. OpenAI.ConflictError = Errors.ConflictError;
  144. OpenAI.RateLimitError = Errors.RateLimitError;
  145. OpenAI.BadRequestError = Errors.BadRequestError;
  146. OpenAI.AuthenticationError = Errors.AuthenticationError;
  147. OpenAI.InternalServerError = Errors.InternalServerError;
  148. OpenAI.PermissionDeniedError = Errors.PermissionDeniedError;
  149. OpenAI.UnprocessableEntityError = Errors.UnprocessableEntityError;
  150. OpenAI.toFile = Uploads.toFile;
  151. OpenAI.fileFromPath = Uploads.fileFromPath;
  152. OpenAI.Completions = completions_1.Completions;
  153. OpenAI.Chat = chat_1.Chat;
  154. OpenAI.ChatCompletionsPage = completions_2.ChatCompletionsPage;
  155. OpenAI.Embeddings = embeddings_1.Embeddings;
  156. OpenAI.Files = files_1.Files;
  157. OpenAI.FileObjectsPage = files_1.FileObjectsPage;
  158. OpenAI.Images = images_1.Images;
  159. OpenAI.Audio = audio_1.Audio;
  160. OpenAI.Moderations = moderations_1.Moderations;
  161. OpenAI.Models = models_1.Models;
  162. OpenAI.ModelsPage = models_1.ModelsPage;
  163. OpenAI.FineTuning = fine_tuning_1.FineTuning;
  164. OpenAI.Graders = graders_1.Graders;
  165. OpenAI.VectorStores = vector_stores_1.VectorStores;
  166. OpenAI.VectorStoresPage = vector_stores_1.VectorStoresPage;
  167. OpenAI.VectorStoreSearchResponsesPage = vector_stores_1.VectorStoreSearchResponsesPage;
  168. OpenAI.Beta = beta_1.Beta;
  169. OpenAI.Batches = batches_1.Batches;
  170. OpenAI.BatchesPage = batches_1.BatchesPage;
  171. OpenAI.Uploads = uploads_1.Uploads;
  172. OpenAI.Responses = responses_1.Responses;
  173. OpenAI.Evals = evals_1.Evals;
  174. OpenAI.EvalListResponsesPage = evals_1.EvalListResponsesPage;
  175. OpenAI.Containers = containers_1.Containers;
  176. OpenAI.ContainerListResponsesPage = containers_1.ContainerListResponsesPage;
  177. /** API Client for interfacing with the Azure OpenAI API. */
  178. class AzureOpenAI extends OpenAI {
  179. /**
  180. * API Client for interfacing with the Azure OpenAI API.
  181. *
  182. * @param {string | undefined} [opts.apiVersion=process.env['OPENAI_API_VERSION'] ?? undefined]
  183. * @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/`
  184. * @param {string | undefined} [opts.apiKey=process.env['AZURE_OPENAI_API_KEY'] ?? undefined]
  185. * @param {string | undefined} opts.deployment - A model deployment, if given, sets the base client URL to include `/deployments/{deployment}`.
  186. * @param {string | null | undefined} [opts.organization=process.env['OPENAI_ORG_ID'] ?? null]
  187. * @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/`.
  188. * @param {number} [opts.timeout=10 minutes] - The maximum amount of time (in milliseconds) the client will wait for a response before timing out.
  189. * @param {number} [opts.httpAgent] - An HTTP agent used to manage HTTP(s) connections.
  190. * @param {Core.Fetch} [opts.fetch] - Specify a custom `fetch` function implementation.
  191. * @param {number} [opts.maxRetries=2] - The maximum number of times the client will retry a request.
  192. * @param {Core.Headers} opts.defaultHeaders - Default headers to include with every request to the API.
  193. * @param {Core.DefaultQuery} opts.defaultQuery - Default query parameters to include with every request to the API.
  194. * @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.
  195. */
  196. 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 } = {}) {
  197. if (!apiVersion) {
  198. 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' }).");
  199. }
  200. if (typeof azureADTokenProvider === 'function') {
  201. dangerouslyAllowBrowser = true;
  202. }
  203. if (!azureADTokenProvider && !apiKey) {
  204. throw new Errors.OpenAIError('Missing credentials. Please pass one of `apiKey` and `azureADTokenProvider`, or set the `AZURE_OPENAI_API_KEY` environment variable.');
  205. }
  206. if (azureADTokenProvider && apiKey) {
  207. throw new Errors.OpenAIError('The `apiKey` and `azureADTokenProvider` arguments are mutually exclusive; only one can be passed at a time.');
  208. }
  209. // define a sentinel value to avoid any typing issues
  210. apiKey ?? (apiKey = API_KEY_SENTINEL);
  211. opts.defaultQuery = { ...opts.defaultQuery, 'api-version': apiVersion };
  212. if (!baseURL) {
  213. if (!endpoint) {
  214. endpoint = process.env['AZURE_OPENAI_ENDPOINT'];
  215. }
  216. if (!endpoint) {
  217. throw new Errors.OpenAIError('Must provide one of the `baseURL` or `endpoint` arguments, or the `AZURE_OPENAI_ENDPOINT` environment variable');
  218. }
  219. baseURL = `${endpoint}/openai`;
  220. }
  221. else {
  222. if (endpoint) {
  223. throw new Errors.OpenAIError('baseURL and endpoint are mutually exclusive');
  224. }
  225. }
  226. super({
  227. apiKey,
  228. baseURL,
  229. ...opts,
  230. ...(dangerouslyAllowBrowser !== undefined ? { dangerouslyAllowBrowser } : {}),
  231. });
  232. this.apiVersion = '';
  233. this._azureADTokenProvider = azureADTokenProvider;
  234. this.apiVersion = apiVersion;
  235. this.deploymentName = deployment;
  236. }
  237. buildRequest(options, props = {}) {
  238. if (_deployments_endpoints.has(options.path) && options.method === 'post' && options.body !== undefined) {
  239. if (!Core.isObj(options.body)) {
  240. throw new Error('Expected request body to be an object');
  241. }
  242. const model = this.deploymentName || options.body['model'] || options.__metadata?.['model'];
  243. if (model !== undefined && !this.baseURL.includes('/deployments')) {
  244. options.path = `/deployments/${model}${options.path}`;
  245. }
  246. }
  247. return super.buildRequest(options, props);
  248. }
  249. async _getAzureADToken() {
  250. if (typeof this._azureADTokenProvider === 'function') {
  251. const token = await this._azureADTokenProvider();
  252. if (!token || typeof token !== 'string') {
  253. throw new Errors.OpenAIError(`Expected 'azureADTokenProvider' argument to return a string but it returned ${token}`);
  254. }
  255. return token;
  256. }
  257. return undefined;
  258. }
  259. authHeaders(opts) {
  260. return {};
  261. }
  262. async prepareOptions(opts) {
  263. /**
  264. * The user should provide a bearer token provider if they want
  265. * to use Azure AD authentication. The user shouldn't set the
  266. * Authorization header manually because the header is overwritten
  267. * with the Azure AD token if a bearer token provider is provided.
  268. */
  269. if (opts.headers?.['api-key']) {
  270. return super.prepareOptions(opts);
  271. }
  272. const token = await this._getAzureADToken();
  273. opts.headers ?? (opts.headers = {});
  274. if (token) {
  275. opts.headers['Authorization'] = `Bearer ${token}`;
  276. }
  277. else if (this.apiKey !== API_KEY_SENTINEL) {
  278. opts.headers['api-key'] = this.apiKey;
  279. }
  280. else {
  281. throw new Errors.OpenAIError('Unable to handle auth');
  282. }
  283. return super.prepareOptions(opts);
  284. }
  285. }
  286. exports.AzureOpenAI = AzureOpenAI;
  287. const _deployments_endpoints = new Set([
  288. '/completions',
  289. '/chat/completions',
  290. '/embeddings',
  291. '/audio/transcriptions',
  292. '/audio/translations',
  293. '/audio/speech',
  294. '/images/generations',
  295. '/images/edits',
  296. ]);
  297. const API_KEY_SENTINEL = '<Missing Key>';
  298. // ---------------------- End Azure ----------------------
  299. var uploads_2 = require("./uploads.js");
  300. Object.defineProperty(exports, "toFile", { enumerable: true, get: function () { return uploads_2.toFile; } });
  301. Object.defineProperty(exports, "fileFromPath", { enumerable: true, get: function () { return uploads_2.fileFromPath; } });
  302. var error_1 = require("./error.js");
  303. Object.defineProperty(exports, "OpenAIError", { enumerable: true, get: function () { return error_1.OpenAIError; } });
  304. Object.defineProperty(exports, "APIError", { enumerable: true, get: function () { return error_1.APIError; } });
  305. Object.defineProperty(exports, "APIConnectionError", { enumerable: true, get: function () { return error_1.APIConnectionError; } });
  306. Object.defineProperty(exports, "APIConnectionTimeoutError", { enumerable: true, get: function () { return error_1.APIConnectionTimeoutError; } });
  307. Object.defineProperty(exports, "APIUserAbortError", { enumerable: true, get: function () { return error_1.APIUserAbortError; } });
  308. Object.defineProperty(exports, "NotFoundError", { enumerable: true, get: function () { return error_1.NotFoundError; } });
  309. Object.defineProperty(exports, "ConflictError", { enumerable: true, get: function () { return error_1.ConflictError; } });
  310. Object.defineProperty(exports, "RateLimitError", { enumerable: true, get: function () { return error_1.RateLimitError; } });
  311. Object.defineProperty(exports, "BadRequestError", { enumerable: true, get: function () { return error_1.BadRequestError; } });
  312. Object.defineProperty(exports, "AuthenticationError", { enumerable: true, get: function () { return error_1.AuthenticationError; } });
  313. Object.defineProperty(exports, "InternalServerError", { enumerable: true, get: function () { return error_1.InternalServerError; } });
  314. Object.defineProperty(exports, "PermissionDeniedError", { enumerable: true, get: function () { return error_1.PermissionDeniedError; } });
  315. Object.defineProperty(exports, "UnprocessableEntityError", { enumerable: true, get: function () { return error_1.UnprocessableEntityError; } });
  316. exports = module.exports = OpenAI;
  317. module.exports.AzureOpenAI = AzureOpenAI;
  318. exports.default = OpenAI;
  319. //# sourceMappingURL=index.js.map