Skip to content

Commit cb620bb

Browse files
stainless-emRobertCraigie
authored andcommitted
fix(bedrock,vertex): update to new SDK version
1 parent ff925db commit cb620bb

27 files changed

+259
-413
lines changed

.prettierignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,3 +5,4 @@ CHANGELOG.md
55

66
# don't format tsc output, will break source maps
77
/dist
8+
/packages/*/dist

packages/bedrock-sdk/build

100644100755
Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -24,17 +24,16 @@ node scripts/postprocess-dist-package-json.cjs
2424

2525
# build to .js/.mjs/.d.ts files
2626
npm exec tsc-multi
27-
# we need to add exports = module.exports = Anthropic TypeScript to index.js;
28-
# No way to get that from index.ts because it would cause compile errors
27+
# we need to patch index.js so that `new module.exports()` works for cjs backwards
28+
# compat. No way to get that from index.ts because it would cause compile errors
2929
# when building .mjs
3030
DIST_PATH=./dist node ../../scripts/utils/fix-index-exports.cjs
3131

32-
# with "moduleResolution": "nodenext", if ESM resolves to index.d.ts,
33-
# it'll have TS errors on the default import. But if it resolves to
34-
# index.d.mts the default import will work (even though both files have
35-
# the same export default statement)
36-
cp dist/index.d.ts dist/index.d.mts
3732
cp tsconfig.dist-src.json dist/src/tsconfig.json
33+
cp src/internal/shim-types.d.ts dist/internal/shim-types.d.ts
34+
cp src/internal/shim-types.d.ts dist/internal/shim-types.d.mts
35+
mkdir -p dist/internal/shims
36+
cp src/internal/shims/*.{mjs,js,d.ts,d.mts} dist/internal/shims
3837

3938
DIST_PATH=./dist PKG_IMPORT_PATH=@anthropic-ai/bedrock-sdk/ node ../../scripts/utils/postprocess-files.cjs
4039

packages/bedrock-sdk/package.json

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@
3535
"@smithy/util-base64": "^2.0.0"
3636
},
3737
"devDependencies": {
38+
"@types/node": "^20.17.6",
3839
"@types/jest": "^29.4.0",
3940
"@typescript-eslint/eslint-plugin": "^6.7.0",
4041
"@typescript-eslint/parser": "^6.7.0",
@@ -46,7 +47,7 @@
4647
"ts-jest": "^29.1.0",
4748
"ts-morph": "^19.0.0",
4849
"ts-node": "^10.5.0",
49-
"tsc-multi": "^1.1.0",
50+
"tsc-multi": "https://github.com/stainless-api/tsc-multi/releases/download/v1.1.3/tsc-multi.tgz",
5051
"tsconfig-paths": "^4.0.0",
5152
"typescript": "^4.8.2"
5253
},

packages/bedrock-sdk/src/client.ts

Lines changed: 32 additions & 47 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,19 @@
1-
import * as Core from '@anthropic-ai/sdk/core';
1+
import { BaseAnthropic, ClientOptions as CoreClientOptions } from '@anthropic-ai/sdk/client';
22
import * as Resources from '@anthropic-ai/sdk/resources/index';
3-
import * as API from '@anthropic-ai/sdk/index';
4-
import { getAuthHeaders } from './auth';
5-
import { Stream } from './streaming';
3+
import { getAuthHeaders } from './core/auth';
4+
import { Stream } from './core/streaming';
5+
import { readEnv } from './internal/utils/env';
6+
import { FinalRequestOptions } from './internal/request-options';
7+
import { isObj } from './internal/utils/values';
8+
import { buildHeaders } from './internal/headers';
9+
import { FinalizedRequestInit } from './internal/types';
10+
11+
export { BaseAnthropic } from '@anthropic-ai/sdk/client';
612

713
const DEFAULT_VERSION = 'bedrock-2023-05-31';
814
const MODEL_ENDPOINTS = new Set<string>(['/v1/complete', '/v1/messages', '/v1/messages?beta=true']);
915

10-
export type ClientOptions = Omit<API.ClientOptions, 'apiKey' | 'authToken'> & {
16+
export type ClientOptions = Omit<CoreClientOptions, 'apiKey' | 'authToken'> & {
1117
awsSecretKey?: string | null | undefined;
1218
awsAccessKey?: string | null | undefined;
1319

@@ -19,14 +25,12 @@ export type ClientOptions = Omit<API.ClientOptions, 'apiKey' | 'authToken'> & {
1925
};
2026

2127
/** API Client for interfacing with the Anthropic Bedrock API. */
22-
export class AnthropicBedrock extends Core.APIClient {
28+
export class AnthropicBedrock extends BaseAnthropic {
2329
awsSecretKey: string | null;
2430
awsAccessKey: string | null;
2531
awsRegion: string;
2632
awsSessionToken: string | null;
2733

28-
private _options: ClientOptions;
29-
3034
/**
3135
* API Client for interfacing with the Anthropic Bedrock API.
3236
*
@@ -36,37 +40,25 @@ export class AnthropicBedrock extends Core.APIClient {
3640
* @param {string | null | undefined} [opts.awsSessionToken]
3741
* @param {string} [opts.baseURL=process.env['ANTHROPIC_BEDROCK_BASE_URL'] ?? https://bedrock-runtime.${this.awsRegion}.amazonaws.com] - Override the default base URL for the API.
3842
* @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.
43+
* @param {MergedRequestInit} [opts.fetchOptions] - Additional `RequestInit` options to be passed to `fetch` calls.
44+
* @param {Fetch} [opts.fetch] - Specify a custom `fetch` function implementation.
4145
* @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.
46+
* @param {HeadersLike} opts.defaultHeaders - Default headers to include with every request to the API.
47+
* @param {Record<string, string | undefined>} opts.defaultQuery - Default query parameters to include with every request to the API.
48+
* @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.
4449
*/
4550
constructor({
46-
baseURL = Core.readEnv('ANTHROPIC_BEDROCK_BASE_URL'),
51+
awsRegion = readEnv('AWS_REGION') ?? 'us-east-1',
52+
baseURL = readEnv('ANTHROPIC_BEDROCK_BASE_URL') ?? `https://bedrock-runtime.${awsRegion}.amazonaws.com`,
4753
awsSecretKey = null,
4854
awsAccessKey = null,
49-
awsRegion = Core.readEnv('AWS_REGION') ?? 'us-east-1',
5055
awsSessionToken = null,
5156
...opts
5257
}: ClientOptions = {}) {
53-
const options: ClientOptions = {
54-
awsSecretKey,
55-
awsAccessKey,
56-
awsRegion,
57-
awsSessionToken,
58-
...opts,
59-
baseURL: baseURL || `https://bedrock-runtime.${awsRegion}.amazonaws.com`,
60-
};
61-
6258
super({
63-
baseURL: options.baseURL!,
64-
timeout: options.timeout ?? 600000 /* 10 minutes */,
65-
httpAgent: options.httpAgent,
66-
maxRetries: options.maxRetries,
67-
fetch: options.fetch,
59+
baseURL,
60+
...opts,
6861
});
69-
this._options = options;
7062

7163
this.awsSecretKey = awsSecretKey;
7264
this.awsAccessKey = awsAccessKey;
@@ -78,20 +70,13 @@ export class AnthropicBedrock extends Core.APIClient {
7870
completions: Resources.Completions = new Resources.Completions(this);
7971
beta: BetaResource = makeBetaResource(this);
8072

81-
protected override defaultQuery(): Core.DefaultQuery | undefined {
82-
return this._options.defaultQuery;
83-
}
84-
85-
protected override defaultHeaders(opts: Core.FinalRequestOptions): Core.Headers {
86-
return {
87-
...super.defaultHeaders(opts),
88-
...this._options.defaultHeaders,
89-
};
73+
protected override validateHeaders() {
74+
// auth validation is handled in prepareRequest since it needs to be async
9075
}
9176

9277
protected override async prepareRequest(
93-
request: RequestInit,
94-
{ url, options }: { url: string; options: Core.FinalRequestOptions },
78+
request: FinalizedRequestInit,
79+
{ url, options }: { url: string; options: FinalRequestOptions },
9580
): Promise<void> {
9681
const regionName = this.awsRegion;
9782
if (!regionName) {
@@ -107,37 +92,37 @@ export class AnthropicBedrock extends Core.APIClient {
10792
awsSecretKey: this.awsSecretKey,
10893
awsSessionToken: this.awsSessionToken,
10994
});
110-
request.headers = { ...request.headers, ...headers };
95+
request.headers = buildHeaders([headers, request.headers]).values;
11196
}
11297

113-
override buildRequest(options: Core.FinalRequestOptions<unknown>): {
114-
req: RequestInit;
98+
override buildRequest(options: FinalRequestOptions): {
99+
req: FinalizedRequestInit;
115100
url: string;
116101
timeout: number;
117102
} {
118103
options.__streamClass = Stream;
119104

120-
if (Core.isObj(options.body)) {
105+
if (isObj(options.body)) {
121106
// create a shallow copy of the request body so that code that mutates it later
122107
// doesn't mutate the original user-provided object
123108
options.body = { ...options.body };
124109
}
125110

126-
if (Core.isObj(options.body)) {
111+
if (isObj(options.body)) {
127112
if (!options.body['anthropic_version']) {
128113
options.body['anthropic_version'] = DEFAULT_VERSION;
129114
}
130115

131116
if (options.headers && !options.body['anthropic_beta']) {
132-
const betas = Core.getHeader(options.headers, 'anthropic-beta');
117+
const betas = buildHeaders([options.headers]).values.get('anthropic-beta');
133118
if (betas != null) {
134119
options.body['anthropic_beta'] = betas.split(',');
135120
}
136121
}
137122
}
138123

139124
if (MODEL_ENDPOINTS.has(options.path) && options.method === 'post') {
140-
if (!Core.isObj(options.body)) {
125+
if (!isObj(options.body)) {
141126
throw new Error('Expected request body to be an object for post /v1/messages');
142127
}
143128

packages/bedrock-sdk/src/auth.ts renamed to packages/bedrock-sdk/src/core/auth.ts

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@ import { SignatureV4 } from '@smithy/signature-v4';
33
import { fromNodeProviderChain } from '@aws-sdk/credential-providers';
44
import { HttpRequest } from '@smithy/protocol-http';
55
import { Sha256 } from '@aws-crypto/sha256-js';
6-
import type { RequestInit } from '@anthropic-ai/sdk/_shims/index';
76

87
type AuthProps = {
98
url: string;
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
export * from '@anthropic-ai/sdk/core/error';
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
export * from '@anthropic-ai/sdk/core/pagination';

packages/bedrock-sdk/src/streaming.ts renamed to packages/bedrock-sdk/src/core/streaming.ts

Lines changed: 6 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -2,15 +2,12 @@ import { EventStreamMarshaller } from '@smithy/eventstream-serde-node';
22
import { fromBase64, toBase64 } from '@smithy/util-base64';
33
import { streamCollector } from '@smithy/fetch-http-handler';
44
import { EventStreamSerdeContext, SerdeContext } from '@smithy/types';
5-
import {
6-
Stream as CoreStream,
7-
readableStreamAsyncIterable,
8-
ServerSentEvent,
9-
} from '@anthropic-ai/sdk/streaming';
5+
import { Stream as CoreStream, ServerSentEvent } from '@anthropic-ai/sdk/streaming';
106
import { AnthropicError } from '@anthropic-ai/sdk/error';
117
import { APIError } from '@anthropic-ai/sdk';
12-
import { createResponseHeaders, safeJSON } from '@anthropic-ai/sdk/core';
13-
import { de_ResponseStream } from './AWS_restJson1';
8+
import { de_ResponseStream } from '../AWS_restJson1';
9+
import { ReadableStreamToAsyncIterable } from '../internal/shims';
10+
import { safeJSON } from '../internal/utils/values';
1411

1512
type Bytes = string | ArrayBuffer | Uint8Array | Buffer | null | undefined;
1613

@@ -42,7 +39,7 @@ export class Stream<Item> extends CoreStream<Item> {
4239
throw new AnthropicError(`Attempted to iterate over a response with no body`);
4340
}
4441

45-
const responseBodyIter = readableStreamAsyncIterable<Bytes>(response.body);
42+
const responseBodyIter = ReadableStreamToAsyncIterable<Bytes>(response.body);
4643
const eventStream = de_ResponseStream(responseBodyIter, getMinimalSerdeContext());
4744
for await (const event of eventStream) {
4845
if (event.chunk && event.chunk.bytes) {
@@ -84,7 +81,7 @@ export class Stream<Item> extends CoreStream<Item> {
8481
const errJSON = safeJSON(errText);
8582
const errMessage = errJSON ? undefined : errText;
8683

87-
throw APIError.generate(undefined, errJSON, errMessage, createResponseHeaders(response.headers));
84+
throw APIError.generate(undefined, errJSON, errMessage, response.headers);
8885
}
8986
}
9087
done = true;

packages/bedrock-sdk/src/index.ts

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,2 @@
1-
import { AnthropicBedrock } from './client';
2-
3-
export default AnthropicBedrock;
4-
export { AnthropicBedrock };
1+
export * from './client';
2+
export { AnthropicBedrock as default } from './client';

packages/bedrock-sdk/src/internal

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
../../../src/internal/

0 commit comments

Comments
 (0)