@wabot-dev/framework 0.1.0-beta.13 → 0.1.0-beta.15

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.
Files changed (43) hide show
  1. package/dist/src/ai/claude/ClaudeChatBotAdapter.js +1 -3
  2. package/dist/src/core/Entity.js +1 -1
  3. package/dist/src/index.d.ts +1 -1
  4. package/dist/src/index.js +1 -0
  5. package/package.json +1 -1
  6. package/dist/src/node_modules/@anthropic-ai/sdk/_vendor/partial-json-parser/parser.js +0 -221
  7. package/dist/src/node_modules/@anthropic-ai/sdk/client.js +0 -540
  8. package/dist/src/node_modules/@anthropic-ai/sdk/core/api-promise.js +0 -74
  9. package/dist/src/node_modules/@anthropic-ai/sdk/core/error.js +0 -100
  10. package/dist/src/node_modules/@anthropic-ai/sdk/core/pagination.js +0 -119
  11. package/dist/src/node_modules/@anthropic-ai/sdk/core/resource.js +0 -8
  12. package/dist/src/node_modules/@anthropic-ai/sdk/core/streaming.js +0 -283
  13. package/dist/src/node_modules/@anthropic-ai/sdk/internal/constants.js +0 -16
  14. package/dist/src/node_modules/@anthropic-ai/sdk/internal/decoders/jsonl.js +0 -37
  15. package/dist/src/node_modules/@anthropic-ai/sdk/internal/decoders/line.js +0 -110
  16. package/dist/src/node_modules/@anthropic-ai/sdk/internal/detect-platform.js +0 -159
  17. package/dist/src/node_modules/@anthropic-ai/sdk/internal/errors.js +0 -37
  18. package/dist/src/node_modules/@anthropic-ai/sdk/internal/headers.js +0 -71
  19. package/dist/src/node_modules/@anthropic-ai/sdk/internal/parse.js +0 -53
  20. package/dist/src/node_modules/@anthropic-ai/sdk/internal/request-options.js +0 -11
  21. package/dist/src/node_modules/@anthropic-ai/sdk/internal/shims.js +0 -86
  22. package/dist/src/node_modules/@anthropic-ai/sdk/internal/to-file.js +0 -94
  23. package/dist/src/node_modules/@anthropic-ai/sdk/internal/tslib.js +0 -14
  24. package/dist/src/node_modules/@anthropic-ai/sdk/internal/uploads.js +0 -113
  25. package/dist/src/node_modules/@anthropic-ai/sdk/internal/utils/bytes.js +0 -27
  26. package/dist/src/node_modules/@anthropic-ai/sdk/internal/utils/env.js +0 -19
  27. package/dist/src/node_modules/@anthropic-ai/sdk/internal/utils/log.js +0 -82
  28. package/dist/src/node_modules/@anthropic-ai/sdk/internal/utils/path.js +0 -76
  29. package/dist/src/node_modules/@anthropic-ai/sdk/internal/utils/sleep.js +0 -4
  30. package/dist/src/node_modules/@anthropic-ai/sdk/internal/utils/uuid.js +0 -16
  31. package/dist/src/node_modules/@anthropic-ai/sdk/internal/utils/values.js +0 -48
  32. package/dist/src/node_modules/@anthropic-ai/sdk/lib/BetaMessageStream.js +0 -588
  33. package/dist/src/node_modules/@anthropic-ai/sdk/lib/MessageStream.js +0 -582
  34. package/dist/src/node_modules/@anthropic-ai/sdk/resources/beta/beta.js +0 -19
  35. package/dist/src/node_modules/@anthropic-ai/sdk/resources/beta/files.js +0 -120
  36. package/dist/src/node_modules/@anthropic-ai/sdk/resources/beta/messages/batches.js +0 -202
  37. package/dist/src/node_modules/@anthropic-ai/sdk/resources/beta/messages/messages.js +0 -85
  38. package/dist/src/node_modules/@anthropic-ai/sdk/resources/beta/models.js +0 -58
  39. package/dist/src/node_modules/@anthropic-ai/sdk/resources/completions.js +0 -21
  40. package/dist/src/node_modules/@anthropic-ai/sdk/resources/messages/batches.js +0 -151
  41. package/dist/src/node_modules/@anthropic-ai/sdk/resources/messages/messages.js +0 -71
  42. package/dist/src/node_modules/@anthropic-ai/sdk/resources/models.js +0 -43
  43. package/dist/src/node_modules/@anthropic-ai/sdk/version.js +0 -3
