index.mjs 14 KB

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