Add extracted source directory and README navigation

This commit is contained in:
Shawn Bot
2026-03-31 14:56:06 +00:00
parent 6252bb6eb5
commit 91e01d755b
4757 changed files with 984951 additions and 0 deletions

View File

@@ -0,0 +1,114 @@
import { BaseAnthropic } from '@anthropic-ai/sdk/client';
import * as Resources from '@anthropic-ai/sdk/resources/index';
import { GoogleAuth } from 'google-auth-library';
import { readEnv } from "./internal/utils/env.mjs";
import { isObj } from "./internal/utils/values.mjs";
import { buildHeaders } from "./internal/headers.mjs";
export { BaseAnthropic } from '@anthropic-ai/sdk/client';
const DEFAULT_VERSION = 'vertex-2023-10-16';
const MODEL_ENDPOINTS = new Set(['/v1/messages', '/v1/messages?beta=true']);
export class AnthropicVertex extends BaseAnthropic {
/**
* API Client for interfacing with the Anthropic Vertex API.
*
* @param {string | null} opts.accessToken
* @param {string | null} opts.projectId
* @param {GoogleAuth} opts.googleAuth - Override the default google auth config
* @param {AuthClient} opts.authClient - Provide a pre-configured AuthClient instance (alternative to googleAuth)
* @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).
* @param {string} [opts.baseURL=process.env['ANTHROPIC_VERTEX__BASE_URL'] ?? https://${region}-aiplatform.googleapis.com/v1] - Override the default base URL for the API.
* @param {number} [opts.timeout=10 minutes] - The maximum amount of time (in milliseconds) the client will wait for a response before timing out.
* @param {MergedRequestInit} [opts.fetchOptions] - Additional `RequestInit` options to be passed to `fetch` calls.
* @param {Fetch} [opts.fetch] - Specify a custom `fetch` function implementation.
* @param {number} [opts.maxRetries=2] - The maximum number of times the client will retry a request.
* @param {HeadersLike} opts.defaultHeaders - Default headers to include with every request to the API.
* @param {Record<string, string | undefined>} opts.defaultQuery - Default query parameters to include with every request to the API.
* @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.
*/
constructor({ baseURL = readEnv('ANTHROPIC_VERTEX_BASE_URL'), region = readEnv('CLOUD_ML_REGION') ?? null, projectId = readEnv('ANTHROPIC_VERTEX_PROJECT_ID') ?? null, ...opts } = {}) {
if (!region) {
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.');
}
super({
baseURL: baseURL ||
(region === 'global' ?
'https://aiplatform.googleapis.com/v1'
: `https://${region}-aiplatform.googleapis.com/v1`),
...opts,
});
this.messages = makeMessagesResource(this);
this.beta = makeBetaResource(this);
this.region = region;
this.projectId = projectId;
this.accessToken = opts.accessToken ?? null;
if (opts.authClient && opts.googleAuth) {
throw new Error('You cannot provide both `authClient` and `googleAuth`. Please provide only one of them.');
}
else if (opts.authClient) {
this._authClientPromise = Promise.resolve(opts.authClient);
}
else {
this._auth =
opts.googleAuth ?? new GoogleAuth({ scopes: 'https://www.googleapis.com/auth/cloud-platform' });
this._authClientPromise = this._auth.getClient();
}
}
validateHeaders() {
// auth validation is handled in prepareOptions since it needs to be async
}
async prepareOptions(options) {
const authClient = await this._authClientPromise;
const authHeaders = await authClient.getRequestHeaders();
const projectId = authClient.projectId ?? authHeaders['x-goog-user-project'];
if (!this.projectId && projectId) {
this.projectId = projectId;
}
options.headers = buildHeaders([authHeaders, options.headers]);
}
async buildRequest(options) {
if (isObj(options.body)) {
// create a shallow copy of the request body so that code that mutates it later
// doesn't mutate the original user-provided object
options.body = { ...options.body };
}
if (isObj(options.body)) {
if (!options.body['anthropic_version']) {
options.body['anthropic_version'] = DEFAULT_VERSION;
}
}
if (MODEL_ENDPOINTS.has(options.path) && options.method === 'post') {
if (!this.projectId) {
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.');
}
if (!isObj(options.body)) {
throw new Error('Expected request body to be an object for post /v1/messages');
}
const model = options.body['model'];
options.body['model'] = undefined;
const stream = options.body['stream'] ?? false;
const specifier = stream ? 'streamRawPredict' : 'rawPredict';
options.path = `/projects/${this.projectId}/locations/${this.region}/publishers/anthropic/models/${model}:${specifier}`;
}
if (options.path === '/v1/messages/count_tokens' ||
(options.path == '/v1/messages/count_tokens?beta=true' && options.method === 'post')) {
if (!this.projectId) {
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.');
}
options.path = `/projects/${this.projectId}/locations/${this.region}/publishers/anthropic/models/count-tokens:rawPredict`;
}
return super.buildRequest(options);
}
}
function makeMessagesResource(client) {
const resource = new Resources.Messages(client);
// @ts-expect-error we're deleting non-optional properties
delete resource.batches;
return resource;
}
function makeBetaResource(client) {
const resource = new Resources.Beta(client);
// @ts-expect-error we're deleting non-optional properties
delete resource.messages.batches;
return resource;
}
//# sourceMappingURL=client.mjs.map

View File

@@ -0,0 +1,2 @@
export * from '@anthropic-ai/sdk/core/error';
//# sourceMappingURL=error.mjs.map

View File