@@ -1,540 +0,0 @@
1
- import { __classPrivateFieldSet, __classPrivateFieldGet } from './internal/tslib.js';
2
- import { uuid4 } from './internal/utils/uuid.js';
3
- import { isAbsoluteURL, isEmptyObj, safeJSON, validatePositiveInteger } from './internal/utils/values.js';
4
- import { sleep } from './internal/utils/sleep.js';
5
- import { castToError, isAbortError } from './internal/errors.js';
6
- import { isRunningInBrowser, getPlatformHeaders } from './internal/detect-platform.js';
7
- import { getDefaultFetch, CancelReadableStream, ReadableStreamFrom } from './internal/shims.js';
8
- import { FallbackEncoder } from './internal/request-options.js';
9
- import { VERSION } from './version.js';
10
- import { AnthropicError, APIError, APIConnectionError, APIConnectionTimeoutError, APIUserAbortError, NotFoundError, ConflictError, RateLimitError, BadRequestError, AuthenticationError, InternalServerError, PermissionDeniedError, UnprocessableEntityError } from './core/error.js';
11
- import { PagePromise } from './core/pagination.js';
12
- import { toFile } from './internal/to-file.js';
13
- import { Beta } from './resources/beta/beta.js';
14
- import { Completions } from './resources/completions.js';
15
- import { Messages } from './resources/messages/messages.js';
16
- import { Models } from './resources/models.js';
17
- import { APIPromise } from './core/api-promise.js';
18
- import { buildHeaders } from './internal/headers.js';
19
- import { readEnv } from './internal/utils/env.js';
20
- import { parseLogLevel, loggerFor, formatRequestDetails } from './internal/utils/log.js';
21
-
22
- // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
23
- var _BaseAnthropic_instances, _a, _BaseAnthropic_encoder, _BaseAnthropic_baseURLOverridden;
24
- /**
25
- * Base class for Anthropic API clients.
26
- */
27
- class BaseAnthropic {
28
- /**
29
- * API Client for interfacing with the Anthropic API.
30
- *
31
- * @param {string | null | undefined} [opts.apiKey=process.env['ANTHROPIC_API_KEY'] ?? null]
32
- * @param {string | null | undefined} [opts.authToken=process.env['ANTHROPIC_AUTH_TOKEN'] ?? null]
33
- * @param {string} [opts.baseURL=process.env['ANTHROPIC_BASE_URL'] ?? https://api.anthropic.com] - Override the default base URL for the API.
34
- * @param {number} [opts.timeout=10 minutes] - The maximum amount of time (in milliseconds) the client will wait for a response before timing out.
35
- * @param {MergedRequestInit} [opts.fetchOptions] - Additional `RequestInit` options to be passed to `fetch` calls.
36
- * @param {Fetch} [opts.fetch] - Specify a custom `fetch` function implementation.
37
- * @param {number} [opts.maxRetries=2] - The maximum number of times the client will retry a request.
38
- * @param {HeadersLike} opts.defaultHeaders - Default headers to include with every request to the API.
39
- * @param {Record<string, string | undefined>} opts.defaultQuery - Default query parameters to include with every request to the API.
40
- * @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.
41
- */
42
- constructor({ baseURL = readEnv('ANTHROPIC_BASE_URL'), apiKey = readEnv('ANTHROPIC_API_KEY') ?? null, authToken = readEnv('ANTHROPIC_AUTH_TOKEN') ?? null, ...opts } = {}) {
43
- _BaseAnthropic_instances.add(this);
44
- _BaseAnthropic_encoder.set(this, void 0);
45
- const options = {
46
- apiKey,
47
- authToken,
48
- ...opts,
49
- baseURL: baseURL || `https://api.anthropic.com`,
50
- };
51
- if (!options.dangerouslyAllowBrowser && isRunningInBrowser()) {
52
- throw new AnthropicError("It looks like you're running in a browser-like environment.\n\nThis is disabled by default, as it risks exposing your secret API credentials to attackers.\nIf you understand the risks and have appropriate mitigations in place,\nyou can set the `dangerouslyAllowBrowser` option to `true`, e.g.,\n\nnew Anthropic({ apiKey, dangerouslyAllowBrowser: true });\n");
53
- }
54
- this.baseURL = options.baseURL;
55
- this.timeout = options.timeout ?? _a.DEFAULT_TIMEOUT /* 10 minutes */;
56
- this.logger = options.logger ?? console;
57
- const defaultLogLevel = 'warn';
58
- // Set default logLevel early so that we can log a warning in parseLogLevel.
59
- this.logLevel = defaultLogLevel;
60
- this.logLevel =
61
- parseLogLevel(options.logLevel, 'ClientOptions.logLevel', this) ??
62
- parseLogLevel(readEnv('ANTHROPIC_LOG'), "process.env['ANTHROPIC_LOG']", this) ??
63
- defaultLogLevel;
64
- this.fetchOptions = options.fetchOptions;
65
- this.maxRetries = options.maxRetries ?? 2;
66
- this.fetch = options.fetch ?? getDefaultFetch();
67
- __classPrivateFieldSet(this, _BaseAnthropic_encoder, FallbackEncoder);
68
- this._options = options;
69
- this.apiKey = apiKey;
70
- this.authToken = authToken;
71
- }
72
- /**
73
- * Create a new client instance re-using the same options given to the current client with optional overriding.
74
- */
75
- withOptions(options) {
76
- const client = new this.constructor({
77
- ...this._options,
78
- baseURL: this.baseURL,
79
- maxRetries: this.maxRetries,
80
- timeout: this.timeout,
81
- logger: this.logger,
82
- logLevel: this.logLevel,
83
- fetch: this.fetch,
84
- fetchOptions: this.fetchOptions,
85
- apiKey: this.apiKey,
86
- authToken: this.authToken,
87
- ...options,
88
- });
89
- return client;
90
- }
91
- defaultQuery() {
92
- return this._options.defaultQuery;
93
- }
94
- validateHeaders({ values, nulls }) {
95
- if (this.apiKey && values.get('x-api-key')) {
96
- return;
97
- }
98
- if (nulls.has('x-api-key')) {
99
- return;
100
- }
101
- if (this.authToken && values.get('authorization')) {
102
- return;
103
- }
104
- if (nulls.has('authorization')) {
105
- return;
106
- }
107
- throw new Error('Could not resolve authentication method. Expected either apiKey or authToken to be set. Or for one of the "X-Api-Key" or "Authorization" headers to be explicitly omitted');
108
- }
109
- async authHeaders(opts) {
110
- return buildHeaders([await this.apiKeyAuth(opts), await this.bearerAuth(opts)]);
111
- }
112
- async apiKeyAuth(opts) {
113
- if (this.apiKey == null) {
114
- return undefined;
115
- }
116
- return buildHeaders([{ 'X-Api-Key': this.apiKey }]);
117
- }
118
- async bearerAuth(opts) {
119
- if (this.authToken == null) {
120
- return undefined;
121
- }
122
- return buildHeaders([{ Authorization: `Bearer ${this.authToken}` }]);
123
- }
124
- /**
125
- * Basic re-implementation of `qs.stringify` for primitive types.
126
- */
127
- stringifyQuery(query) {
128
- return Object.entries(query)
129
- .filter(([_, value]) => typeof value !== 'undefined')
130
- .map(([key, value]) => {
131
- if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {
132
- return `${encodeURIComponent(key)}=${encodeURIComponent(value)}`;
133
- }
134
- if (value === null) {
135
- return `${encodeURIComponent(key)}=`;
136
- }
137
- throw new AnthropicError(`Cannot stringify type ${typeof value}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`);
138
- })
139
- .join('&');
140
- }
141
- getUserAgent() {
142
- return `${this.constructor.name}/JS ${VERSION}`;
143
- }
144
- defaultIdempotencyKey() {
145
- return `stainless-node-retry-${uuid4()}`;
146
- }
147
- makeStatusError(status, error, message, headers) {
148
- return APIError.generate(status, error, message, headers);
149
- }
150
- buildURL(path, query, defaultBaseURL) {
151
- const baseURL = (!__classPrivateFieldGet(this, _BaseAnthropic_instances, "m", _BaseAnthropic_baseURLOverridden).call(this) && defaultBaseURL) || this.baseURL;
152
- const url = isAbsoluteURL(path) ?
153
- new URL(path)
154
- : new URL(baseURL + (baseURL.endsWith('/') && path.startsWith('/') ? path.slice(1) : path));
155
- const defaultQuery = this.defaultQuery();
156
- if (!isEmptyObj(defaultQuery)) {
157
- query = { ...defaultQuery, ...query };
158
- }
159
- if (typeof query === 'object' && query && !Array.isArray(query)) {
160
- url.search = this.stringifyQuery(query);
161
- }
162
- return url.toString();
163
- }
164
- _calculateNonstreamingTimeout(maxTokens) {
165
- const defaultTimeout = 10 * 60;
166
- const expectedTimeout = (60 * 60 * maxTokens) / 128000;
167
- if (expectedTimeout > defaultTimeout) {
168
- throw new AnthropicError('Streaming is required for operations that may take longer than 10 minutes. ' +
169
- 'See https://github.com/anthropics/anthropic-sdk-typescript#streaming-responses for more details');
170
- }
171
- return defaultTimeout * 1000;
172
- }
173
- /**
174
- * Used as a callback for mutating the given `FinalRequestOptions` object.
175
- */
176
- async prepareOptions(options) { }
177
- /**
178
- * Used as a callback for mutating the given `RequestInit` object.
179
- *
180
- * This is useful for cases where you want to add certain headers based off of
181
- * the request properties, e.g. `method` or `url`.
182
- */
183
- async prepareRequest(request, { url, options }) { }
184
- get(path, opts) {
185
- return this.methodRequest('get', path, opts);
186
- }
187
- post(path, opts) {
188
- return this.methodRequest('post', path, opts);
189
- }
190
- patch(path, opts) {
191
- return this.methodRequest('patch', path, opts);
192
- }
193
- put(path, opts) {
194
- return this.methodRequest('put', path, opts);
195
- }
196
- delete(path, opts) {
197
- return this.methodRequest('delete', path, opts);
198
- }
199
- methodRequest(method, path, opts) {
200
- return this.request(Promise.resolve(opts).then((opts) => {
201
- return { method, path, ...opts };
202
- }));
203
- }
204
- request(options, remainingRetries = null) {
205
- return new APIPromise(this, this.makeRequest(options, remainingRetries, undefined));
206
- }
207
- async makeRequest(optionsInput, retriesRemaining, retryOfRequestLogID) {
208
- const options = await optionsInput;
209
- const maxRetries = options.maxRetries ?? this.maxRetries;
210
- if (retriesRemaining == null) {
211
- retriesRemaining = maxRetries;
212
- }
213
- await this.prepareOptions(options);
214
- const { req, url, timeout } = await this.buildRequest(options, {
215
- retryCount: maxRetries - retriesRemaining,
216
- });
217
- await this.prepareRequest(req, { url, options });
218
- /** Not an API request ID, just for correlating local log entries. */
219
- const requestLogID = 'log_' + ((Math.random() * (1 << 24)) | 0).toString(16).padStart(6, '0');
220
- const retryLogStr = retryOfRequestLogID === undefined ? '' : `, retryOf: ${retryOfRequestLogID}`;
221
- const startTime = Date.now();
222
- loggerFor(this).debug(`[${requestLogID}] sending request`, formatRequestDetails({
223
- retryOfRequestLogID,
224
- method: options.method,
225
- url,
226
- options,
227
- headers: req.headers,
228
- }));
229
- if (options.signal?.aborted) {
230
- throw new APIUserAbortError();
231
- }
232
- const controller = new AbortController();
233
- const response = await this.fetchWithTimeout(url, req, timeout, controller).catch(castToError);
234
- const headersTime = Date.now();
235
- if (response instanceof Error) {
236
- const retryMessage = `retrying, ${retriesRemaining} attempts remaining`;
237
- if (options.signal?.aborted) {
238
- throw new APIUserAbortError();
239
- }
240
- // detect native connection timeout errors
241
- // deno throws "TypeError: error sending request for url (https://example/): client error (Connect): tcp connect error: Operation timed out (os error 60): Operation timed out (os error 60)"
242
- // undici throws "TypeError: fetch failed" with cause "ConnectTimeoutError: Connect Timeout Error (attempted address: example:443, timeout: 1ms)"
243
- // others do not provide enough information to distinguish timeouts from other connection errors
244
- const isTimeout = isAbortError(response) ||
245
- /timed? ?out/i.test(String(response) + ('cause' in response ? String(response.cause) : ''));
246
- if (retriesRemaining) {
247
- loggerFor(this).info(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} - ${retryMessage}`);
248
- loggerFor(this).debug(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} (${retryMessage})`, formatRequestDetails({
249
- retryOfRequestLogID,
250
- url,
251
- durationMs: headersTime - startTime,
252
- message: response.message,
253
- }));
254
- return this.retryRequest(options, retriesRemaining, retryOfRequestLogID ?? requestLogID);
255
- }
256
- loggerFor(this).info(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} - error; no more retries left`);
257
- loggerFor(this).debug(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} (error; no more retries left)`, formatRequestDetails({
258
- retryOfRequestLogID,
259
- url,
260
- durationMs: headersTime - startTime,
261
- message: response.message,
262
- }));
263
- if (isTimeout) {
264
- throw new APIConnectionTimeoutError();
265
- }
266
- throw new APIConnectionError({ cause: response });
267
- }
268
- const specialHeaders = [...response.headers.entries()]
269
- .filter(([name]) => name === 'request-id')
270
- .map(([name, value]) => ', ' + name + ': ' + JSON.stringify(value))
271
- .join('');
272
- const responseInfo = `[${requestLogID}${retryLogStr}${specialHeaders}] ${req.method} ${url} ${response.ok ? 'succeeded' : 'failed'} with status ${response.status} in ${headersTime - startTime}ms`;
273
- if (!response.ok) {
274
- const shouldRetry = await this.shouldRetry(response);
275
- if (retriesRemaining && shouldRetry) {
276
- const retryMessage = `retrying, ${retriesRemaining} attempts remaining`;
277
- // We don't need the body of this response.
278
- await CancelReadableStream(response.body);
279
- loggerFor(this).info(`${responseInfo} - ${retryMessage}`);
280
- loggerFor(this).debug(`[${requestLogID}] response error (${retryMessage})`, formatRequestDetails({
281
- retryOfRequestLogID,
282
- url: response.url,
283
- status: response.status,
284
- headers: response.headers,
285
- durationMs: headersTime - startTime,
286
- }));
287
- return this.retryRequest(options, retriesRemaining, retryOfRequestLogID ?? requestLogID, response.headers);
288
- }
289
- const retryMessage = shouldRetry ? `error; no more retries left` : `error; not retryable`;
290
- loggerFor(this).info(`${responseInfo} - ${retryMessage}`);
291
- const errText = await response.text().catch((err) => castToError(err).message);
292
- const errJSON = safeJSON(errText);
293
- const errMessage = errJSON ? undefined : errText;
294
- loggerFor(this).debug(`[${requestLogID}] response error (${retryMessage})`, formatRequestDetails({
295
- retryOfRequestLogID,
296
- url: response.url,
297
- status: response.status,
298
- headers: response.headers,
299
- message: errMessage,
300
- durationMs: Date.now() - startTime,
301
- }));
302
- const err = this.makeStatusError(response.status, errJSON, errMessage, response.headers);
303
- throw err;
304
- }
305
- loggerFor(this).info(responseInfo);
306
- loggerFor(this).debug(`[${requestLogID}] response start`, formatRequestDetails({
307
- retryOfRequestLogID,
308
- url: response.url,
309
- status: response.status,
310
- headers: response.headers,
311
- durationMs: headersTime - startTime,
312
- }));
313
- return { response, options, controller, requestLogID, retryOfRequestLogID, startTime };
314
- }
315
- getAPIList(path, Page, opts) {
316
- return this.requestAPIList(Page, { method: 'get', path, ...opts });
317
- }
318
- requestAPIList(Page, options) {
319
- const request = this.makeRequest(options, null, undefined);
320
- return new PagePromise(this, request, Page);
321
- }
322
- async fetchWithTimeout(url, init, ms, controller) {
323
- const { signal, method, ...options } = init || {};
324
- if (signal)
325
- signal.addEventListener('abort', () => controller.abort());
326
- const timeout = setTimeout(() => controller.abort(), ms);
327
- const isReadableBody = (globalThis.ReadableStream && options.body instanceof globalThis.ReadableStream) ||
328
- (typeof options.body === 'object' && options.body !== null && Symbol.asyncIterator in options.body);
329
- const fetchOptions = {
330
- signal: controller.signal,
331
- ...(isReadableBody ? { duplex: 'half' } : {}),
332
- method: 'GET',
333
- ...options,
334
- };
335
- if (method) {
336
- // Custom methods like 'patch' need to be uppercased
337
- // See https://github.com/nodejs/undici/issues/2294
338
- fetchOptions.method = method.toUpperCase();
339
- }
340
- try {
341
- // use undefined this binding; fetch errors if bound to something else in browser/cloudflare
342
- return await this.fetch.call(undefined, url, fetchOptions);
343
- }
344
- finally {
345
- clearTimeout(timeout);
346
- }
347
- }
348
- async shouldRetry(response) {
349
- // Note this is not a standard header.
350
- const shouldRetryHeader = response.headers.get('x-should-retry');
351
- // If the server explicitly says whether or not to retry, obey.
352
- if (shouldRetryHeader === 'true')
353
- return true;
354
- if (shouldRetryHeader === 'false')
355
- return false;
356
- // Retry on request timeouts.
357
- if (response.status === 408)
358
- return true;
359
- // Retry on lock timeouts.
360
- if (response.status === 409)
361
- return true;
362
- // Retry on rate limits.
363
- if (response.status === 429)
364
- return true;
365
- // Retry internal errors.
366
- if (response.status >= 500)
367
- return true;
368
- return false;
369
- }
370
- async retryRequest(options, retriesRemaining, requestLogID, responseHeaders) {
371
- let timeoutMillis;
372
- // Note the `retry-after-ms` header may not be standard, but is a good idea and we'd like proactive support for it.
373
- const retryAfterMillisHeader = responseHeaders?.get('retry-after-ms');
374
- if (retryAfterMillisHeader) {
375
- const timeoutMs = parseFloat(retryAfterMillisHeader);
376
- if (!Number.isNaN(timeoutMs)) {
377
- timeoutMillis = timeoutMs;
378
- }
379
- }
380
- // About the Retry-After header: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After
381
- const retryAfterHeader = responseHeaders?.get('retry-after');
382
- if (retryAfterHeader && !timeoutMillis) {
383
- const timeoutSeconds = parseFloat(retryAfterHeader);
384
- if (!Number.isNaN(timeoutSeconds)) {
385
- timeoutMillis = timeoutSeconds * 1000;
386
- }
387
- else {
388
- timeoutMillis = Date.parse(retryAfterHeader) - Date.now();
389
- }
390
- }
391
- // If the API asks us to wait a certain amount of time (and it's a reasonable amount),
392
- // just do what it says, but otherwise calculate a default
393
- if (!(timeoutMillis && 0 <= timeoutMillis && timeoutMillis < 60 * 1000)) {
394
- const maxRetries = options.maxRetries ?? this.maxRetries;
395
- timeoutMillis = this.calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries);
396
- }
397
- await sleep(timeoutMillis);
398
- return this.makeRequest(options, retriesRemaining - 1, requestLogID);
399
- }
400
- calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries) {
401
- const initialRetryDelay = 0.5;
402
- const maxRetryDelay = 8.0;
403
- const numRetries = maxRetries - retriesRemaining;
404
- // Apply exponential backoff, but not more than the max.
405
- const sleepSeconds = Math.min(initialRetryDelay * Math.pow(2, numRetries), maxRetryDelay);
406
- // Apply some jitter, take up to at most 25 percent of the retry time.
407
- const jitter = 1 - Math.random() * 0.25;
408
- return sleepSeconds * jitter * 1000;
409
- }
410
- calculateNonstreamingTimeout(maxTokens, maxNonstreamingTokens) {
411
- const maxTime = 60 * 60 * 1000; // 10 minutes
412
- const defaultTime = 60 * 10 * 1000; // 10 minutes
413
- const expectedTime = (maxTime * maxTokens) / 128000;
414
- if (expectedTime > defaultTime || (maxNonstreamingTokens != null && maxTokens > maxNonstreamingTokens)) {
415
- throw new AnthropicError('Streaming is required for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#long-requests for more details');
416
- }
417
- return defaultTime;
418
- }
419
- async buildRequest(inputOptions, { retryCount = 0 } = {}) {
420
- const options = { ...inputOptions };
421
- const { method, path, query, defaultBaseURL } = options;
422
- const url = this.buildURL(path, query, defaultBaseURL);
423
- if ('timeout' in options)
424
- validatePositiveInteger('timeout', options.timeout);
425
- options.timeout = options.timeout ?? this.timeout;
426
- const { bodyHeaders, body } = this.buildBody({ options });
427
- const reqHeaders = await this.buildHeaders({ options: inputOptions, method, bodyHeaders, retryCount });
428
- const req = {
429
- method,
430
- headers: reqHeaders,
431
- ...(options.signal && { signal: options.signal }),
432
- ...(globalThis.ReadableStream &&
433
- body instanceof globalThis.ReadableStream && { duplex: 'half' }),
434
- ...(body && { body }),
435
- ...(this.fetchOptions ?? {}),
436
- ...(options.fetchOptions ?? {}),
437
- };
438
- return { req, url, timeout: options.timeout };
439
- }
440
- async buildHeaders({ options, method, bodyHeaders, retryCount, }) {
441
- let idempotencyHeaders = {};
442
- if (this.idempotencyHeader && method !== 'get') {
443
- if (!options.idempotencyKey)
444
- options.idempotencyKey = this.defaultIdempotencyKey();
445
- idempotencyHeaders[this.idempotencyHeader] = options.idempotencyKey;
446
- }
447
- const headers = buildHeaders([
448
- idempotencyHeaders,
449
- {
450
- Accept: 'application/json',
451
- 'User-Agent': this.getUserAgent(),
452
- 'X-Stainless-Retry-Count': String(retryCount),
453
- ...(options.timeout ? { 'X-Stainless-Timeout': String(Math.trunc(options.timeout / 1000)) } : {}),
454
- ...getPlatformHeaders(),
455
- ...(this._options.dangerouslyAllowBrowser ?
456
- { 'anthropic-dangerous-direct-browser-access': 'true' }
457
- : undefined),
458
- 'anthropic-version': '2023-06-01',
459
- },
460
- await this.authHeaders(options),
461
- this._options.defaultHeaders,
462
- bodyHeaders,
463
- options.headers,
464
- ]);
465
- this.validateHeaders(headers);
466
- return headers.values;
467
- }
468
- buildBody({ options: { body, headers: rawHeaders } }) {
469
- if (!body) {
470
- return { bodyHeaders: undefined, body: undefined };
471
- }
472
- const headers = buildHeaders([rawHeaders]);
473
- if (
474
- // Pass raw type verbatim
475
- ArrayBuffer.isView(body) ||
476
- body instanceof ArrayBuffer ||
477
- body instanceof DataView ||
478
- (typeof body === 'string' &&
479
- // Preserve legacy string encoding behavior for now
480
- headers.values.has('content-type')) ||
481
- // `Blob` is superset of `File`
482
- body instanceof Blob ||
483
- // `FormData` -> `multipart/form-data`
484
- body instanceof FormData ||
485
- // `URLSearchParams` -> `application/x-www-form-urlencoded`
486
- body instanceof URLSearchParams ||
487
- // Send chunked stream (each chunk has own `length`)
488
- (globalThis.ReadableStream && body instanceof globalThis.ReadableStream)) {
489
- return { bodyHeaders: undefined, body: body };
490
- }
491
- else if (typeof body === 'object' &&
492
- (Symbol.asyncIterator in body ||
493
- (Symbol.iterator in body && 'next' in body && typeof body.next === 'function'))) {
494
- return { bodyHeaders: undefined, body: ReadableStreamFrom(body) };
495
- }
496
- else {
497
- return __classPrivateFieldGet(this, _BaseAnthropic_encoder, "f").call(this, { body, headers });
498
- }
499
- }
500
- }
501
- _a = BaseAnthropic, _BaseAnthropic_encoder = new WeakMap(), _BaseAnthropic_instances = new WeakSet(), _BaseAnthropic_baseURLOverridden = function _BaseAnthropic_baseURLOverridden() {
502
- return this.baseURL !== 'https://api.anthropic.com';
503
- };
504
- BaseAnthropic.Anthropic = _a;
505
- BaseAnthropic.HUMAN_PROMPT = '\n\nHuman:';
506
- BaseAnthropic.AI_PROMPT = '\n\nAssistant:';
507
- BaseAnthropic.DEFAULT_TIMEOUT = 600000; // 10 minutes
508
- BaseAnthropic.AnthropicError = AnthropicError;
509
- BaseAnthropic.APIError = APIError;
510
- BaseAnthropic.APIConnectionError = APIConnectionError;
511
- BaseAnthropic.APIConnectionTimeoutError = APIConnectionTimeoutError;
512
- BaseAnthropic.APIUserAbortError = APIUserAbortError;
513
- BaseAnthropic.NotFoundError = NotFoundError;
514
- BaseAnthropic.ConflictError = ConflictError;
515
- BaseAnthropic.RateLimitError = RateLimitError;
516
- BaseAnthropic.BadRequestError = BadRequestError;
517
- BaseAnthropic.AuthenticationError = AuthenticationError;
518
- BaseAnthropic.InternalServerError = InternalServerError;
519
- BaseAnthropic.PermissionDeniedError = PermissionDeniedError;
520
- BaseAnthropic.UnprocessableEntityError = UnprocessableEntityError;
521
- BaseAnthropic.toFile = toFile;
522
- /**
523
- * API Client for interfacing with the Anthropic API.
524
- */
525
- class Anthropic extends BaseAnthropic {
526
- constructor() {
527
- super(...arguments);
528
- this.completions = new Completions(this);
529
- this.messages = new Messages(this);
530
- this.models = new Models(this);
531
- this.beta = new Beta(this);
532
- }
533
- }
534
- Anthropic.Completions = Completions;
535
- Anthropic.Messages = Messages;
536
- Anthropic.Models = Models;
537
- Anthropic.Beta = Beta;
538
- const { HUMAN_PROMPT, AI_PROMPT } = Anthropic;
539
-
540
- export { AI_PROMPT, Anthropic, BaseAnthropic, HUMAN_PROMPT };
@@ -1,74 +0,0 @@
1
- import { __classPrivateFieldSet, __classPrivateFieldGet } from '../internal/tslib.js';
2
- import { defaultParseResponse, addRequestID } from '../internal/parse.js';
3
-
4
- // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
5
- var _APIPromise_client;
6
- /**
7
- * A subclass of `Promise` providing additional helper methods
8
- * for interacting with the SDK.
9
- */
10
- class APIPromise extends Promise {
11
- constructor(client, responsePromise, parseResponse = defaultParseResponse) {
12
- super((resolve) => {
13
- // this is maybe a bit weird but this has to be a no-op to not implicitly
14
- // parse the response body; instead .then, .catch, .finally are overridden
15
- // to parse the response
16
- resolve(null);
17
- });
18
- this.responsePromise = responsePromise;
19
- this.parseResponse = parseResponse;
20
- _APIPromise_client.set(this, void 0);
21
- __classPrivateFieldSet(this, _APIPromise_client, client);
22
- }
23
- _thenUnwrap(transform) {
24
- return new APIPromise(__classPrivateFieldGet(this, _APIPromise_client, "f"), this.responsePromise, async (client, props) => addRequestID(transform(await this.parseResponse(client, props), props), props.response));
25
- }
26
- /**
27
- * Gets the raw `Response` instance instead of parsing the response
28
- * data.
29
- *
30
- * If you want to parse the response body but still get the `Response`
31
- * instance, you can use {@link withResponse()}.
32
- *
33
- * 👋 Getting the wrong TypeScript type for `Response`?
34
- * Try setting `"moduleResolution": "NodeNext"` or add `"lib": ["DOM"]`
35
- * to your `tsconfig.json`.
36
- */
37
- asResponse() {
38
- return this.responsePromise.then((p) => p.response);
39
- }
40
- /**
41
- * Gets the parsed response data, the raw `Response` instance and the ID of the request,
42
- * returned via the `request-id` header which is useful for debugging requests and resporting
43
- * issues to Anthropic.
44
- *
45
- * If you just want to get the raw `Response` instance without parsing it,
46
- * you can use {@link asResponse()}.
47
- *
48
- * 👋 Getting the wrong TypeScript type for `Response`?
49
- * Try setting `"moduleResolution": "NodeNext"` or add `"lib": ["DOM"]`
50
- * to your `tsconfig.json`.
51
- */
52
- async withResponse() {
53
- const [data, response] = await Promise.all([this.parse(), this.asResponse()]);
54
- return { data, response, request_id: response.headers.get('request-id') };
55
- }
56
- parse() {
57
- if (!this.parsedPromise) {
58
- this.parsedPromise = this.responsePromise.then((data) => this.parseResponse(__classPrivateFieldGet(this, _APIPromise_client, "f"), data));
59
- }
60
- return this.parsedPromise;
61
- }
62
- then(onfulfilled, onrejected) {
63
- return this.parse().then(onfulfilled, onrejected);
64
- }
65
- catch(onrejected) {
66
- return this.parse().catch(onrejected);
67
- }
68
- finally(onfinally) {
69
- return this.parse().finally(onfinally);
70
- }
71
- }
72
- _APIPromise_client = new WeakMap();
73
-
74
- export { APIPromise };