client.mjs 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  1. import { BaseAnthropic } from '@anthropic-ai/sdk/client';
  2. import * as Resources from '@anthropic-ai/sdk/resources/index';
  3. import { GoogleAuth } from 'google-auth-library';
  4. import { readEnv } from "./internal/utils/env.mjs";
  5. import { isObj } from "./internal/utils/values.mjs";
  6. import { buildHeaders } from "./internal/headers.mjs";
  7. export { BaseAnthropic } from '@anthropic-ai/sdk/client';
  8. const DEFAULT_VERSION = 'vertex-2023-10-16';
  9. const MODEL_ENDPOINTS = new Set(['/v1/messages', '/v1/messages?beta=true']);
  10. export class AnthropicVertex extends BaseAnthropic {
  11. /**
  12. * API Client for interfacing with the Anthropic Vertex API.
  13. *
  14. * @param {string | null} opts.accessToken
  15. * @param {string | null} opts.projectId
  16. * @param {GoogleAuth} opts.googleAuth - Override the default google auth config
  17. * @param {AuthClient} opts.authClient - Provide a pre-configured AuthClient instance (alternative to googleAuth)
  18. * @param {string | null} [opts.region=process.env['CLOUD_ML_REGION']] - The region to use for the API. Use 'global' for global endpoint. [More details here](https://cloud.google.com/vertex-ai/generative-ai/docs/learn/locations).
  19. * @param {string} [opts.baseURL=process.env['ANTHROPIC_VERTEX__BASE_URL'] ?? https://${region}-aiplatform.googleapis.com/v1] - Override the default base URL for the API.
  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 {MergedRequestInit} [opts.fetchOptions] - Additional `RequestInit` options to be passed to `fetch` calls.
  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 {HeadersLike} opts.defaultHeaders - Default headers to include with every request to the API.
  25. * @param {Record<string, string | undefined>} 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 = readEnv('ANTHROPIC_VERTEX_BASE_URL'), region = readEnv('CLOUD_ML_REGION') ?? null, projectId = readEnv('ANTHROPIC_VERTEX_PROJECT_ID') ?? null, ...opts } = {}) {
  29. if (!region) {
  30. throw new Error('No region was given. The client should be instantiated with the `region` option or the `CLOUD_ML_REGION` environment variable should be set.');
  31. }
  32. super({
  33. baseURL: baseURL ||
  34. (region === 'global' ?
  35. 'https://aiplatform.googleapis.com/v1'
  36. : `https://${region}-aiplatform.googleapis.com/v1`),
  37. ...opts,
  38. });
  39. this.messages = makeMessagesResource(this);
  40. this.beta = makeBetaResource(this);
  41. this.region = region;
  42. this.projectId = projectId;
  43. this.accessToken = opts.accessToken ?? null;
  44. if (opts.authClient && opts.googleAuth) {
  45. throw new Error('You cannot provide both `authClient` and `googleAuth`. Please provide only one of them.');
  46. }
  47. else if (opts.authClient) {
  48. this._authClientPromise = Promise.resolve(opts.authClient);
  49. }
  50. else {
  51. this._auth =
  52. opts.googleAuth ?? new GoogleAuth({ scopes: 'https://www.googleapis.com/auth/cloud-platform' });
  53. this._authClientPromise = this._auth.getClient();
  54. }
  55. }
  56. validateHeaders() {
  57. // auth validation is handled in prepareOptions since it needs to be async
  58. }
  59. async prepareOptions(options) {
  60. const authClient = await this._authClientPromise;
  61. const authHeaders = await authClient.getRequestHeaders();
  62. const projectId = authClient.projectId ?? authHeaders['x-goog-user-project'];
  63. if (!this.projectId && projectId) {
  64. this.projectId = projectId;
  65. }
  66. options.headers = buildHeaders([authHeaders, options.headers]);
  67. }
  68. async buildRequest(options) {
  69. if (isObj(options.body)) {
  70. // create a shallow copy of the request body so that code that mutates it later
  71. // doesn't mutate the original user-provided object
  72. options.body = { ...options.body };
  73. }
  74. if (isObj(options.body)) {
  75. if (!options.body['anthropic_version']) {
  76. options.body['anthropic_version'] = DEFAULT_VERSION;
  77. }
  78. }
  79. if (MODEL_ENDPOINTS.has(options.path) && options.method === 'post') {
  80. if (!this.projectId) {
  81. throw new Error('No projectId was given and it could not be resolved from credentials. The client should be instantiated with the `projectId` option or the `ANTHROPIC_VERTEX_PROJECT_ID` environment variable should be set.');
  82. }
  83. if (!isObj(options.body)) {
  84. throw new Error('Expected request body to be an object for post /v1/messages');
  85. }
  86. const model = options.body['model'];
  87. options.body['model'] = undefined;
  88. const stream = options.body['stream'] ?? false;
  89. const specifier = stream ? 'streamRawPredict' : 'rawPredict';
  90. options.path = `/projects/${this.projectId}/locations/${this.region}/publishers/anthropic/models/${model}:${specifier}`;
  91. }
  92. if (options.path === '/v1/messages/count_tokens' ||
  93. (options.path == '/v1/messages/count_tokens?beta=true' && options.method === 'post')) {
  94. if (!this.projectId) {
  95. throw new Error('No projectId was given and it could not be resolved from credentials. The client should be instantiated with the `projectId` option or the `ANTHROPIC_VERTEX_PROJECT_ID` environment variable should be set.');
  96. }
  97. options.path = `/projects/${this.projectId}/locations/${this.region}/publishers/anthropic/models/count-tokens:rawPredict`;
  98. }
  99. return super.buildRequest(options);
  100. }
  101. }
  102. function makeMessagesResource(client) {
  103. const resource = new Resources.Messages(client);
  104. // @ts-expect-error we're deleting non-optional properties
  105. delete resource.batches;
  106. return resource;
  107. }
  108. function makeBetaResource(client) {
  109. const resource = new Resources.Beta(client);
  110. // @ts-expect-error we're deleting non-optional properties
  111. delete resource.messages.batches;
  112. return resource;
  113. }
  114. //# sourceMappingURL=client.mjs.map