@anthropic-ai/sdk 0.101.0 → 0.103.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +28 -0
- package/client.d.mts +35 -2
- package/client.d.mts.map +1 -1
- package/client.d.ts +35 -2
- package/client.d.ts.map +1 -1
- package/client.js +74 -24
- package/client.js.map +1 -1
- package/client.mjs +73 -23
- package/client.mjs.map +1 -1
- package/core/middleware.d.mts +42 -5
- package/core/middleware.d.mts.map +1 -1
- package/core/middleware.d.ts +42 -5
- package/core/middleware.d.ts.map +1 -1
- package/core/middleware.js +14 -7
- package/core/middleware.js.map +1 -1
- package/core/middleware.mjs +14 -7
- package/core/middleware.mjs.map +1 -1
- package/core/streaming.d.mts +9 -0
- package/core/streaming.d.mts.map +1 -1
- package/core/streaming.d.ts +9 -0
- package/core/streaming.d.ts.map +1 -1
- package/core/streaming.js +11 -0
- package/core/streaming.js.map +1 -1
- package/core/streaming.mjs +11 -0
- package/core/streaming.mjs.map +1 -1
- package/index.d.mts +1 -0
- package/index.d.mts.map +1 -1
- package/index.d.ts +1 -0
- package/index.d.ts.map +1 -1
- package/index.js +4 -1
- package/index.js.map +1 -1
- package/index.mjs +1 -0
- package/index.mjs.map +1 -1
- package/internal/parse.d.mts.map +1 -1
- package/internal/parse.d.ts.map +1 -1
- package/internal/parse.js +0 -3
- package/internal/parse.js.map +1 -1
- package/internal/parse.mjs +0 -3
- package/internal/parse.mjs.map +1 -1
- package/internal/request-options.d.mts +46 -3
- package/internal/request-options.d.mts.map +1 -1
- package/internal/request-options.d.ts +46 -3
- package/internal/request-options.d.ts.map +1 -1
- package/internal/request-options.js +12 -1
- package/internal/request-options.js.map +1 -1
- package/internal/request-options.mjs +10 -0
- package/internal/request-options.mjs.map +1 -1
- package/internal/utils/log.d.mts +11 -1
- package/internal/utils/log.d.mts.map +1 -1
- package/internal/utils/log.d.ts +11 -1
- package/internal/utils/log.d.ts.map +1 -1
- package/internal/utils/log.js +34 -9
- package/internal/utils/log.js.map +1 -1
- package/internal/utils/log.mjs +32 -8
- package/internal/utils/log.mjs.map +1 -1
- package/lib/BetaMessageStream.d.mts.map +1 -1
- package/lib/BetaMessageStream.d.ts.map +1 -1
- package/lib/BetaMessageStream.js +5 -0
- package/lib/BetaMessageStream.js.map +1 -1
- package/lib/BetaMessageStream.mjs +5 -0
- package/lib/BetaMessageStream.mjs.map +1 -1
- package/lib/middleware.d.mts +96 -0
- package/lib/middleware.d.mts.map +1 -0
- package/lib/middleware.d.ts +96 -0
- package/lib/middleware.d.ts.map +1 -0
- package/lib/middleware.js +703 -0
- package/lib/middleware.js.map +1 -0
- package/lib/middleware.mjs +698 -0
- package/lib/middleware.mjs.map +1 -0
- package/lib/tools/BetaToolRunner.d.mts +1 -1
- package/lib/tools/BetaToolRunner.d.mts.map +1 -1
- package/lib/tools/BetaToolRunner.d.ts +1 -1
- package/lib/tools/BetaToolRunner.d.ts.map +1 -1
- package/lib/tools/BetaToolRunner.js +10 -2
- package/lib/tools/BetaToolRunner.js.map +1 -1
- package/lib/tools/BetaToolRunner.mjs +10 -2
- package/lib/tools/BetaToolRunner.mjs.map +1 -1
- package/package.json +1 -1
- package/resources/beta/agents/agents.d.mts +12 -22
- package/resources/beta/agents/agents.d.mts.map +1 -1
- package/resources/beta/agents/agents.d.ts +12 -22
- package/resources/beta/agents/agents.d.ts.map +1 -1
- package/resources/beta/agents/agents.js.map +1 -1
- package/resources/beta/agents/agents.mjs.map +1 -1
- package/resources/beta/beta.d.mts +3 -3
- package/resources/beta/beta.d.mts.map +1 -1
- package/resources/beta/beta.d.ts +3 -3
- package/resources/beta/beta.d.ts.map +1 -1
- package/resources/beta/beta.js.map +1 -1
- package/resources/beta/beta.mjs.map +1 -1
- package/resources/beta/index.d.mts +1 -1
- package/resources/beta/index.d.mts.map +1 -1
- package/resources/beta/index.d.ts +1 -1
- package/resources/beta/index.d.ts.map +1 -1
- package/resources/beta/index.js.map +1 -1
- package/resources/beta/index.mjs.map +1 -1
- package/resources/beta/messages/batches.d.mts +28 -0
- package/resources/beta/messages/batches.d.mts.map +1 -1
- package/resources/beta/messages/batches.d.ts +28 -0
- package/resources/beta/messages/batches.d.ts.map +1 -1
- package/resources/beta/messages/index.d.mts +1 -1
- package/resources/beta/messages/index.d.mts.map +1 -1
- package/resources/beta/messages/index.d.ts +1 -1
- package/resources/beta/messages/index.d.ts.map +1 -1
- package/resources/beta/messages/index.js.map +1 -1
- package/resources/beta/messages/index.mjs.map +1 -1
- package/resources/beta/messages/messages.d.mts +247 -8
- package/resources/beta/messages/messages.d.mts.map +1 -1
- package/resources/beta/messages/messages.d.ts +247 -8
- package/resources/beta/messages/messages.d.ts.map +1 -1
- package/resources/beta/messages/messages.js +7 -0
- package/resources/beta/messages/messages.js.map +1 -1
- package/resources/beta/messages/messages.mjs +7 -0
- package/resources/beta/messages/messages.mjs.map +1 -1
- package/resources/beta/models.d.mts +6 -0
- package/resources/beta/models.d.mts.map +1 -1
- package/resources/beta/models.d.ts +6 -0
- package/resources/beta/models.d.ts.map +1 -1
- package/resources/beta/webhooks.d.mts +22 -22
- package/resources/beta/webhooks.d.ts +22 -22
- package/resources/messages/messages.d.mts +3 -2
- package/resources/messages/messages.d.mts.map +1 -1
- package/resources/messages/messages.d.ts +3 -2
- package/resources/messages/messages.d.ts.map +1 -1
- package/resources/messages/messages.js +1 -0
- package/resources/messages/messages.js.map +1 -1
- package/resources/messages/messages.mjs +1 -0
- package/resources/messages/messages.mjs.map +1 -1
- package/src/client.ts +92 -27
- package/src/core/middleware.ts +53 -7
- package/src/core/streaming.ts +15 -0
- package/src/index.ts +6 -0
- package/src/internal/parse.ts +0 -4
- package/src/internal/request-options.ts +48 -3
- package/src/internal/utils/log.ts +39 -9
- package/src/lib/BetaMessageStream.ts +5 -0
- package/src/lib/middleware.ts +937 -0
- package/src/lib/tools/BetaToolRunner.ts +12 -3
- package/src/resources/beta/agents/agents.ts +13 -21
- package/src/resources/beta/beta.ts +15 -1
- package/src/resources/beta/index.ts +6 -0
- package/src/resources/beta/messages/batches.ts +30 -0
- package/src/resources/beta/messages/index.ts +6 -0
- package/src/resources/beta/messages/messages.ts +296 -7
- package/src/resources/beta/models.ts +7 -0
- package/src/resources/beta/webhooks.ts +22 -22
- package/src/resources/messages/messages.ts +6 -1
- package/src/version.ts +1 -1
- package/version.d.mts +1 -1
- package/version.d.ts +1 -1
- package/version.js +1 -1
- package/version.mjs +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"messages.js","sourceRoot":"","sources":["../../src/resources/messages/messages.ts"],"names":[],"mappings":";AAAA,sFAAsF;;;;AAGtF,qDAAkD;AAElD,uDAAsD;AAEtD,kFAA0E;AAC1E,8DAAwD;AACxD,gDAK0B;AAC1B,iEAAwC;AACxC,0CAcmB;AAGnB,2DAAqE;AAErE,MAAa,QAAS,SAAQ,sBAAW;IAAzC;;QACE,YAAO,GAAuB,IAAI,UAAU,CAAC,OAAO,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;IAsJrE,CAAC;IAxHC,MAAM,CACJ,IAAyB,EACzB,OAAwB;QAExB,IAAI,IAAI,CAAC,KAAK,IAAI,iBAAiB,EAAE,CAAC;YACpC,OAAO,CAAC,IAAI,CACV,cAAc,IAAI,CAAC,KAAK,iDACtB,iBAAiB,CAAC,IAAI,CAAC,KAAK,CAC9B,gIAAgI,CACjI,CAAC;QACJ,CAAC;QACD,IACE,oCAAoC,CAAC,QAAQ,CAAC,IAAI,CAAC,KAAK,CAAC;YACzD,IAAI,CAAC,QAAQ;YACb,IAAI,CAAC,QAAQ,CAAC,IAAI,KAAK,SAAS,EAChC,CAAC;YACD,OAAO,CAAC,IAAI,CACV,qBAAqB,IAAI,CAAC,KAAK,oNAAoN,CACpP,CAAC;QACJ,CAAC;QAED,IAAI,OAAO,GAAI,IAAI,CAAC,OAAe,CAAC,QAAQ,CAAC,OAAwB,CAAC;QACtE,IAAI,CAAC,IAAI,CAAC,MAAM,I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IAC9E,CAAC;CACF;AAvJD,4BAuJC;AAqiCD,MAAM,iBAAiB,GAEnB;IACF,YAAY,EAAE,oBAAoB;IAClC,iBAAiB,EAAE,oBAAoB;IACvC,oBAAoB,EAAE,oBAAoB;IAC1C,yBAAyB,EAAE,oBAAoB;IAC/C,oBAAoB,EAAE,oBAAoB;IAC1C,0BAA0B,EAAE,iBAAiB;IAC7C,wBAAwB,EAAE,mBAAmB;IAC7C,YAAY,EAAE,iBAAiB;IAC/B,YAAY,EAAE,iBAAiB;IAC/B,0BAA0B,EAAE,qBAAqB;IACjD,4BAA4B,EAAE,qBAAqB;IACnD,yBAAyB,EAAE,qBAAqB;IAChD,2BAA2B,EAAE,qBAAqB;IAClD,iBAAiB,EAAE,iBAAiB;IACpC,wBAAwB,EAAE,iBAAiB;IAC3C,mBAAmB,EAAE,iBAAiB;IACtC,0BAA0B,EAAE,iBAAiB;IAC7C,iBAAiB,EAAE,kBAAkB;IACrC,0BAA0B,EAAE,kBAAkB;IAC9C,uBAAuB,EAAE,iBAAiB;CAC3C,CAAC;AAEF,MAAM,oCAAoC,GAAY,CAAC,uBAAuB,EAAE,iBAAiB,CAAC,CAAC;AAigEnG,QAAQ,CAAC,OAAO,GAAG,iBAAO,CAAC"}
|
|
@@ -123,6 +123,7 @@ const DEPRECATED_MODELS = {
|
|
|
123
123
|
'claude-sonnet-4-20250514': 'June 15th, 2026',
|
|
124
124
|
'claude-opus-4-1': 'August 5th, 2026',
|
|
125
125
|
'claude-opus-4-1-20250805': 'August 5th, 2026',
|
|
126
|
+
'claude-mythos-preview': 'June 30th, 2026',
|
|
126
127
|
};
|
|
127
128
|
const MODELS_TO_WARN_WITH_THINKING_ENABLED = ['claude-mythos-preview', 'claude-opus-4-6'];
|
|
128
129
|
Messages.Batches = Batches;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"messages.mjs","sourceRoot":"","sources":["../../src/resources/messages/messages.ts"],"names":[],"mappings":"AAAA,sFAAsF;AAGtF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BAAiB,EAAE,oBAAoB;IACvC,oBAAoB,EAAE,oBAAoB;IAC1C,yBAAyB,EAAE,oBAAoB;IAC/C,oBAAoB,EAAE,oBAAoB;IAC1C,0BAA0B,EAAE,iBAAiB;IAC7C,wBAAwB,EAAE,mBAAmB;IAC7C,YAAY,EAAE,iBAAiB;IAC/B,YAAY,EAAE,iBAAiB;IAC/B,0BAA0B,EAAE,qBAAqB;IACjD,4BAA4B,EAAE,qBAAqB;IACnD,yBAAyB,EAAE,qBAAqB;IAChD,2BAA2B,EAAE,qBAAqB;IAClD,iBAAiB,EAAE,iBAAiB;IACpC,wBAAwB,EAAE,iBAAiB;IAC3C,mBAAmB,EAAE,iBAAiB;IACtC,0BAA0B,EAAE,iBAAiB;IAC7C,iBAAiB,EAAE,kBAAkB;IACrC,0BAA0B,EAAE,kBAAkB;IAC9C,uBAAuB,EAAE,iBAAiB;CAC3C,CAAC;AAEF,MAAM,oCAAoC,GAAY,CAAC,uBAAuB,EAAE,iBAAiB,CAAC,CAAC;AAigEnG,QAAQ,CAAC,OAAO,GAAG,OAAO,CAAC"}
|
package/src/client.ts
CHANGED
|
@@ -256,6 +256,7 @@ import { readEnv } from './internal/utils/env';
|
|
|
256
256
|
import {
|
|
257
257
|
type LogLevel,
|
|
258
258
|
type Logger,
|
|
259
|
+
defaultLogLevel,
|
|
259
260
|
formatRequestDetails,
|
|
260
261
|
loggerFor,
|
|
261
262
|
parseLogLevel,
|
|
@@ -390,7 +391,11 @@ export interface ClientOptions {
|
|
|
390
391
|
* {@link Middleware} functions that wrap every HTTP request made by the
|
|
391
392
|
* client.
|
|
392
393
|
*
|
|
393
|
-
* Middleware runs per HTTP attempt, including retries.
|
|
394
|
+
* Middleware runs per HTTP attempt, including retries. It observes the
|
|
395
|
+
* canonical Anthropic-shaped request and response on every backend: on
|
|
396
|
+
* clients for third-party backends (Bedrock, Vertex, Foundry), the
|
|
397
|
+
* backend's URL/body rewriting, request signing, and response
|
|
398
|
+
* normalization happen inside `next`.
|
|
394
399
|
*/
|
|
395
400
|
middleware?: ReadonlyArray<Middleware> | undefined;
|
|
396
401
|
|
|
@@ -537,12 +542,11 @@ export class BaseAnthropic {
|
|
|
537
542
|
this._baseURLIsExplicit = (opts as InternalClientOptions).__baseURLIsExplicit ?? !!baseURL;
|
|
538
543
|
this.timeout = options.timeout ?? BaseAnthropic.DEFAULT_TIMEOUT /* 10 minutes */;
|
|
539
544
|
this.logger = options.logger ?? console;
|
|
540
|
-
const defaultLogLevel = 'warn';
|
|
541
545
|
// Set default logLevel early so that we can log a warning in parseLogLevel.
|
|
542
546
|
this.logLevel = defaultLogLevel;
|
|
543
547
|
this.logLevel =
|
|
544
|
-
parseLogLevel(options.logLevel, 'ClientOptions.logLevel', this) ??
|
|
545
|
-
parseLogLevel(readEnv('ANTHROPIC_LOG'), "process.env['ANTHROPIC_LOG']", this) ??
|
|
548
|
+
parseLogLevel(options.logLevel, 'ClientOptions.logLevel', loggerFor(this)) ??
|
|
549
|
+
parseLogLevel(readEnv('ANTHROPIC_LOG'), "process.env['ANTHROPIC_LOG']", loggerFor(this)) ??
|
|
546
550
|
defaultLogLevel;
|
|
547
551
|
this.fetchOptions = options.fetchOptions;
|
|
548
552
|
this.maxRetries = options.maxRetries ?? 2;
|
|
@@ -655,7 +659,7 @@ export class BaseAnthropic {
|
|
|
655
659
|
* same reason, `ctx.options` is undefined for these requests.
|
|
656
660
|
*/
|
|
657
661
|
private _credentialsFetch(): Fetch {
|
|
658
|
-
return wrapFetchWithMiddleware(this.fetch, this.middleware);
|
|
662
|
+
return wrapFetchWithMiddleware(this.fetch, this.middleware, undefined, this);
|
|
659
663
|
}
|
|
660
664
|
|
|
661
665
|
private _makeTokenCache(provider: AccessTokenProvider): TokenCache {
|
|
@@ -898,6 +902,13 @@ export class BaseAnthropic {
|
|
|
898
902
|
*
|
|
899
903
|
* This is useful for cases where you want to add certain headers based off of
|
|
900
904
|
* the request properties, e.g. `method` or `url`.
|
|
905
|
+
*
|
|
906
|
+
* Runs after all middleware (including {@link backendMiddleware}),
|
|
907
|
+
* immediately before each underlying fetch call, so it sees exactly what
|
|
908
|
+
* goes over the wire. Middleware may replay a request by calling `next()`
|
|
909
|
+
* more than once, so this hook can run multiple times per attempt:
|
|
910
|
+
* overrides must be idempotent and overwrite headers from a previous
|
|
911
|
+
* invocation rather than append to them.
|
|
901
912
|
*/
|
|
902
913
|
protected async prepareRequest(
|
|
903
914
|
request: RequestInit,
|
|
@@ -925,6 +936,28 @@ export class BaseAnthropic {
|
|
|
925
936
|
}
|
|
926
937
|
}
|
|
927
938
|
|
|
939
|
+
/**
|
|
940
|
+
* Internal {@link Middleware} composed innermost in the chain — inside both
|
|
941
|
+
* client-level and per-request middleware, immediately around the underlying
|
|
942
|
+
* `fetch`. Subclasses for third-party backends override this to adapt the
|
|
943
|
+
* canonical Anthropic-shaped request to the backend's wire shape (URL/body
|
|
944
|
+
* rewriting, request signing) and to normalize the wire response back to the
|
|
945
|
+
* canonical shape (e.g. AWS EventStream to SSE).
|
|
946
|
+
*
|
|
947
|
+
* Running inside the user's middleware means user middleware always observes
|
|
948
|
+
* canonical Anthropic-shaped traffic, and the adaptation re-runs (e.g.
|
|
949
|
+
* re-signs) on every `next()` invocation, covering whatever the middleware
|
|
950
|
+
* mutated.
|
|
951
|
+
*
|
|
952
|
+
* Errors thrown here follow the middleware error policy: they propagate to
|
|
953
|
+
* the caller as-is — no retries, no `APIConnectionError` wrapping — unless
|
|
954
|
+
* retryable (see {@link Middleware}); throw a `RetryableError` to opt into
|
|
955
|
+
* the retry path.
|
|
956
|
+
*/
|
|
957
|
+
protected backendMiddleware(): ReadonlyArray<Middleware> {
|
|
958
|
+
return [];
|
|
959
|
+
}
|
|
960
|
+
|
|
928
961
|
get<Rsp>(path: string, opts?: PromiseOrValue<RequestOptions>): APIPromise<Rsp> {
|
|
929
962
|
return this.methodRequest('get', path, opts);
|
|
930
963
|
}
|
|
@@ -984,30 +1017,20 @@ export class BaseAnthropic {
|
|
|
984
1017
|
retryCount: maxRetries - retriesRemaining,
|
|
985
1018
|
});
|
|
986
1019
|
|
|
987
|
-
await this.prepareRequest(req, { url, options });
|
|
988
|
-
|
|
989
1020
|
/** Not an API request ID, just for correlating local log entries. */
|
|
990
1021
|
const requestLogID = 'log_' + ((Math.random() * (1 << 24)) | 0).toString(16).padStart(6, '0');
|
|
991
1022
|
const retryLogStr = retryOfRequestLogID === undefined ? '' : `, retryOf: ${retryOfRequestLogID}`;
|
|
992
1023
|
const startTime = Date.now();
|
|
993
1024
|
|
|
994
|
-
loggerFor(this).debug(
|
|
995
|
-
`[${requestLogID}] sending request`,
|
|
996
|
-
formatRequestDetails({
|
|
997
|
-
retryOfRequestLogID,
|
|
998
|
-
method: options.method,
|
|
999
|
-
url,
|
|
1000
|
-
options,
|
|
1001
|
-
headers: req.headers,
|
|
1002
|
-
}),
|
|
1003
|
-
);
|
|
1004
|
-
|
|
1005
1025
|
if (options.signal?.aborted) {
|
|
1006
1026
|
throw new Errors.APIUserAbortError();
|
|
1007
1027
|
}
|
|
1008
1028
|
|
|
1009
1029
|
const controller = new AbortController();
|
|
1010
|
-
const response = await this.fetchWithTimeout(url, req, timeout, controller, options
|
|
1030
|
+
const response = await this.fetchWithTimeout(url, req, timeout, controller, options, {
|
|
1031
|
+
requestLogID,
|
|
1032
|
+
retryOfRequestLogID,
|
|
1033
|
+
}).catch(castToError);
|
|
1011
1034
|
const headersTime = Date.now();
|
|
1012
1035
|
|
|
1013
1036
|
if (response instanceof globalThis.Error) {
|
|
@@ -1023,11 +1046,13 @@ export class BaseAnthropic {
|
|
|
1023
1046
|
isAbortError(response) ||
|
|
1024
1047
|
/timed? ?out/i.test(String(response) + ('cause' in response ? String(response.cause) : ''));
|
|
1025
1048
|
|
|
1026
|
-
// Errors thrown by middleware
|
|
1027
|
-
//
|
|
1028
|
-
//
|
|
1029
|
-
// which stay on the
|
|
1030
|
-
|
|
1049
|
+
// Errors thrown by middleware (user middleware and the backend adaptation
|
|
1050
|
+
// alike) propagate to the caller as-is — no retries, no APIConnectionError
|
|
1051
|
+
// wrapping — except retryable errors (timeouts/aborts, APIConnectionErrors,
|
|
1052
|
+
// and RetryableErrors, directly or in the `cause` chain), which stay on the
|
|
1053
|
+
// retry path.
|
|
1054
|
+
const hasMiddleware =
|
|
1055
|
+
this.middleware.length > 0 || !!options.middleware?.length || this.backendMiddleware().length > 0;
|
|
1031
1056
|
if (hasMiddleware && !isTimeout && !isRetryableError(response)) {
|
|
1032
1057
|
loggerFor(this).info(`[${requestLogID}] middleware error (not retryable)`);
|
|
1033
1058
|
loggerFor(this).debug(
|
|
@@ -1182,6 +1207,7 @@ export class BaseAnthropic {
|
|
|
1182
1207
|
ms: number,
|
|
1183
1208
|
controller: AbortController,
|
|
1184
1209
|
requestOptions?: FinalRequestOptions | undefined,
|
|
1210
|
+
logCtx?: { requestLogID: string; retryOfRequestLogID?: string | undefined } | undefined,
|
|
1185
1211
|
): Promise<Response> {
|
|
1186
1212
|
const { signal, method, ...options } = init || {};
|
|
1187
1213
|
// Avoid creating a closure over `this`, `init`, or `options` to prevent memory leaks.
|
|
@@ -1222,9 +1248,48 @@ export class BaseAnthropic {
|
|
|
1222
1248
|
}
|
|
1223
1249
|
};
|
|
1224
1250
|
|
|
1225
|
-
|
|
1226
|
-
|
|
1227
|
-
|
|
1251
|
+
// Prepare the request (auth signing and other `prepareRequest` hooks) as
|
|
1252
|
+
// the innermost step, after any middleware — including the backend
|
|
1253
|
+
// middleware, so it sees exactly what goes over the wire. Runs per
|
|
1254
|
+
// inner-fetch invocation, so a request middleware rewrote — or replayed
|
|
1255
|
+
// via a second `next()` call — is prepared fresh each time. Preparation is
|
|
1256
|
+
// outside the timeout timer, matching its pre-middleware behavior.
|
|
1257
|
+
const innerFetch: Fetch =
|
|
1258
|
+
requestOptions === undefined ? timedFetch : (
|
|
1259
|
+
async (innerUrl, innerInit = {}) => {
|
|
1260
|
+
const innerUrlStr =
|
|
1261
|
+
typeof innerUrl === 'string' ? innerUrl
|
|
1262
|
+
: innerUrl instanceof URL ? innerUrl.href
|
|
1263
|
+
: innerUrl.url;
|
|
1264
|
+
innerInit.headers =
|
|
1265
|
+
innerInit.headers instanceof Headers ? innerInit.headers : new Headers(innerInit.headers);
|
|
1266
|
+
|
|
1267
|
+
await this.prepareRequest(innerInit, { url: innerUrlStr, options: requestOptions });
|
|
1268
|
+
|
|
1269
|
+
if (logCtx) {
|
|
1270
|
+
loggerFor(this).debug(
|
|
1271
|
+
`[${logCtx.requestLogID}] sending request`,
|
|
1272
|
+
formatRequestDetails({
|
|
1273
|
+
retryOfRequestLogID: logCtx.retryOfRequestLogID,
|
|
1274
|
+
method: innerInit.method,
|
|
1275
|
+
url: innerUrlStr,
|
|
1276
|
+
options: requestOptions,
|
|
1277
|
+
headers: innerInit.headers,
|
|
1278
|
+
}),
|
|
1279
|
+
);
|
|
1280
|
+
}
|
|
1281
|
+
|
|
1282
|
+
return timedFetch(innerUrl, innerInit);
|
|
1283
|
+
}
|
|
1284
|
+
);
|
|
1285
|
+
|
|
1286
|
+
const requestMiddleware = requestOptions?.middleware;
|
|
1287
|
+
const backendMiddleware = this.backendMiddleware();
|
|
1288
|
+
const allMiddleware =
|
|
1289
|
+
requestMiddleware?.length || backendMiddleware.length ?
|
|
1290
|
+
[...this.middleware, ...(requestMiddleware ?? []), ...backendMiddleware]
|
|
1291
|
+
: this.middleware;
|
|
1292
|
+
return await wrapFetchWithMiddleware(innerFetch, allMiddleware, requestOptions, this)(url, fetchOptions);
|
|
1228
1293
|
}
|
|
1229
1294
|
|
|
1230
1295
|
private async shouldRetry(response: Response, options: FinalRequestOptions): Promise<boolean> {
|
package/src/core/middleware.ts
CHANGED
|
@@ -1,7 +1,9 @@
|
|
|
1
|
+
import type { BaseAnthropic } from '../client';
|
|
1
2
|
import type { Fetch } from '../internal/builtin-types';
|
|
2
3
|
import { castToError, isAbortError } from '../internal/errors';
|
|
3
4
|
import { addRequestID } from '../internal/parse';
|
|
4
5
|
import type { FinalRequestOptions } from '../internal/request-options';
|
|
6
|
+
import { defaultLogger, loggerFor, type Logger } from '../internal/utils/log';
|
|
5
7
|
import type { APIRequest } from './api';
|
|
6
8
|
import { AnthropicError, APIConnectionError, RetryableError } from './error';
|
|
7
9
|
import { Stream } from './streaming';
|
|
@@ -27,6 +29,26 @@ export interface MiddlewareContext {
|
|
|
27
29
|
*/
|
|
28
30
|
readonly options?: FinalRequestOptions | undefined;
|
|
29
31
|
|
|
32
|
+
/**
|
|
33
|
+
* The client's logger, pre-filtered to the client's configured log level
|
|
34
|
+
* (the `logLevel` client option or the `ANTHROPIC_LOG` environment
|
|
35
|
+
* variable). Calls below the active level are no-ops, so it's always safe
|
|
36
|
+
* to call; with no logger configured it writes to the global `console`.
|
|
37
|
+
*
|
|
38
|
+
* Values are logged as-is — when logging request or response headers,
|
|
39
|
+
* redact credentials (`authorization`, `x-api-key`, `cookie`) the way the
|
|
40
|
+
* SDK's own logs do.
|
|
41
|
+
*
|
|
42
|
+
* @example
|
|
43
|
+
* ```ts
|
|
44
|
+
* const mw: Middleware = async (request, next, ctx) => {
|
|
45
|
+
* ctx.logger.debug('->', request.method, request.url);
|
|
46
|
+
* return next(request);
|
|
47
|
+
* };
|
|
48
|
+
* ```
|
|
49
|
+
*/
|
|
50
|
+
readonly logger: Logger;
|
|
51
|
+
|
|
30
52
|
/**
|
|
31
53
|
* Parse a response body the way the SDK would for the request in flight:
|
|
32
54
|
*
|
|
@@ -67,6 +89,18 @@ export interface MiddlewareContext {
|
|
|
67
89
|
* or replace the response, short-circuit by returning a `Response` without
|
|
68
90
|
* calling `next`, or call `next` multiple times to implement custom retries.
|
|
69
91
|
*
|
|
92
|
+
* Middleware always observes the canonical Anthropic-shaped request — e.g.
|
|
93
|
+
* `POST .../v1/messages` with `model` and `stream` in the JSON body and
|
|
94
|
+
* `anthropic-beta` as a header — with the client's logical credentials
|
|
95
|
+
* (`x-api-key` / `Authorization`) applied. On clients for third-party
|
|
96
|
+
* backends (Bedrock, Vertex, Foundry), the backend adaptation — URL and body
|
|
97
|
+
* rewriting, request signing (e.g. AWS SigV4), and response normalization
|
|
98
|
+
* (e.g. AWS EventStream to SSE) — runs *inside* `next`, so middleware behaves
|
|
99
|
+
* identically on every backend: mutating the request is safe (signing covers
|
|
100
|
+
* the final body), and streaming responses are observed as SSE. Each `next()`
|
|
101
|
+
* call re-runs the adaptation, so custom retries re-sign from scratch. To
|
|
102
|
+
* observe the literal wire traffic instead, provide a custom `fetch`.
|
|
103
|
+
*
|
|
70
104
|
* Middleware must not consume the body of the `Response` it returns - the
|
|
71
105
|
* client still needs to read it. To inspect the body, use
|
|
72
106
|
* `await ctx.parse(response)` (cached, leaves the body readable) or read a
|
|
@@ -85,10 +119,10 @@ export interface MiddlewareContext {
|
|
|
85
119
|
*
|
|
86
120
|
* @example
|
|
87
121
|
* ```ts
|
|
88
|
-
* const logger: Middleware = async (request, next) => {
|
|
89
|
-
*
|
|
122
|
+
* const logger: Middleware = async (request, next, ctx) => {
|
|
123
|
+
* ctx.logger.debug('->', request.method, request.url);
|
|
90
124
|
* const response = await next(request);
|
|
91
|
-
*
|
|
125
|
+
* ctx.logger.debug('<-', response.status, request.url);
|
|
92
126
|
* return response;
|
|
93
127
|
* };
|
|
94
128
|
*
|
|
@@ -149,11 +183,16 @@ export function isRetryableError(err: unknown): boolean {
|
|
|
149
183
|
*
|
|
150
184
|
* `options` — the SDK request options behind this call, when there are any —
|
|
151
185
|
* is surfaced to middleware as `ctx.options` and drives `ctx.parse`.
|
|
186
|
+
*
|
|
187
|
+
* `client` supplies `ctx.logger` (the client's level-filtered logger);
|
|
188
|
+
* without it, `ctx.logger` falls back to the client defaults: `console`,
|
|
189
|
+
* filtered to `ANTHROPIC_LOG` or `'warn'`.
|
|
152
190
|
*/
|
|
153
191
|
export function wrapFetchWithMiddleware(
|
|
154
192
|
fetchFn: Fetch,
|
|
155
193
|
middleware: readonly Middleware[],
|
|
156
194
|
options?: FinalRequestOptions | undefined,
|
|
195
|
+
client?: BaseAnthropic | undefined,
|
|
157
196
|
): Fetch {
|
|
158
197
|
return async (url, init = {}) => {
|
|
159
198
|
if (middleware.length === 0) {
|
|
@@ -165,6 +204,7 @@ export function wrapFetchWithMiddleware(
|
|
|
165
204
|
fetchFn,
|
|
166
205
|
middleware,
|
|
167
206
|
options,
|
|
207
|
+
client,
|
|
168
208
|
)({
|
|
169
209
|
...init,
|
|
170
210
|
headers,
|
|
@@ -188,13 +228,19 @@ export function wrapFetchWithMiddleware(
|
|
|
188
228
|
/**
|
|
189
229
|
* Creates the {@link MiddlewareContext} shared by every middleware in one chain.
|
|
190
230
|
*/
|
|
191
|
-
function createMiddlewareContext(
|
|
231
|
+
function createMiddlewareContext(
|
|
232
|
+
options: FinalRequestOptions | undefined,
|
|
233
|
+
client: BaseAnthropic | undefined,
|
|
234
|
+
): MiddlewareContext {
|
|
192
235
|
// Keyed on the Response so each `next()` call's response (e.g. with custom
|
|
193
236
|
// retries, or a middleware swapping in a replacement) parses independently,
|
|
194
237
|
// while several middleware parsing the same response share a single read.
|
|
195
238
|
const cache = new WeakMap<Response, Promise<unknown>>();
|
|
196
239
|
return {
|
|
197
240
|
options,
|
|
241
|
+
// Resolved per chain, so changes to the client's `logLevel`/`logger`
|
|
242
|
+
// apply to subsequent requests.
|
|
243
|
+
logger: client ? loggerFor(client) : defaultLogger(),
|
|
198
244
|
parse<T>(response: Response): Promise<T> {
|
|
199
245
|
// Streams are single-consumer, so caching one would hand later callers
|
|
200
246
|
// an already-consumed stream; every call gets a fresh clone-backed one.
|
|
@@ -233,8 +279,7 @@ async function parseMiddlewareResponse(
|
|
|
233
279
|
// A fresh controller rather than the request's own: aborting (or
|
|
234
280
|
// `break`ing out of) the middleware's stream must not cancel the
|
|
235
281
|
// in-flight request the client is still reading.
|
|
236
|
-
|
|
237
|
-
return streamClass.fromSSEResponse(response.clone(), new AbortController());
|
|
282
|
+
return Stream.fromSSEResponse(response.clone(), new AbortController());
|
|
238
283
|
}
|
|
239
284
|
|
|
240
285
|
// fetch refuses to read the body when the status code is 204.
|
|
@@ -267,6 +312,7 @@ export function applyMiddleware(
|
|
|
267
312
|
fetchFn: Fetch,
|
|
268
313
|
middleware: readonly Middleware[],
|
|
269
314
|
options?: FinalRequestOptions | undefined,
|
|
315
|
+
client?: BaseAnthropic | undefined,
|
|
270
316
|
): MiddlewareNext {
|
|
271
317
|
// use undefined this binding; fetch errors if bound to something else in browser/cloudflare
|
|
272
318
|
let next: MiddlewareNext = async ({ url, ...init }) => {
|
|
@@ -282,7 +328,7 @@ export function applyMiddleware(
|
|
|
282
328
|
}
|
|
283
329
|
};
|
|
284
330
|
|
|
285
|
-
const ctx = createMiddlewareContext(options);
|
|
331
|
+
const ctx = createMiddlewareContext(options, client);
|
|
286
332
|
for (let i = middleware.length - 1; i >= 0; i--) {
|
|
287
333
|
const mw = middleware[i]!;
|
|
288
334
|
const nextInner = next;
|
package/src/core/streaming.ts
CHANGED
|
@@ -33,6 +33,21 @@ export class Stream<Item> implements AsyncIterable<Item> {
|
|
|
33
33
|
this.#client = client;
|
|
34
34
|
}
|
|
35
35
|
|
|
36
|
+
/**
|
|
37
|
+
* Iterate the raw Server-Sent Events from `response` — `{event, data, raw}`
|
|
38
|
+
* objects, before any JSON parsing or event-name filtering.
|
|
39
|
+
*
|
|
40
|
+
* This reads `response.body` directly (not a clone), so the response is
|
|
41
|
+
* consumed. Use this in middleware that fully replaces the stream body; for
|
|
42
|
+
* read-only observation of parsed events, use `ctx.parse()` instead.
|
|
43
|
+
*/
|
|
44
|
+
static rawEvents(
|
|
45
|
+
response: Response,
|
|
46
|
+
controller: AbortController = new AbortController(),
|
|
47
|
+
): AsyncGenerator<ServerSentEvent, void, unknown> {
|
|
48
|
+
return _iterSSEMessages(response, controller);
|
|
49
|
+
}
|
|
50
|
+
|
|
36
51
|
static fromSSEResponse<Item>(
|
|
37
52
|
response: Response,
|
|
38
53
|
controller: AbortController,
|
package/src/index.ts
CHANGED
|
@@ -5,6 +5,12 @@ export { Anthropic as default } from './client';
|
|
|
5
5
|
export { type Uploadable, toFile } from './core/uploads';
|
|
6
6
|
export { APIPromise } from './core/api-promise';
|
|
7
7
|
export { type Middleware, type MiddlewareContext, type MiddlewareNext } from './core/middleware';
|
|
8
|
+
export {
|
|
9
|
+
betaRefusalFallbackMiddleware,
|
|
10
|
+
BetaFallbackState,
|
|
11
|
+
type BetaRefusalFallbackError,
|
|
12
|
+
type BetaRefusalFallbackOptions,
|
|
13
|
+
} from './lib/middleware';
|
|
8
14
|
export {
|
|
9
15
|
BaseAnthropic,
|
|
10
16
|
Anthropic,
|
package/src/internal/parse.ts
CHANGED
|
@@ -27,10 +27,6 @@ export async function defaultParseResponse<T>(
|
|
|
27
27
|
// Note: there is an invariant here that isn't represented in the type system
|
|
28
28
|
// that if you set `stream: true` the response type must also be `Stream<T>`
|
|
29
29
|
|
|
30
|
-
if (props.options.__streamClass) {
|
|
31
|
-
return props.options.__streamClass.fromSSEResponse(response, props.controller) as any;
|
|
32
|
-
}
|
|
33
|
-
|
|
34
30
|
return Stream.fromSSEResponse(response, props.controller) as any;
|
|
35
31
|
}
|
|
36
32
|
|
|
@@ -10,7 +10,42 @@ import { type HeadersLike } from './headers';
|
|
|
10
10
|
|
|
11
11
|
export type FinalRequestOptions = RequestOptions & { method: HTTPMethod; path: string };
|
|
12
12
|
|
|
13
|
-
|
|
13
|
+
/**
|
|
14
|
+
* Tracks which fallback a sequence of requests is pinned to.
|
|
15
|
+
*
|
|
16
|
+
* Create one (`new BetaFallbackState()`) and pass it via the `fallbackState`
|
|
17
|
+
* request option on every request that should share the pin — the turns of one
|
|
18
|
+
* conversation, or any wider scope the stickiness should apply to;
|
|
19
|
+
* `betaRefusalFallbackMiddleware` mutates it in place when a model refuses.
|
|
20
|
+
*/
|
|
21
|
+
export class BetaFallbackState {
|
|
22
|
+
/**
|
|
23
|
+
* Index into the fallback chain the requests are pinned to.
|
|
24
|
+
*
|
|
25
|
+
* `undefined` (or -1) targets the original request params; the middleware
|
|
26
|
+
* sets it to the index of the fallback that accepted the request.
|
|
27
|
+
*/
|
|
28
|
+
index?: number;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Options for an individual API request.
|
|
33
|
+
*
|
|
34
|
+
* Declared as an interface so it can be extended via declaration merging, e.g.
|
|
35
|
+
* to thread custom per-request context through to {@link Middleware}:
|
|
36
|
+
*
|
|
37
|
+
* ```ts
|
|
38
|
+
* declare module '@anthropic-ai/sdk/internal/request-options' {
|
|
39
|
+
* interface RequestOptions {
|
|
40
|
+
* myContext?: string;
|
|
41
|
+
* }
|
|
42
|
+
* }
|
|
43
|
+
* ```
|
|
44
|
+
*
|
|
45
|
+
* The SDK ignores properties it doesn't know about; they are visible to
|
|
46
|
+
* middleware on `ctx.options`.
|
|
47
|
+
*/
|
|
48
|
+
export interface RequestOptions {
|
|
14
49
|
/**
|
|
15
50
|
* The HTTP method for the request (e.g., 'get', 'post', 'put', 'delete').
|
|
16
51
|
*/
|
|
@@ -70,10 +105,20 @@ export type RequestOptions = {
|
|
|
70
105
|
/**
|
|
71
106
|
* Additional {@link Middleware} to wrap this request's HTTP attempts.
|
|
72
107
|
*
|
|
73
|
-
* These run after any client-level middleware
|
|
108
|
+
* These run after any client-level middleware (but still outside any backend
|
|
109
|
+
* adaptation) and apply to every attempt of this request, including retries.
|
|
74
110
|
*/
|
|
75
111
|
middleware?: ReadonlyArray<Middleware> | undefined;
|
|
76
112
|
|
|
113
|
+
/**
|
|
114
|
+
* Sticky state for `betaRefusalFallbackMiddleware`.
|
|
115
|
+
*
|
|
116
|
+
* The middleware records which fallback it settled on, so requests sharing
|
|
117
|
+
* the state skip models that already refused. Pass the same object across
|
|
118
|
+
* whatever scope the pin should apply to — typically a conversation.
|
|
119
|
+
*/
|
|
120
|
+
fallbackState?: BetaFallbackState;
|
|
121
|
+
|
|
77
122
|
/**
|
|
78
123
|
* A unique key for this request to enable idempotency.
|
|
79
124
|
*/
|
|
@@ -86,7 +131,7 @@ export type RequestOptions = {
|
|
|
86
131
|
|
|
87
132
|
__binaryResponse?: boolean | undefined;
|
|
88
133
|
__streamClass?: typeof Stream;
|
|
89
|
-
}
|
|
134
|
+
}
|
|
90
135
|
|
|
91
136
|
export type EncodedContent = { bodyHeaders: HeadersLike; body: BodyInit };
|
|
92
137
|
export type RequestEncoder = (request: { headers: NullableHeaders; body: unknown }) => EncodedContent;
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
|
|
2
2
|
|
|
3
3
|
import { hasOwn } from './values';
|
|
4
|
+
import { readEnv } from './env';
|
|
4
5
|
import { type BaseAnthropic } from '../../client';
|
|
5
6
|
import { RequestOptions } from '../request-options';
|
|
6
7
|
|
|
@@ -13,6 +14,8 @@ export type Logger = {
|
|
|
13
14
|
};
|
|
14
15
|
export type LogLevel = 'off' | 'error' | 'warn' | 'info' | 'debug';
|
|
15
16
|
|
|
17
|
+
export const defaultLogLevel: LogLevel = 'warn';
|
|
18
|
+
|
|
16
19
|
const levelNumbers = {
|
|
17
20
|
off: 0,
|
|
18
21
|
error: 200,
|
|
@@ -24,7 +27,7 @@ const levelNumbers = {
|
|
|
24
27
|
export const parseLogLevel = (
|
|
25
28
|
maybeLevel: string | undefined,
|
|
26
29
|
sourceName: string,
|
|
27
|
-
|
|
30
|
+
logger: Logger,
|
|
28
31
|
): LogLevel | undefined => {
|
|
29
32
|
if (!maybeLevel) {
|
|
30
33
|
return undefined;
|
|
@@ -32,7 +35,7 @@ export const parseLogLevel = (
|
|
|
32
35
|
if (hasOwn(levelNumbers, maybeLevel)) {
|
|
33
36
|
return maybeLevel;
|
|
34
37
|
}
|
|
35
|
-
|
|
38
|
+
logger.warn(
|
|
36
39
|
`${sourceName} was set to ${JSON.stringify(maybeLevel)}, expected one of ${JSON.stringify(
|
|
37
40
|
Object.keys(levelNumbers),
|
|
38
41
|
)}`,
|
|
@@ -60,13 +63,7 @@ const noopLogger = {
|
|
|
60
63
|
|
|
61
64
|
let cachedLoggers = /* @__PURE__ */ new WeakMap<Logger, [LogLevel, Logger]>();
|
|
62
65
|
|
|
63
|
-
|
|
64
|
-
const logger = client.logger;
|
|
65
|
-
const logLevel = client.logLevel ?? 'off';
|
|
66
|
-
if (!logger) {
|
|
67
|
-
return noopLogger;
|
|
68
|
-
}
|
|
69
|
-
|
|
66
|
+
function filterLogger(logger: Logger, logLevel: LogLevel): Logger {
|
|
70
67
|
const cachedLogger = cachedLoggers.get(logger);
|
|
71
68
|
if (cachedLogger && cachedLogger[0] === logLevel) {
|
|
72
69
|
return cachedLogger[1];
|
|
@@ -84,6 +81,39 @@ export function loggerFor(client: BaseAnthropic): Logger {
|
|
|
84
81
|
return levelLogger;
|
|
85
82
|
}
|
|
86
83
|
|
|
84
|
+
export function loggerFor(client: BaseAnthropic): Logger {
|
|
85
|
+
const logger = client.logger;
|
|
86
|
+
const logLevel = client.logLevel ?? 'off';
|
|
87
|
+
if (!logger) {
|
|
88
|
+
return noopLogger;
|
|
89
|
+
}
|
|
90
|
+
return filterLogger(logger, logLevel);
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
let lastEnvLevel: string | undefined;
|
|
94
|
+
let cachedDefaultLogger: Logger | undefined;
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* A logger matching the client defaults — `console`, filtered to
|
|
98
|
+
* `ANTHROPIC_LOG` or {@link defaultLogLevel} — for contexts with no client to
|
|
99
|
+
* read the configured `logger`/`logLevel` from.
|
|
100
|
+
*
|
|
101
|
+
* Cached per `ANTHROPIC_LOG` value so an invalid value warns once, like a
|
|
102
|
+
* client construction does, rather than on every request.
|
|
103
|
+
*/
|
|
104
|
+
export function defaultLogger(): Logger {
|
|
105
|
+
const envLevel = readEnv('ANTHROPIC_LOG');
|
|
106
|
+
if (!cachedDefaultLogger || envLevel !== lastEnvLevel) {
|
|
107
|
+
lastEnvLevel = envLevel;
|
|
108
|
+
cachedDefaultLogger = filterLogger(
|
|
109
|
+
console,
|
|
110
|
+
parseLogLevel(envLevel, "process.env['ANTHROPIC_LOG']", filterLogger(console, defaultLogLevel)) ??
|
|
111
|
+
defaultLogLevel,
|
|
112
|
+
);
|
|
113
|
+
}
|
|
114
|
+
return cachedDefaultLogger;
|
|
115
|
+
}
|
|
116
|
+
|
|
87
117
|
export const formatRequestDetails = (details: {
|
|
88
118
|
options?: RequestOptions | undefined;
|
|
89
119
|
headers?: Headers | Record<string, string> | undefined;
|
|
@@ -607,6 +607,11 @@ export class BetaMessageStream<ParsedT = null> implements AsyncIterable<BetaMess
|
|
|
607
607
|
return snapshot;
|
|
608
608
|
case 'content_block_start':
|
|
609
609
|
snapshot.content.push(event.content_block);
|
|
610
|
+
if (event.content_block.type === 'fallback') {
|
|
611
|
+
// the final hop's fallback block names the model that served the response —
|
|
612
|
+
// keeps the snapshot consistent with the relabeled non-streaming message
|
|
613
|
+
snapshot.model = event.content_block.to.model;
|
|
614
|
+
}
|
|
610
615
|
return snapshot;
|
|
611
616
|
case 'content_block_delta': {
|
|
612
617
|
const snapshotContent = snapshot.content.at(event.index);
|