azure.mjs 5.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. import { buildHeaders } from "./internal/headers.mjs";
  2. import * as Errors from "./error.mjs";
  3. import { isObj, readEnv } from "./internal/utils.mjs";
  4. import { OpenAI } from "./client.mjs";
  5. /** API Client for interfacing with the Azure OpenAI API. */
  6. export class AzureOpenAI extends OpenAI {
  7. /**
  8. * API Client for interfacing with the Azure OpenAI API.
  9. *
  10. * @param {string | undefined} [opts.apiVersion=process.env['OPENAI_API_VERSION'] ?? undefined]
  11. * @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/`
  12. * @param {string | undefined} [opts.apiKey=process.env['AZURE_OPENAI_API_KEY'] ?? undefined]
  13. * @param {string | undefined} opts.deployment - A model deployment, if given, sets the base client URL to include `/deployments/{deployment}`.
  14. * @param {string | null | undefined} [opts.organization=process.env['OPENAI_ORG_ID'] ?? null]
  15. * @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/`.
  16. * @param {number} [opts.timeout=10 minutes] - The maximum amount of time (in milliseconds) the client will wait for a response before timing out.
  17. * @param {number} [opts.httpAgent] - An HTTP agent used to manage HTTP(s) connections.
  18. * @param {Fetch} [opts.fetch] - Specify a custom `fetch` function implementation.
  19. * @param {number} [opts.maxRetries=2] - The maximum number of times the client will retry a request.
  20. * @param {Headers} opts.defaultHeaders - Default headers to include with every request to the API.
  21. * @param {DefaultQuery} opts.defaultQuery - Default query parameters to include with every request to the API.
  22. * @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.
  23. */
  24. constructor({ baseURL = readEnv('OPENAI_BASE_URL'), apiKey = readEnv('AZURE_OPENAI_API_KEY'), apiVersion = readEnv('OPENAI_API_VERSION'), endpoint, deployment, azureADTokenProvider, dangerouslyAllowBrowser, ...opts } = {}) {
  25. if (!apiVersion) {
  26. 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' }).");
  27. }
  28. if (typeof azureADTokenProvider === 'function') {
  29. dangerouslyAllowBrowser = true;
  30. }
  31. if (!azureADTokenProvider && !apiKey) {
  32. throw new Errors.OpenAIError('Missing credentials. Please pass one of `apiKey` and `azureADTokenProvider`, or set the `AZURE_OPENAI_API_KEY` environment variable.');
  33. }
  34. if (azureADTokenProvider && apiKey) {
  35. throw new Errors.OpenAIError('The `apiKey` and `azureADTokenProvider` arguments are mutually exclusive; only one can be passed at a time.');
  36. }
  37. opts.defaultQuery = { ...opts.defaultQuery, 'api-version': apiVersion };
  38. if (!baseURL) {
  39. if (!endpoint) {
  40. endpoint = process.env['AZURE_OPENAI_ENDPOINT'];
  41. }
  42. if (!endpoint) {
  43. throw new Errors.OpenAIError('Must provide one of the `baseURL` or `endpoint` arguments, or the `AZURE_OPENAI_ENDPOINT` environment variable');
  44. }
  45. baseURL = `${endpoint}/openai`;
  46. }
  47. else {
  48. if (endpoint) {
  49. throw new Errors.OpenAIError('baseURL and endpoint are mutually exclusive');
  50. }
  51. }
  52. super({
  53. apiKey: azureADTokenProvider ?? apiKey,
  54. baseURL,
  55. ...opts,
  56. ...(dangerouslyAllowBrowser !== undefined ? { dangerouslyAllowBrowser } : {}),
  57. });
  58. this.apiVersion = '';
  59. this.apiVersion = apiVersion;
  60. this.deploymentName = deployment;
  61. }
  62. async buildRequest(options, props = {}) {
  63. if (_deployments_endpoints.has(options.path) && options.method === 'post' && options.body !== undefined) {
  64. if (!isObj(options.body)) {
  65. throw new Error('Expected request body to be an object');
  66. }
  67. const model = this.deploymentName || options.body['model'] || options.__metadata?.['model'];
  68. if (model !== undefined && !this.baseURL.includes('/deployments')) {
  69. options.path = `/deployments/${model}${options.path}`;
  70. }
  71. }
  72. return super.buildRequest(options, props);
  73. }
  74. async authHeaders(opts) {
  75. if (typeof this._options.apiKey === 'string') {
  76. return buildHeaders([{ 'api-key': this.apiKey }]);
  77. }
  78. return super.authHeaders(opts);
  79. }
  80. }
  81. const _deployments_endpoints = new Set([
  82. '/completions',
  83. '/chat/completions',
  84. '/embeddings',
  85. '/audio/transcriptions',
  86. '/audio/translations',
  87. '/audio/speech',
  88. '/images/generations',
  89. '/batches',
  90. '/images/edits',
  91. ]);
  92. //# sourceMappingURL=azure.mjs.map