client.mjs 5.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. import { buildHeaders } from "./internal/headers.mjs";
  2. import * as Errors from "./core/error.mjs";
  3. import { readEnv } from "./internal/utils.mjs";
  4. import { Anthropic } from '@anthropic-ai/sdk/client';
  5. export { BaseAnthropic } from '@anthropic-ai/sdk/client';
  6. import * as Resources from '@anthropic-ai/sdk/resources/index';
  7. /** API Client for interfacing with the Anthropic Foundry API. */
  8. export class AnthropicFoundry extends Anthropic {
  9. /**
  10. * API Client for interfacing with the Anthropic Foundry API.
  11. *
  12. * @param {string | undefined} [opts.resource=process.env['ANTHROPIC_FOUNDRY_RESOURCE'] ?? undefined] - Your Foundry resource name
  13. * @param {string | undefined} [opts.apiKey=process.env['ANTHROPIC_FOUNDRY_API_KEY'] ?? undefined]
  14. * @param {string | null | undefined} [opts.organization=process.env['ANTHROPIC_ORG_ID'] ?? null]
  15. * @param {string} [opts.baseURL=process.env['ANTHROPIC_FOUNDRY_BASE_URL']] - Sets the base URL for the API, e.g. `https://example-resource.azure.anthropic.com/anthropic/`.
  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('ANTHROPIC_FOUNDRY_BASE_URL'), apiKey = readEnv('ANTHROPIC_FOUNDRY_API_KEY'), resource = readEnv('ANTHROPIC_FOUNDRY_RESOURCE'), azureADTokenProvider, dangerouslyAllowBrowser, ...opts } = {}) {
  25. if (typeof azureADTokenProvider === 'function') {
  26. dangerouslyAllowBrowser = true;
  27. }
  28. if (!azureADTokenProvider && !apiKey) {
  29. throw new Errors.AnthropicError('Missing credentials. Please pass one of `apiKey` and `azureTokenProvider`, or set the `ANTHROPIC_FOUNDRY_API_KEY` environment variable.');
  30. }
  31. if (azureADTokenProvider && apiKey) {
  32. throw new Errors.AnthropicError('The `apiKey` and `azureADTokenProvider` arguments are mutually exclusive; only one can be passed at a time.');
  33. }
  34. if (!baseURL) {
  35. if (!resource) {
  36. throw new Errors.AnthropicError('Must provide one of the `baseURL` or `resource` arguments, or the `ANTHROPIC_FOUNDRY_RESOURCE` environment variable');
  37. }
  38. baseURL = `https://${resource}.services.ai.azure.com/anthropic/`;
  39. }
  40. else {
  41. if (resource) {
  42. throw new Errors.AnthropicError('baseURL and resource are mutually exclusive');
  43. }
  44. }
  45. super({
  46. apiKey: azureADTokenProvider ?? apiKey,
  47. baseURL,
  48. ...opts,
  49. ...(dangerouslyAllowBrowser !== undefined ? { dangerouslyAllowBrowser } : {}),
  50. });
  51. this.resource = null;
  52. // @ts-expect-error are using a different Messages type that omits batches
  53. this.messages = makeMessagesResource(this);
  54. // @ts-expect-error are using a different Beta type that omits batches
  55. this.beta = makeBetaResource(this);
  56. // @ts-expect-error Anthropic Foundry does not support models endpoint
  57. this.models = undefined;
  58. }
  59. async authHeaders() {
  60. if (typeof this._options.apiKey === 'function') {
  61. let token;
  62. try {
  63. token = await this._options.apiKey();
  64. }
  65. catch (err) {
  66. if (err instanceof Errors.AnthropicError)
  67. throw err;
  68. throw new Errors.AnthropicError(`Failed to get token from azureADTokenProvider: ${err.message}`,
  69. // @ts-ignore
  70. { cause: err });
  71. }
  72. if (typeof token !== 'string' || !token) {
  73. throw new Errors.AnthropicError(`Expected azureADTokenProvider function argument to return a string but it returned ${token}`);
  74. }
  75. return buildHeaders([{ Authorization: `Bearer ${token}` }]);
  76. }
  77. if (typeof this._options.apiKey === 'string') {
  78. return buildHeaders([{ 'x-api-key': this.apiKey }]);
  79. }
  80. return undefined;
  81. }
  82. validateHeaders() {
  83. return;
  84. }
  85. }
  86. function makeMessagesResource(client) {
  87. const resource = new Resources.Messages(client);
  88. // @ts-expect-error we're deleting non-optional properties
  89. delete resource.batches;
  90. return resource;
  91. }
  92. function makeBetaResource(client) {
  93. const resource = new Resources.Beta(client);
  94. // @ts-expect-error we're deleting non-optional properties
  95. delete resource.messages.batches;
  96. return resource;
  97. }
  98. //# sourceMappingURL=client.mjs.map