@@ -0,0 +1,3 @@
export * from "./client.mjs";
export { AnthropicVertex as default } from "./client.mjs";
//# sourceMappingURL=index.mjs.map

View File

@@ -0,0 +1,74 @@
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
import { isReadonlyArray } from "./utils/values.mjs";
const brand_privateNullableHeaders = Symbol.for('brand.privateNullableHeaders');
function* iterateHeaders(headers) {
if (!headers)
return;
if (brand_privateNullableHeaders in headers) {
const { values, nulls } = headers;
yield* values.entries();
for (const name of nulls) {
yield [name, null];
}
return;
}
let shouldClear = false;
let iter;
if (headers instanceof Headers) {
iter = headers.entries();
}
else if (isReadonlyArray(headers)) {
iter = headers;
}
else {
shouldClear = true;
iter = Object.entries(headers ?? {});
}
for (let row of iter) {
const name = row[0];
if (typeof name !== 'string')
throw new TypeError('expected header name to be a string');
const values = isReadonlyArray(row[1]) ? row[1] : [row[1]];
let didClear = false;
for (const value of values) {
if (value === undefined)
continue;
// Objects keys always overwrite older headers, they never append.
// Yield a null to clear the header before adding the new values.
if (shouldClear && !didClear) {
didClear = true;
yield [name, null];
}
yield [name, value];
}
}
}
export const buildHeaders = (newHeaders) => {
const targetHeaders = new Headers();
const nullHeaders = new Set();
for (const headers of newHeaders) {
const seenHeaders = new Set();
for (const [name, value] of iterateHeaders(headers)) {
const lowerName = name.toLowerCase();
if (!seenHeaders.has(lowerName)) {
targetHeaders.delete(name);
seenHeaders.add(lowerName);
}
if (value === null) {
targetHeaders.delete(name);
nullHeaders.add(lowerName);
}
else {
targetHeaders.append(name, value);
nullHeaders.delete(lowerName);
}
}
}
return { [brand_privateNullableHeaders]: true, values: targetHeaders, nulls: nullHeaders };
};
export const isEmptyHeaders = (headers) => {
for (const _ of iterateHeaders(headers))
return false;
return true;
};
//# sourceMappingURL=headers.mjs.map

View File

@@ -0,0 +1,18 @@
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
/**
* Read an environment variable.
*
* Trims beginning and trailing whitespace.
*
* Will return undefined if the environment variable doesn't exist or cannot be accessed.
*/
export const readEnv = (env) => {
if (typeof globalThis.process !== 'undefined') {
return globalThis.process.env?.[env]?.trim() ?? undefined;
}
if (typeof globalThis.Deno !== 'undefined') {
return globalThis.Deno.env?.get?.(env)?.trim();
}
return undefined;
};
//# sourceMappingURL=env.mjs.map

View File

@@ -0,0 +1,94 @@
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
import { AnthropicError } from "../../core/error.mjs";
// https://url.spec.whatwg.org/#url-scheme-string
const startsWithSchemeRegexp = /^[a-z][a-z0-9+.-]*:/i;
export const isAbsoluteURL = (url) => {
return startsWithSchemeRegexp.test(url);
};
export let isArray = (val) => ((isArray = Array.isArray), isArray(val));
export let isReadonlyArray = isArray;
/** Returns an object if the given value isn't an object, otherwise returns as-is */
export function maybeObj(x) {
if (typeof x !== 'object') {
return {};
}
return x ?? {};
}
// https://stackoverflow.com/a/34491287
export function isEmptyObj(obj) {
if (!obj)
return true;
for (const _k in obj)
return false;
return true;
}
// https://eslint.org/docs/latest/rules/no-prototype-builtins
export function hasOwn(obj, key) {
return Object.prototype.hasOwnProperty.call(obj, key);
}
export function isObj(obj) {
return obj != null && typeof obj === 'object' && !Array.isArray(obj);
}
export const ensurePresent = (value) => {
if (value == null) {
throw new AnthropicError(`Expected a value to be given but received ${value} instead.`);
}
return value;
};
export const validatePositiveInteger = (name, n) => {
if (typeof n !== 'number' || !Number.isInteger(n)) {
throw new AnthropicError(`${name} must be an integer`);
}
if (n < 0) {
throw new AnthropicError(`${name} must be a positive integer`);
}
return n;
};
export const coerceInteger = (value) => {
if (typeof value === 'number')
return Math.round(value);
if (typeof value === 'string')
return parseInt(value, 10);
throw new AnthropicError(`Could not coerce ${value} (type: ${typeof value}) into a number`);
};
export const coerceFloat = (value) => {
if (typeof value === 'number')
return value;
if (typeof value === 'string')
return parseFloat(value);
throw new AnthropicError(`Could not coerce ${value} (type: ${typeof value}) into a number`);
};
export const coerceBoolean = (value) => {
if (typeof value === 'boolean')
return value;
if (typeof value === 'string')
return value === 'true';
return Boolean(value);
};
export const maybeCoerceInteger = (value) => {
if (value == null) {
return undefined;
}
return coerceInteger(value);
};
export const maybeCoerceFloat = (value) => {
if (value == null) {
return undefined;
}
return coerceFloat(value);
};
export const maybeCoerceBoolean = (value) => {
if (value == null) {
return undefined;
}
return coerceBoolean(value);
};
export const safeJSON = (text) => {
try {
return JSON.parse(text);
}
catch (err) {
return undefined;
}
};
//# sourceMappingURL=values.mjs.map